how to implement autoimplemented properties in C# for setting a value - c#

I am trying to use autoimplemented properties.
It shows me error
public OpenMode OpenFor
{
get;//must declare a body because it is not marked as abstract, partial or external. Why so
set
{
if (value == OpenMode.Add)
{
btnAddGuest.Text = "Save";
btnUpdatePreference.Visible = false;
dgvGuestInfo.ClearSelection();
}
else if (value == OpenMode.Update)
{
btnAddGuest.Text = "Update";
btnUpdatePreference.Visible = true;
}
}
}

You must implement both a getter and setter if you implement one of them. You can auto implement only both:
public OpenMode OpenFor
{
get;
set;
}
You may consider to use a backing field:
private OpenMode openFor;
public OpenMode OpenFor
{
get
{
return openFor;
}
set
{
openFor = value;
//...
}
}

autoimplementation works only for the simple usecase that set and get have no custom body

To use just get; you need to use just set; as well. In this case you'd have an implicit variable. When you declare a body for set, that doesn't work. Ask yourself the question; how can you get anything you can never set?

private OpenMode _openFor;
public OpenMode OpenFor
{
get{return _openFor;}
set{
_openFor = value;
SetOpenFor(value);
}
}
private void SetOpenFor(OpenMode mode)
{
if (mode== OpenMode.Add)
{
btnAddGuest.Text = "Save";
btnUpdatePreference.Visible = false;
dgvGuestInfo.ClearSelection();
}
else if (mode == OpenMode.Update)
{
btnAddGuest.Text = "Update";
btnUpdatePreference.Visible = true;
}
}

Also note that the auto-implemented properties also listen to access modifiers:
public string Foo { get; private set; }
Though you still need to define both.
In your example, it looks like you don't need the get. You aren't storing the value into a local field either, so it looks like your property should be a method.
Alternatively, your get could infer the value from the state of the buttons you are modifying in the set - but this is starting to get silly.

Related

How to get a property value of a class defined inside of another class through a reflection

I have a MerchantWSBO and MerchantWSVO classes.
MerchantWSBO has a property of a type of MerchantWSVO.
I need to get a value of the property of a MerchantWSVO.
So, I have a code defining both classes(classes are coming through a WebReference from a 3rd party)
public MerchantWSBO {
private MerchantWSVO overviewField;
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public MerchantWSVO overview {
get {
return this.overviewField;
}
set {
this.overviewField = value;
}
}
}
public MerchantWSVO{
private System.Nullable<bool> discoverRetainedField;
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool discoverRetainedSpecified {
get {
return this.discoverRetainedFieldSpecified;
}
set {
this.discoverRetainedFieldSpecified = value;
}
}
}
I have the following method where I need to get the property value of dicoverRetained using reflection:
private string ClassToXML(Object classObject)
{
MerchantTest mt = new MerchantTest();
if(classObject is MerchantWSBO)
{
classObject.GetType().GetProperty("overviewField").GetValue(new MerchantWSVO, null);
mt.overview.discoverRetained = //need to get the value
}
var myString = new System.IO.StringWriter();
var serializer = new XmlSerializer(classObject.GetType());
serializer.Serialize(myString, classObject);
return myString.ToString();
}
Based on a parameter classObject which in this case can be of two types, I need to get a value from a property.
How can I do that?
You don't need reflection at all, simply cast the object to the correct type. Pattern matching helps here.
if(classObject is MerchantWSBO wsbo)
{
Console.WriteLine(wsbo.overview.discoverRetained);
}
or on older C# versions:
var wsbo = classObject as MerchantWSBO;
if(wsbo != null)
{
Console.WriteLine(wsbo.overview.discoverRetained);
}

Adding a bool for each property

I'm building a c# class that works with two different data sources. It will load a data source and take a configuration set from a function. Then I want to do several tasks on all properties within the object.
for example.
public String StreetAddress
{
get { return _streetAddress; }
set
{
if (value.Length <= 64)
_streetAddress = value;
else
_streetAddress = value.Substring(0, 1024).Trim();
}
}
public String City
{
get { return _city; }
set
{
if (value.Length <= 128)
_city = value;
else
_city = value.Substring(0, 128).Trim();
}
}
public String State
{
get { return _state; }
set
{
if (value.Length <= 128)
_state = value;
else
_state = value.Substring(0, 128).Trim();
}
}
So that holds the data from one side. I was hoping to be able to store and set a change flag on each property. So if we take State for example. If the person is moved from Texas to Illinois I want to set a bool within that property to note the change then be able to loop over all changes before saving the object to the DB. But I don't see any way to assign another state variable within that property. Is the best way to write another object on top of this to control it or is there another more creative way to store multiple strings within the one property?
If you'd like an OOP way of doing the thing, you can:
Define an interface and a class for holding your property, such as:
interface IPropertySlot
{
bool IsDirty { get; }
void ResetIsDirty();
object UntypedValue { get; }
}
class PropertySlot<T>:IPropertySlot
{
public T Value { get; private set; }
public bool SetValue(T value)
{
if (!Equals(_value, Value))
{
Value = value;
IsDirty = true;
return true;
}
return false;
}
public bool IsDirty { get; private set; }
public void ResetIsDirty()
{
IsDirty = false;
}
public object UntypedValue
{
get { return Value; }
}
}
Store your properties inside your class in a dictionary from String (for name of property) to IPropertySlot and get/set them through a pair of methods:
void SetProperty<T>(string name, T value)
{
IPropertySlot property;
if (!_properties.TryGetValue(name, out property))
{
property = new PropertySlot<T>();
_properties[name] = property;
}
((PropertySlot<T>)property) .SetValue(value);
}
T GetProperty<T>(string name)
{
IPropertySlot property;
if (!_properties.TryGetValue(name, out property))
{
property = new PropertySlot<T>();
_properties[name] = property;
}
return ((PropertySlot<T>)property).Value;
}
Finding the changed properties later is just a matter of going over the _properties.Values and finding which of them are IsDirty.
This approach also gives you a way to add more functionality to your properties in an OO manner (such as raising PropertyChanged/PropertyChanging events, mapping it to DB fields, etc.).
In such a situation I'd prefer an approach external to the Dto implementation.
Implement some unit that would take two instances of a class, and determine all the differences.
Map each property to compare:
static PropertyManager<Dto> manager = new PropertyManager<Dto>()
.Map(x => x.City)
.Map(x => x.StreetAddress);
Use two instances to compute difference:
var a = new Dto{ StreetAddress = "Foo", City = "Bar" };
var b = new Dto{ StreetAddress = "Foo", City = "Baz" };
var differences = manager.ComputeDifferences(a,b).ToList();
if( differences.Any() )
{
Console.WriteLine("Instances differ");
}
foreach (var diff in differences)
{
Console.WriteLine(diff);
}
This sample code prints out:
Instances differ
x.City
Here is a complete code example:
https://dotnetfiddle.net/4sNeoN

Forcing all WPF bound controls to update with GetBindingExpression().UpdateTarget()

I have a WPF application that includes ~50 controls that are bound to properties on my business object which implements INotifyPropertyChanged. Here's a quick snippet of my business object:
public class MyBusinessObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
// properties begin here
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name == value)
{
return;
}
_name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
// constructor, etc. not shown
}
I also have several validation rules that are used to validate the user input in these controls. I'm using command binding to prevent my user from saving the data if there are any validation errors. My application also includes a "Reset default values" button which, obviously, will reset the default value for all of the properties on my business object. This all works exactly as I'd like it to with one exception. If my user enters invalid data into one or more controls and then clicks the "Reset default values" button, the controls that contain invalid data don't always update as I'd expect. This happens because of the following code in my property setters:
if (_name == value)
{
return;
}
This code exists to prevent unnecessary property changed notifications from occurring when the value entered by my user in the bound UI control is the same value that the property is already set to. As an example, I have an IntegerUpDown control in my UI (this control is part of the Extended WPF Toolkit from Xceed). The default value of the property that my control is bound to is 10. My user deletes the value from the control and my validation rule is triggered which results in a validation error and the UI is updated appropriately with an error adorner, etc. The value of the property that this control is mapped to hasn't been changed so it's still set to 10. Now my user clicks the "Reset default values" button which will result in the default value (10) for the property being reset. However, the value for the property is already set to 10 so the short circuit logic in my setter will return instead of setting the property value.
So now, after my user clicks "Reset default values", I am also forcing an update on my binding target like this:
this.myIntegerUpDown.GetBindingExpression(Xceed.Wpf.Toolkit.IntegerUpDown.ValueProperty).UpdateTarget();
This solves my problem but only for this particular control. Is there any easy way to do this for all of my bound controls without having to specify each one? Thanks.
OnPropertyChanged(new PropertyChangedEventArgs(string.Empty));
This is intended to imply that ALL properties on that object have changed.
Could you do one of the following?
1) Reset the DataContext - Either recreate it, or re-set the property
var context = this.DataContext;
this.DataContext = null;
this.DataContext = context;
2) Loop through all properties programmatically via reflection and manually call OnPropertyChanged with the relevant property names.
var properties = typeof(ViewModel).GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var property in properties)
{
this.OnPropertyChanged(new PropertyChangedEventArgs(property.Name));
}
You've mentioned validation and reset values, and of course the obvious one is to persist it.
Why don't you implement IEditableObject Interface on your entity that has three signature methods. BeginEdit(), CancelEdit() and EndEdit()
That way you can easily roll back your entity to the whatever you want, or validate it and lastly persist it. A good example is found here
Sample code
public class Customer : IEditableObject
{
struct CustomerData
{
internal string id ;
internal string firstName ;
internal string lastName ;
}
private CustomersList parent;
private CustomerData custData;
private CustomerData backupData;
private bool inTxn = false;
// Implements IEditableObject
void IEditableObject.BeginEdit()
{
Console.WriteLine("Start BeginEdit");
if (!inTxn)
{
this.backupData = custData;
inTxn = true;
Console.WriteLine("BeginEdit - " + this.backupData.lastName);
}
Console.WriteLine("End BeginEdit");
}
void IEditableObject.CancelEdit()
{
Console.WriteLine("Start CancelEdit");
if (inTxn)
{
this.custData = backupData;
inTxn = false;
Console.WriteLine("CancelEdit - " + this.custData.lastName);
}
Console.WriteLine("End CancelEdit");
}
void IEditableObject.EndEdit()
{
Console.WriteLine("Start EndEdit" + this.custData.id + this.custData.lastName);
if (inTxn)
{
backupData = new CustomerData();
inTxn = false;
Console.WriteLine("Done EndEdit - " + this.custData.id + this.custData.lastName);
}
Console.WriteLine("End EndEdit");
}
public Customer(string ID) : base()
{
this.custData = new CustomerData();
this.custData.id = ID;
this.custData.firstName = "";
this.custData.lastName = "";
}
public string ID
{
get
{
return this.custData.id;
}
}
public string FirstName
{
get
{
return this.custData.firstName;
}
set
{
this.custData.firstName = value;
this.OnCustomerChanged();
}
}
public string LastName
{
get
{
return this.custData.lastName;
}
set
{
this.custData.lastName = value;
this.OnCustomerChanged();
}
}
internal CustomersList Parent
{
get
{
return parent;
}
set
{
parent = value ;
}
}
private void OnCustomerChanged()
{
if (!inTxn && Parent != null)
{
Parent.CustomerChanged(this);
}
}
public override string ToString()
{
StringWriter sb = new StringWriter();
sb.Write(this.FirstName);
sb.Write(" ");
sb.Write(this.LastName);
return sb.ToString();
}
}
Wouldn't it be easier to just always call OnPropertyChanged regardless of whether its the same? How much of a performance boost does that give you?

Unable to edit values in a DataGridView (using BindingList)

It seems that, due to an unknown cause, I am now unable to edit anything in my DataGridView. The DGV's ReadOnly property value is false, and all columns except for one all have the ReadOnly property set to false as well.
I'm beginning to think that it may be due to a special value I tried adding to one of my classes, one that I only wanted to be modified within the class, but still read only to the public. I don't think that value is messing with anything else, but none the less, here is the relevant portion of my code:
private void loaderWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
loadingBar.Value = e.ProgressPercentage;
if (e.UserState != null)
{
savefiles.Add((SaveFile)e.UserState);
}
}
Where savefiles is a BindingList, and where SaveFile is my class:
public class SaveFile
{
private string d_directory;
private int d_weirdnumber;
private bool d_isautosave;
private string d_fullname;
private string d_datatype;
private string d_owner;
private bool d_isquicksave;
private string d_title;
private string d_gametime;
public SaveFile() { }
public SaveFile(string directory, int weirdnumber, bool isautosave, string fullname, string datatype, string owner, bool isquicksave, string title)
{
d_directory = directory;
d_weirdnumber = weirdnumber;
d_isautosave = isautosave;
d_fullname = fullname;
d_datatype = datatype;
d_owner = owner;
d_isquicksave = isquicksave;
d_title = title;
}
public string Gametime
{
get { return d_gametime; }
}
public string Datatype
{
get { return d_datatype; }
set { d_datatype = value; }
}
public string Title
{
get { return d_title; }
set { d_title = value; }
}
public bool IsQuickSave
{
get { return d_isquicksave; }
set { d_isquicksave = value; }
}
public bool IsAutoSave
{
get { return d_isautosave; }
set { d_isautosave = value; }
}
public string Directory
{
get { return d_directory; }
set { d_directory = value; }
}
public string FullName
{
get { return d_fullname; }
set
{
d_fullname = value;
string[] split = value.Split(new char[]{'-'});
foreach (string str in split)
{
if (System.Text.RegularExpressions.Regex.IsMatch(str, "^\\d\\d:\\d\\d:\\d\\d$"))
{
d_gametime = str;
}
}
}
}
public int Weirdnumber
{
get { return d_weirdnumber; }
set { d_weirdnumber = value; }
}
public string Owner
{
get { return d_owner; }
set { d_owner = value; }
}
}
Gametime is that special property I mentioned earlier. It doesn't have a set function, but according to this, I should be in the clear, right?
Can anyone then tell me why I may not be able to edit any of the DGV cells?
EDIT: I just found out that not setting AutoGenerateColumns to false allows me to edit again, but I still don't know why.
After several hours, a friend finally took a look at it over Remote Desktop. He wrote a function to force all columns to have a non read-only status, and go figure, it worked. So we looked at the column properties in the editor, and somehow... I don't know why... they were all set to Read only. I swear I checked them 4 times before.
The lesson of this story (I guess): When in doubt, check your settings. When not in doubt, become doubtful. Otherwise, file a bug report to Microsoft :\

List/Collection of references to Properties

Consider these properties,
double _temperature;
public double Temperature
{
get { return _temperature; }
set { _temperature = value; }
}
double _humidity;
public double Humidity
{
get { return _humidity; }
set { _humidity = value; }
}
bool _isRaining;
public bool IsRaining
{
get { return _isRaining; }
set { _isRaining = value; }
}
And now I want to make a list/collection/container of properties like this,
PropertyContainer.Add(Temperature); //Line1
PropertyContainer.Add(Humidity); //Line2
PropertyContainer.Add(IsRaining); //Line3
I want to make this such that later on I may be able to access the current values of properties using index, something like this,
object currentTemperature = PropertyContainer[0];
object currentHumidity = PropertyContainer[1];
object currentIsRaining = PropertyContainer[2];
But obviously, this is not going to work, since PropertyContainer[0] will return the old value - the value which Temperature had at the time of adding Temperature to the container (see the Line1 above).
Is there any solution to this problem? Basically I want to access current values of properties uniformly; the only thing that can change is, the index. The index however could be string as well.
PS: I don't want to use Reflection!
Well, you could use Lambdas:
List<Func<object>> PropertyAccessors = new List<Func<object>>();
PropertyAccessors.Add(() => this.Temperature);
PropertyAccessors.Add(() => this.Humidity);
PropertyAccessors.Add(() => this.IsRaining);
then you could to this:
object currentTemperature = PropertyAccessors[0]();

Categories