Logging Experiences

How to make more refactoring friendly data-bindings with C# 5

Posted in C#, Programming by Sina Iravanian on November 1, 2012

Imagine that we want to create a Person business object for whose properties we desire a two-way data binding. The source-to-target data-binding can be triggered by implementing INotifyPropertyChanged interface, like this:

public class Person : INotifyPropertyChanged
{
    private string _name;
    private double _age;

    public string Name 
    {
        get
        {
            return _name;
        }

        set
        {
            if (value != _name)
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
    }

    public double Age 
    {
        get
        {
            return _age;
        }

        set
        {
            if (_age != value)
            {
                _age = value;
                OnPropertyChanged("Age");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

See how the setters pass the property name in a string. This is not nice, because whenever we change the property name through refactoring tools, the string value remains untouched and we have to manually change them as well (if we are lucky enough to get notified before run-time). Anyway we had to tolerate them for years…

C# 5 comes with a nice feature, which is addition of two attributes [CallerFilePath] and [CallerMemberName] in the System.Runtime.CompilerServices namespace. If you decorate an optional string parameter of a method with one of these attributes, then the value of that parameter will be replaced with the caller’s file name or the caller’s member name at runtime, if no explicit value is passed for the optional parameter. They come very handy in logging scenarios, but we can use the latter for making our data-binding code nicer. This is how:

public class Person : INotifyPropertyChanged
{
    private string _name;
    private double _age;

    public string Name 
    {
        get
        {
            return _name;
        }

        set
        {
            if (value != _name)
            {
                _name = value;
                OnPropertyChanged();
            }
        }
    }

    public double Age 
    {
        get
        {
            return _age;
        }

        set
        {
            if (_age != value)
            {
                _age = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName]string propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Now that string constants are removed from the setters we can more freely refactor our code. After being spoiled by automatic properties, this is still a very verbose way of defining properties; however it is much better than before.

How to serialize DataTable and DataSet objects with YAXLib

Posted in C#, Programming, YAXLib by Sina Iravanian on October 24, 2012

YAXLib 2.x does not support serializing DataSet and DataTable objects by default. Since they have public properties of their own type, one will receive a YAXCannotSerializeSelfReferentialTypes exception. But it is quite possible to serialize them with custom serializers. Below is defined a custom serializer for DataSet:

public class DataSetCustomSerializer : ICustomSerializer<DataSet>
{
    public DataSet DeserializeFromElement(System.Xml.Linq.XElement element)
    {
        var child = element.Elements().FirstOrDefault();
        if(child == null)
            return null;
        using (var xr = child.CreateReader())
        {
            DataSet ds = new DataSet();
            var readMode = ds.ReadXml(xr);
            return ds;
        }
    }

    public void SerializeToElement(DataSet objectToSerialize, System.Xml.Linq.XElement elemToFill)
    {
        using (var xw = elemToFill.CreateWriter())
        {
            objectToSerialize.WriteXml(xw);
        }
    }

    public DataSet DeserializeFromAttribute(System.Xml.Linq.XAttribute attrib)
    {
        throw new NotImplementedException();
    }

    public DataSet DeserializeFromValue(string value)
    {
        throw new NotImplementedException();
    }

    public void SerializeToAttribute(DataSet objectToSerialize, System.Xml.Linq.XAttribute attrToFill)
    {
        throw new NotImplementedException();
    }

    public string SerializeToValue(DataSet objectToSerialize)
    {
        throw new NotImplementedException();
    }
}

And this is a custom serializer for DataTable:

public class DataTableCustomSerializer : ICustomSerializer<DataTable>
{
    public DataTable DeserializeFromElement(System.Xml.Linq.XElement element)
    {
        var dsElem = element.Elements().Where(x => x.Name.LocalName == "NewDataSet").FirstOrDefault();
        if (dsElem == null)
            return null;

        using (var xr = dsElem.CreateReader())
        {
            DataSet ds = new DataSet();
            var readMode = ds.ReadXml(xr);
            if(ds.Tables.Count > 0)
                return ds.Tables[0].Copy();
            return null;
        }
    }

    public void SerializeToElement(DataTable objectToSerialize, System.Xml.Linq.XElement elemToFill)
    {
        using (var xw = elemToFill.CreateWriter())
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(objectToSerialize.Copy());
            ds.WriteXml(xw);
        }
    }

    public DataTable DeserializeFromAttribute(System.Xml.Linq.XAttribute attrib)
    {
        throw new NotImplementedException();
    }

    public DataTable DeserializeFromValue(string value)
    {
        throw new NotImplementedException();
    }

    public void SerializeToAttribute(DataTable objectToSerialize, System.Xml.Linq.XAttribute attrToFill)
    {
        throw new NotImplementedException();
    }

    public string SerializeToValue(DataTable objectToSerialize)
    {
        throw new NotImplementedException();
    }
}

Having the above custom serializers at hand, one can decorate the DataSet and DataTable properties (or fields) with the YAXCustomSerializer attribute fed with the appropriate custom serializer type, as demonstrated below:

public class DataSerializationDemo
{
    [YAXCustomSerializer(typeof(DataTableCustomSerializer))]
    public DataTable TheDataTable { get; set; }

    [YAXCustomSerializer(typeof(DataSetCustomSerializer))]
    public DataSet TheDataSet { get; set; }
}

The following provides a sample instantiation for the above class:

public static DataSerializationDemo GetSampleInstance()
{
    var dataTable = new DataTable("TableName", "http://tableNs/");
    dataTable.Columns.Add(new DataColumn("Col1", typeof(string)));
    dataTable.Columns.Add(new DataColumn("Col2", typeof(int)));
    dataTable.Columns.Add(new DataColumn("Col3", typeof(string)));

    dataTable.Rows.Add("1", 2, "3");
    dataTable.Rows.Add("y", 4, "n");

    var dataTable1 = new DataTable("Table1");
    dataTable1.Columns.Add(new DataColumn("Cl1", typeof(string)));
    dataTable1.Columns.Add(new DataColumn("Cl2", typeof(int)));

    dataTable1.Rows.Add("num1", 34);
    dataTable1.Rows.Add("num2", 54);

    var dataTable2 = new DataTable("Table2");
    dataTable2.Columns.Add(new DataColumn("C1", typeof(string)));
    dataTable2.Columns.Add(new DataColumn("C2", typeof(int)));
    dataTable2.Columns.Add(new DataColumn("C3", typeof(double)));

    dataTable2.Rows.Add("one", 1, 1.5);
    dataTable2.Rows.Add("two", 2, 2.5);

    var dataSet = new DataSet("MyDataSet");
    dataSet.Tables.AddRange(new[] { dataTable1, dataTable2 });

    return new DataSerializationDemo
    {
        TheDataTable = dataTable,
        TheDataSet = dataSet
    };
}

And the following is the XML result for serializing the above object:

<DataSerializationDemo>
  <TheDataTable>
    <NewDataSet>
      <TableName xmlns="http://tableNs/">
        <Col1>1</Col1>
        <Col2>2</Col2>
        <Col3>3</Col3>
      </TableName>
      <TableName xmlns="http://tableNs/">
        <Col1>y</Col1>
        <Col2>4</Col2>
        <Col3>n</Col3>
      </TableName>
    </NewDataSet>
  </TheDataTable>
  <TheDataSet>
    <MyDataSet>
      <Table1>
        <Cl1>num1</Cl1>
        <Cl2>34</Cl2>
      </Table1>
      <Table1>
        <Cl1>num2</Cl1>
        <Cl2>54</Cl2>
      </Table1>
      <Table2>
        <C1>one</C1>
        <C2>1</C2>
        <C3>1.5</C3>
      </Table2>
      <Table2>
        <C1>two</C1>
        <C2>2</C2>
        <C3>2.5</C3>
      </Table2>
    </MyDataSet>
  </TheDataSet>
</DataSerializationDemo>

Please note that all the above steps are provided for YAXLib 2.x, which may require slight modifications in future versions of the library.

An example for C# dynamic in action

Posted in C#, Programming, Tips and Tricks by Sina Iravanian on July 23, 2012

Recently I was involved with enabling validation for a Windows Forms form containing several pages shown through a tree view. There were one user control defined for each page, therefore whenever a node in tree-view got activated, an instance of that user-control were shown. The user-controls did not have a common user-defined parent base-class or interface. The author of the existing code had defined a Save method in each control separately which performed updating data with values entered in the forms.

First, I changed all void Save() methods to bool Save(), and performed the validation stuff in each control separately. Then in the parent form, I created an array of Controls, so that I could loop through them, and call their Save method. But wait, Save is not inherited from any base-class or interface, so there’s no polymorphism at hand. How can I call them through references of type Control?

Well honestly, the best solution would be adding a new interface to the project, say ISavableControl or something, add the Save method to it, and let the controls implement that interface. But I wanted to make a quick fix to the problem without adding new files and types to the code. Here C#’s dynamic comes into action.

Using dynamic keyword, one postpones binding methods, properties, and fields to run-time. In our scenario we know that the user-controls each have a method called Save, which is not derived from a parent. Without dynamic, I would need to have a reference explicitly from each user control’s type, and I would have to call them one by one, as in:

bool succeeded = false;
succeeded = userControl1.Save();
succeeded = succeeded || userControl2.Save();
succeeded = succeeded || userControl3.Save();
// ...
succeeded = succeeded || userControln.Save();

However using dynamic keyword, life gets a lot easier:

// objects are not inherited from a base class or interface,
// therefore we cannot call Save using polymorphism
bool succeeded = false;
foreach(var ctrl in controlsArray)
{
    dynamic dynCtrl = ctrl;
    succeeded = succeeded || dynCtrl.Save();
}

// do something with the value of succeeded

Take care that binding the Save methods to controls happen at runtime. Therefore if a control does not implement a Save method, or if another one misspells Save, as say Svae, you will get no hints at compile time. So, try to avoid this style of coding, unless you have good reasons for doing so.

Tagged with: , ,

Code Snippet: Mean, Variance, and Standard Deviation Methods

Posted in C#, Programming, Snippets by Sina Iravanian on May 15, 2011

The methods to calculate mean, variance, and standard deviation of a vector of values. These are put here for easy reference, so that I do not need to rewrite them again.

A Helper Method for Performing K-Fold Cross Validation

Posted in C#, Programming, Snippets by Sina Iravanian on May 15, 2011

The following method is a utility method for creating the K divisions upon which one is going to perform the K-fold cross validation operation. The input of the method is the length of the training data, and the number K. The output says which indices of the training-data is to be put in each division.

Tagged with: ,

Dealing with ListView control, in the details mode

Posted in C#, Programming, Snippets, Tips and Tricks by Sina Iravanian on May 9, 2011

I needed a piece of code to manage list-view controllers. I needed to use ListView controls in the details mode, which automatically sort its contents when I click on the header, and also pastes the content in a tabular format when I press Ctrl+C or Ctrl+Insert on it. So I created the following classes. It is necessary to note that the code that carries out the sorting stuff when the header is clicked is taken from the following MSDN article:
http://msdn.microsoft.com/en-us/library/ms996467.aspx

So these are the contributions of these pieces of code: 1) Sorting ListView items automatically when the header is clicked, 2) Pasting the contents of the ListView control to the clipboard in a tabular format, and 3) Providing an easy to use API to append data to a ListView control.

The following gist contains the code to accomplish this. It consists of 3 files. The ListViewColumnSorter.cs file is responsible for the sorting stuff. The ListViewUtils.cs file provides the utility methods for a ListView control. The main methods that perform the job are located in the ListViewUtils class. The two needed methods are InitListView and AppendToListView. And finally the Usage.cs file provides a small sample demo of the utility methods.

Code Snippet: Trimming Strings of White-space and control characters

Posted in C#, Programming, Snippets by Sina Iravanian on March 2, 2011

The following method trims the given string of both white-space characters and control characters, and its rather fast!

Tagged with: , ,

Tips and Tricks: Making Windows Forms Size to Their Content

Posted in C#, Programming, Tips and Tricks by Sina Iravanian on August 15, 2010

Windows In WPF can make use of a property which makes the window to automatically adjust its own size to fit its content. The related property in WPF is SizeToContent which can be set to Manual (the default), Width, Height and WidthAndHeight. The last item makes the window shrink or grow so that it will fit its content.

The same effect can be made in Windows Forms using the AutoSize and AutoSizeMode properties of the form. Simply set AutoSize to true and also do not forget to set AutoSizeMode to GrowAndShrink. This effect is not visualized during design.

Tagged with: ,

Code Snippet: Determining how two intervals overlap

Posted in C#, Programming, Snippets by Sina Iravanian on August 9, 2010

The following pieces of code help you figure out how two intervals overlap, and provides tools to represent them in a way that is useful for debugging purposes. This job is quite easy to accomplish, but since it is written too frequently each time from scratch, I have put them in this gist.

The IntervalOverlapKinds.cs file defines the IntervalOverlapKinds enumeration. The interval detection is carried out in the static methods of the IntervalOverlap class.

Code Snippet: Representing strings with all their characters visible

Posted in C#, Programming, Snippets by Sina Iravanian on August 8, 2010

This piece of code is useful if you intend to work on a string processing algorithm. There are times, that you need to see the real content of a string while showing them in a windows form, console, and so on. This little method may help: