|
Message Closed
modified 23-Nov-14 6:58am.
|
|
|
|
|
Thanks for all, but i mean how to send a packet, like example 09 at SharpPcap, but here i need to write the contents of the packet and sending it to specific host, here i need to write the IP address of the destination(that host)..............
Regards
|
|
|
|
|
I'm having trouble grasping the value of properties and the get/set accessors in C#. In my reading, typical examples are structured as:
public class SomeClass()
{
private int myProperty;
public int MyProperty
{
get {return myProperty;}
set {myProperty = value;)
}
}
I'm using this feature for the first time in a form that is created by a main form, and every data member collected by the child form is to be returned to the main form. The VS 2008 Designer did all the hard work for me, for which I'm duly grateful, but it created all the form data members as private, and the parent form can't access them. In keeping with what seems to be the preferred design philosophy of C#, I'm busy filling in public get/set accessor pairs for each member so the parent form can retrieve the data, but it seems kind of silly to me. Why not just make all the data members public and be done with it?
I realize this is quite a simple example, as it's my first serious attempt to make something useful with C#, but I really don't see the value of this construct. Can someone explain or provide examples of situations that would make this useful?
"A Journey of a Thousand Rest Stops Begins with a Single Movement"
|
|
|
|
|
In that case you're not getting much benefit; so you could make it an automatic property instead:
public class SomeClass()
{
public int MyProperty { get ; set ; }
}
Or you can make it read-only with:
public class SomeClass()
{
public int MyProperty { get ; private set ; }
}
But some times you need to do more work in a Property:
public class SomeClass()
{
private int myProperty;
public int MyProperty
{
get {return myProperty;}
set
{
if ( value <= 0 )
{
throw something ;
}
myProperty = value;
}
}
}
|
|
|
|
|
PIEBALDconsult wrote: you could make it an automatic property instead:
Hot damn! I haven't seen that notation anywhere. That saves a bunch of typing! But, given my example, how does this construct "know" to associate the public MyProperty with the private myProperty? Most of my data members are textboxes, with the pairing txtProperty.Text <=> Property.
PIEBALDconsult wrote: some times you need to do more work in a Property
So I can use the property accessor to do validation? Cool!
I guess, too, that there might be times when many of a class's data members contain internal states that should not be tampered with during the object's lifetime. That would necessitate some means of shielding the data, perhaps in the case of modelling a state machine or some such object far beyond my current skill level.
Thanks a bunch!
"A Journey of a Thousand Rest Stops Begins with a Single Movement"
|
|
|
|
|
There are also other useful 'properties' of properties. A couple that spring to mind are...
Properties can be serialized by the designer, fields cannot.
Because property getters and setters are methods, we can do other stuff such as raising events if the underlying value changes, as well as validation. Consider this component's code:
using System;
using System.ComponentModel;
public class PercentageControl : Component
{
private const int DefaultPercentage = 50;
public const int MaxPercentage = 100;
public const int MinPercentage = 0;
public event EventHandler PercentageChanged;
private int percentage;
public PercentageControl()
{
percentage = DefaultPercentage;
}
[DefaultValue(50)]
public int Percentage
{
get { return percentage; }
set
{
if (value >= MinPercentage && value <= MaxPercentage)
{
if (value != percentage)
{
percentage = value;
OnPercentageChanged(EventArgs.Empty);
}
}
else
{
throw new ArgumentOutOfRangeException(
"Percentage",
string.Format("Percentage must be between {0} and {1}",
MinPercentage, MaxPercentage));
}
}
}
protected virtual void OnPercentageChanged(EventArgs e)
{
EventHandler eh = PercentageChanged;
if (eh != null)
eh(this, e);
}
} If you create a winforms project, add this code, build and then drop a PercentageControl from the toolbox onto the form, whenever the Percentage property isn't 50, the form's .Designer.cs will change and store the new property value for you so it can be set to the design time value at runtime.
If you subscribe to the PercentageChanged event, you will see it is raised whenever the Percentage property's value is changed.
Dave
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) Why are you using VB6? Do you hate yourself? (Christian Graus)
|
|
|
|
|
Sweet!
"A Journey of a Thousand Rest Stops Begins with a Single Movement"
|
|
|
|
|
Roger Wright wrote: how does this construct "know" to associate the public MyProperty with the private myProperty
It doesn't; with an Automatic Property you don't create the field, the compiler does. If you do have to create the field for some reason (as with a Control on a Form) you wouldn't use an Automatic Property.
|
|
|
|
|
Roger Wright wrote: ...created all the form data members as private
Are you refering to controls? Textbox, Combobox, etc.
It is important for these to private by default, because it would open up a hugh security hole.
As far as the value of a property itself, it can be very useful when you are wanting to validate the input. Say for instance you had a class named Car. The max speed that the car could go was 120 mph.
Using "set", you could make sure that no speed was set above the maximum allowable speed.
public class Car
{
private const byte MAX_SPEED = 120;
public byte Speed
{
get { return _Speed; }
set
{
if (value > MAX_SPEED)
throw new ArgumentException("Speed cannot exceed: " + MAX_SPEED.ToString());
else
_Speed = value
}
}
}
Does this help? By the way a property is compiled into two methods. get_Speed() and set_Speed(). Properties are just C# short hand for these two methods.
Cheers!
Richard
If my answer has helped you, one of my articles may also be a help. Also remember that your best friend's name is google.
|
|
|
|
|
Thank you, Richard!
I'm old, and all the clarification available helps me learn. And yes, the child form is populated by controls for data entry. The parent form is primarily a menu for the functions available to the user. I plan to use the child forms for gathering data, the main form for consolidating that information, and dispatching it to a database utility class containing methods for maintaining the database.
Richard Blythe wrote: By the way a property is compiled into two methods. get_Speed() and set_Speed().
That's new information, not included in any book I've read. It aids my understanding to know what's going on behind the scenes. Thanks, again!
"A Journey of a Thousand Rest Stops Begins with a Single Movement"
|
|
|
|
|
Ah, so old dogs can learn new tricks!
One fundamental rule to professional programming is separating your UI code from your business logic.
For example, if you was writing those child forms for me, I wouldn't want to access a field by the control. I would want to access a meaningful field name. For example:
EmployeeForm.EmployeeName
looks much better than:
EmployeeForm.NameTextBox.Text
This is where a good property would work great:
public string EmployeeName
{
get { return NameTextBox.Text; }
set
{
if (value == "")
throw new ArgumentException("Employee name cannot be empty!")
else
NameTextBox.Text = value;
}
}
I wish you the best. Just remember me when you become a millionare!
If my answer has helped you, one of my articles may also be a help. Also remember that your best friend's name is google.
|
|
|
|
|
Nice to know I did something right. My controls are named as txtSerial, but my properties follow as Serial. It does make it more readable, and in this case, Serial corresponds to a database field name directly. I'm trying to get the UI and business logic working the way I want them to before I even touch the database functions; I have a feeling that this is where the nightmares begin. Mycroft sent me some samples of how he would implement it, and I plan to study that this weekend before I attempt to tackle it myself.
Richard Blythe wrote: so old dogs can learn new tricks!
Yes, but we're slow, and tend to bite. Thanks for your patience...
"A Journey of a Thousand Rest Stops Begins with a Single Movement"
|
|
|
|
|
Roger Wright wrote: Question About Class Properties
Dito all for structs.
|
|
|
|
|
I am having a little bit of a problem. I am trying to get installed software from computers. The problem is when running it from a x86 machine it defaults to the wow6432node on the x64 server. What I really need is to read both the regular AND the wow6432node for all software installed on the machine.
Here is what I am doing:
string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
try
{
Microsoft.Win32.RegistryKey key = Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.LocalMachine,
dnsName.ToString());
Microsoft.Win32.RegistryKey subKey = key.OpenSubKey(registryKey);
foreach (string foundValues in subKey.GetSubKeyNames())
{
Microsoft.Win32.RegistryKey val = subKey.OpenSubKey(foundValues);
if (!(val.GetValue("DisplayName") == null))
{
ListViewItem item = new ListViewItem();
item.Text = val.GetValue("DisplayName").ToString();
if (val.GetValue("InstallLocation") != null)
item.SubItems.Add(val.GetValue("InstallLocation").ToString());
Invoke((Action)(() => { lstApplications.Items.Add(item); }));
}
}
}
catch (Exception) { }
finally
{
Invoke((Action)(() => { picProgressApps.Visible = false; }));
}
|
|
|
|
|
You're trying to read the 64-bit registry from a 32-bit machine?? You have to do it from a 64-bit app running on a 64-bit machine for that to work.
If you want to know what's installed on a machine in a more generic way, use WMI instead. Google for "Win32_Product" and "Win32_QuickFixEngineering" to get installed software and HotFixes.
|
|
|
|
|
Thanks! I was actually reading about WMI after I posted my first discussion. I took a look at http://msdn.microsoft.com/en-us/library/aa394378(VS.85).aspx[^] and it has everything I need! I was able to read only from the wow6432node with the previous code but with WMI it lets me read all installed software
Does the WMI do basically the same in checking uninstallers or is it checking installed applications some other way? I guess I'm wondering why WMI can do it but remote registry can't
|
|
|
|
|
The WMI query executes on the remote machine, in it's native envrironment, not on your machine. The results are packed into standardized, platform independant objects (WMI classes) and returned to the caller. That's why it works and reading the registry directly doesn't.
|
|
|
|
|
Ohh I see. Thank you for explaining that to me.
Have a good day!
|
|
|
|
|
I am writing a program that is going to be operated with an IR controller. In the program Form1 creates a new form Form2.
Form2 dlg = new Form2(fname);
if (dlg.ShowDialog() == DialogResult.OK)
{
}
Unfortunatly the new form will not receive input unless I click on it with the mouse to make it active. I have tried various commands but in order to make the new form receive the IR commands I must click on the form with the mouse. How can I activate the form programatically.
public Form2(string temp)
{
InitializeComponent();
//this.Focus(); // Tried these
//this.Activate();
//this.BringToFront();
}
|
|
|
|
|
Hi George,
electriac wrote: the new form will not receive input unless I click on it
I don't think this is correct. What probably happened is the Control with the lowest TabIndex isn't the one you want it to be. Try playing around with TabIndex (and check TabStop is still at its default value of true).
If all that does not help, experiment with Focus, Activate, BringToFront inside the Shown handler, the constructor is too soon for these.
Regards,
|
|
|
|
|
Tried delaying commands with a timer. NG. Unless I click on the form the IR commands are written to my source code. So the compiler is the active form.
|
|
|
|
|
electriac wrote: the compiler is the active form
Each WinForm application has an active window; what you are saying is somehow your IDE (Visual Studio?) is active instead of your app itself. That is abnormal; what do you do to make your app run? what language is it in? it is a WinForm app isn't it? what happens when you run your app by double-clicking its exe (in bin/debug/ or in bin/release/ subfolders)?
BTW: within the app, i.e. assuming your app has focus, it is the Shown event you want, not a timer!
|
|
|
|
|
I am compiling and executing with CTRL F5 it is a standard windows form in C#. I will have to look into executing outside the compiler.
TNX Luc
|
|
|
|
|
I don't know how useful this may be, as I'm a total newbie to C#, but I'm working tonight on the exact same situation - a form creating a form - and mine's working perfectly. The only difference I see is that, rather than passing a value in the new statement, I'm initializing that value in a separate statement immediately after, ie:
Form2 dlg = new Form2();
dlg.temp = fname;
if(dlg.ShowDialog()==DialogResult.OK)
{ ...
This assumes that Form2 defines a public member temp, of course. I have no idea why it would make a difference, but it just might.
"A Journey of a Thousand Rest Stops Begins with a Single Movement"
|
|
|
|
|
electriac wrote: Unfortunatly the new form will not receive input
What do you mean by this ? Do you have a textbox in your form that doesn't receive what you type on the keyboard as soon as the form is opened? You may have to set its TabIndex property to 0 and TabStop to true .
|
|
|
|