Wednesday, March 17, 2010

A Smarter ViewModelBase

The advent of WPF has led to ubiquity of the MVVM pattern. Developers usually have a ViewModelBase class the implements the INotifyPropertyChanged interface as shown below:-

class ViewModelBase : INotifyPropertyChanged
{
   public event PropertyChangedEventHandler PropertyChanged;

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

The NotifyPropertChanged method is called from within the "set accessor" of a property with the name of the property passed as a parameter.

The problem with this implementation is that if the property name "string" parameter has be be in sync with actual property name as an when it changes. We as developers are prone to spelling mistakes and could easily leave out some property change notifications out of sync with the property name.

The following code address the problem mentioned above

class ViewModelBase : INotifyPropertyChanged
{
   private const string SetPropertyPrefix = "set_";

   #region INotifyPropertyChanged Members

   public event PropertyChangedEventHandler PropertyChanged;

   #endregion

   // Call this method from within a set accessor of a property
   protected void NotifyCurrentPropertyChanged()
   {
      if (PropertyChanged == null)
      {
         return;
      }

      StackTrace st = new StackTrace(1);
      StackFrame sf = st.GetFrame(0);
      MethodBase mb = sf.GetMethod();

      if (mb.MemberType == MemberTypes.Property)
      {
         // if the calling method is not an accessor of a property, do nothing
         string methodName = mb.Name;
         if (methodName.StartsWith(ViewModelBase.SetPropertyPrefix))
         {
            // We are bothered only with set accessors
            string propertyName = methodName.Substring(ViewModelBase.SetPropertyPrefix.Length);
            NotifyPropertyChanged(propertyName);
         }
      }
   }

   // The conventional NotifyPropertyChanged
   protected void NotifyPropertyChanged(string propertyName)
   {
      if (PropertyChanged != null)
      {
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
   }
}

The NotifyCurrentPropertyChanged method can be used in the set accessors of properties. Note that there is no need to pass the propery name anymore!

Tuesday, March 16, 2010

Thread.Suspend – Don’t call me anymore

Recently I ported our project from .NET 3.5 to .NET 3.5 SP1. Among the bunch of warnings, I found these interesting (to write about):-

Thread.Suspend has been deprecated. Please use other classes in System.Threading, such
as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources.
http://go.microsoft.com/fwlink/?linkid=14202

Thread.Resume has been deprecated. Please use other classes in System.Threading, such
as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources.
http://go.microsoft.com/fwlink/?linkid=14202"

I had used the Thread.Suspend and Thread.Resume APIs in order to freeze operation (interaction with hardware) until the desired user input is received to continue. This is not a rogue programming model. In the Win32 world, despite the caveats raised for SuspendThread and ResumeThread, these APIs are not uncommon for tough guys. I have used it in my earlier projects. But it seems, in .NET world, we have to infer something from the above warnings. These native and low-level APIs seem to have some serious implications. My interpretation of this warning is Microsoft is not going to support this API anymore. Since the threading and runtime infrastructure is always undergoing (internal) changes, it seems to have a strong bearing on the behavior of the API. Besides, CLR thread may not be a Win32 thread physically. I have read that the CLR may use fibers, if possible. So the CLR safely withdraws from providing any more guarantees for platform specific low-level APIs.

Now Let’s see what are the implications of using this API in our code

With Thread.Suspend, we have explicit control over the execution of an arbitrary thread which is absolutely a dangerous thing. Thread.Suspend/Resume are very primitive and low level APIs to be used control the flow of a program. A thread may be executing any piece of code when it is being suspended, It may be executing a user code or an operating system code at the User-Level IRQL or in a third-party library. Under these situations, the caller of Thread.Suspend is totally oblivious of the fact that the thread might be holding synchronization locks that are critical to the application/library and OS. This could result in deadlocks that are difficult to debug. All this is pointing towards one thing, an application is not well designed if it is using these APIs.

If we want to synchronize threads, we should always resort to understanding the problem first and design a solution with the higher primitives provided by the framework like Mutex, Semaphores, critical sections and events etc; that is what is suggested by .NET with the above warnings. By using these high-level primitives, we delegate the lower-level responsibilities of suspending and resuming the threads to the Framework/OS. Besides making our code safe, we make our intent explicit. A few lines of explicit code is worth a ton of documentation!

Monday, October 5, 2009

My first Sangeeth Sammelan concert

I just came back after my first sangeeth sammelan concert held in New Delhi on 3rd october at FICCI auditorium organised by All India Radio. It will be relayed on Channel A from 10pm to 11pm on 3rd Nov 2009. I accompanied T.M. Krishna on the violin and Poongulam Subramaniam was on the mridangam. The concert went on very well and the hall was packed. The list is

1. Neelayadakshi - Paras - Syama Sasthri
2. RTP - Begada - Adhi - Kailasapathe pasupathe umapathe namosthuthe
3. Javali in Kaanada

His begada rendition was truly awesome and very inspiring. I heard a lot of new phrases. Poongulam subramainiam as usual was very supportive. It is after eleven years I am accompaniying T.M. Krishna (I started my career with him in the year 1998) and it was a truly amazing experience. Surprisingly he remebered it when I told him.

Monday, September 7, 2009

“Please Don’t fail me!” – Decorator cries out to Template Method

This article is a result of serendipity that I experienced when implementing a small framework. As an ardent fan of design patterns I tend to use them where ever I could. I had a few classes in my framework in which I used the “Template Method” Design Pattern. When I wanted to extend my classes without modifying them, the first pattern that came to my mind was the Decorator Design Pattern. This article explains what problems I encountered during this implementation and how they were circumvented. Do these patterns gel well?

Follow the link Decorator Vs Template Method to find out the answer.

Friday, August 21, 2009

XML Configuration File Upgrade Technique

One of my colleagues asked me if there was a simple way to upgrade an xml configuration to one conforming to a new schema. Actually this is pretty easy and fun in .NET (if we use DataSets).
Here is an example

Old schema – OldEmployee.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" 
xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="EmployeeDetails">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="Employee">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Name" type="xs:string" />
              <xs:element name="Designation" type="xs:string" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

New Schema – NewEmployee.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" 
xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="EmployeeDetails">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="Employee">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Name" type="xs:string" />
              <xs:element name="Designation" type="xs:string" />
              <xs:element name="Age" type="xs:positiveInteger" default="40"/>
              <xs:element name="Gender" type="xs:string" default="Male"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
The following code

  • Reads the old schema into a data set
  • Reads the old XML file (conforming to the old schema)
  • Reads the new schema into a new data set
  • Performs a merge on the new data set merging the old dataset
  • Outputs the upgraded XML configuration file
using System.Data;

namespace ConfigFileUpgrade
{
   class Program
   {
      static void Main(string[] args)
      {
         DataSet dsOld = new DataSet();
         dsOld.ReadXmlSchema("OldEmployee.xsd");
         // Now lets try to read an XML conforming to this schema
         dsOld.ReadXml("OldEmployee.xml", XmlReadMode.Auto);

         // We create a new dataset and assign the new schema to it
         // This data set will not contain any data since we have read only the schema
         DataSet dsNew = new DataSet();
         dsNew.ReadXmlSchema("NewEmployee.xsd");

         // We merge the old data set with the new data
         // all the data in the old data set now gets merged to the new data set with
         // the new schema
         dsNew.Merge(dsOld, false, MissingSchemaAction.Add);

         // Upgrade is complete
         dsNew.WriteXml("NewEmployee.xml");
      }
   }
}

Thursday, August 20, 2009

Increasing performance (.NET Regular Expressions)

I just discovered that the .NET Regex class offers a static method (CompileToAssembly) to compile a regular expression to an assembly for increased performance. Here is a sample code.
using System;
using System.Text.RegularExpressions;
using System.Reflection;

namespace CompiledRegEx
{
   class Program
   {
      static void Main(string[] args)
      {
         if ( args.Length < 5 )
         {
            Console.WriteLine("Error: Insufficient Parameters. \nUsage: rexc ");
            return;
         }

         string pattern = args[0];
         string options = args[1];
         string className = args[2];
         string namespaceName = args[3];
         string assemblyName = args[4];

         RegexCompilationInfo ri = new RegexCompilationInfo(pattern,
            (RegexOptions)Convert.ToInt32(options),
            className,
            namespaceName,
            true);

         Regex.CompileToAssembly(new RegexCompilationInfo[] { ri },
            new AssemblyName(assemblyName));

         Console.WriteLine("Regular Expression successfully compiled to an assembly");
      }
   }
}
You can now use the new type from the compiled assembly just as you would use any other type from an assembly. The Match method of the new RegEx type does not take the pattern as a parameter. If you use a lot of static regular expressions in your code, this can provide significant gain in performance.

Monday, August 17, 2009

Auto and Manual Reset Events Revisited

Just posted as article for Code Project on Auto and Manual Reset Events. I ended up writing this article after my bitter experience with analyzing some other group's log files and finding out the problem in their code was due to improper use of Manual Reset events.

Click HERE to read the article at CodeProject.