Thursday, 27 May 2010

Blog has been moved

My blog has been moved to http://sanjivanipant.com. Please visit new link for blogs.

Tuesday, 11 May 2010

Accessing and Setting Properties via Reflection

.NET gives us a cool feature called Reflection using that we can access object’s properties and methods at run time. The classes which help us in using this feature are all in System.Reflection namespace. That means you will have to add this namespace in the class where you will be writing reflection code. So basically, when object type is unknown at design time, we can’t access its properties until we don’t know what properties object possesses. In such situation we can access object properties at runtime using Reflection.

Let’s head towards building a small example,

I have Red and Blue forms in my project and for both the forms I want to show a label on the form when form is in focus and make that label invisible when form is not in focus.




I have a common library where I have ShowBusy() method. Red and Blue form calls this method to get label visible and invisible on Enter and Leave events respectively.


Both forms also have two more properties:

1. GetProgressLabel: It is a read only property which will return progress label.

2. IsInProgress: This property will possess form’s status whether form is in progress or not. Once ShowBusy is done for a form, it can update this property for a form.


So Blue and Red form’s code looks like below:


Blue Form:

public partial class frmBlue : Form

{

private bool _isInProgress;

clsProgress objprog = new clsProgress();

public frmBlue()

{

InitializeComponent();

}

private void frmBlue_Enter(object sender, EventArgs e)

{

objprog.ShowBusy(this, true);

}

public Label GetProgressLabel

{

get { return lblProgress; }

}

public bool IsInProgress

{

get { return _isInProgress; }

set { _isInProgress = value; }

}

private void frmBlue_Leave(object sender, EventArgs e)

{

objprog.ShowBusy(this, false);

}

}


Red Form:

public partial class frmRed : Form

{

private bool _isInProgress;

clsProgress objprog = new clsProgress();

public frmRed()

{

InitializeComponent();

}

private void frmRed_Enter(object sender, EventArgs e)

{

objprog.ShowBusy(this, true);

}

public Label GetProgressLabel

{

get { return lblProgress; }

}

public bool IsInProgress

{

get { return _isInProgress; }

set { _isInProgress = value; }

}

private void frmRed_Leave(object sender, EventArgs e)

{

objprog.ShowBusy(this, false );

}

}

In the common Library, I have a class clsProgress in which I have defined ShowBusy as below:

public class clsProgress

{

public void ShowBusy(object sender, bool busy)

{

//Make Progress Label Visible/Invisible

#1 Type SenderType = sender.GetType();

#2 PropertyInfo pi = (PropertyInfo)SenderType.GetProperty("GetProgressLabel");

#3 MethodInfo mi = pi.GetGetMethod();

#4 System.Windows.Forms.Label lbl = (System.Windows.Forms.Label)mi.Invoke(sender, null);

#5 lbl.Visible = busy;

//Set IsInProgress property of the form

#6 PropertyInfo pi1 = (PropertyInfo)SenderType.GetProperty("IsInProgress");

#7 pi1.SetValue(sender, busy, null);

}

}


In the ShowBusy method, we have code to make form’s progress label visible/invisible. It also has logic to set IsInProgress property of the form.

In this case, it would have been difficult to access sender’s property directly because at design time it is not known for which form ShowBusy is called. Another point to be noted is, Common Library project does not have reference of Red and Blue form project, so if you are thinking of having alternate way of achieving this by adding if conditions then casting to red and blue form then it won’t be possible. To cast it to Red and Blue form, you will need to have Blue/Red form project reference added in Common Library. So we adopted the Reflection here to access and modify object’s properties.


Let’s understand what we have done in ShowBusy:


#1 : We are extracting the type out of sender object

#2 : Using the extracted type we are extracting GetProgressLabel property and storing the property information in PropertyInfo object.

#3 : It returns the “Get” accessor of the GetProcessLabel property.

#4 : Invoke method on MethodInfo object will invoke the get property and return its value.

#5 : At line #4 we got the form’s label, so accessing Visible property and setting it.

#6 : Like step #2, extracting IsInProgress property.

#7 : To set property value, we have SetValue method. Please have a look onto http://msdn.microsoft.com/en-us/library/xb5dd1f1.aspx to understand SetValue method’s parameters.


You can download the example from here.

Thursday, 29 April 2010

Introduction to C# 3.0 features – Part I

There are many cool features available in C# 3.0 vis

  • Extension Methods
  • Implicitly Typed Local Variables
  • Lambda expressions
  • Object Initializers
  • Anonymous types
  • Implicitly typed arrays
  • Query expressions
  • Expression trees


Out of these cool features, I would like to write about Extension Methods first. I would write about C# 3.0 features in my subsequent articles.

Most of the times we tend to code in our traditional way and ignore such a cool features which are available to make developer’s life easy. For example, a developer like me who mostly worked on Framework 2.0 will hardly dare to spend more time in trying new alternate available way, in care of dead line J I would suggest be familiar with new features, trying it in dummy samples and be ready to use in your real projects.

Before heading towards Extension methods… let’s consider we have to create a method to reverse a string. So our usual approach would be to write a method accepting a string parameter, writing logic to reverse a string and returning a reversed string. Below is the code, we might have coded for this requirement.

class Program

{

static void Main(string[] args)

{

String myString = "Sanjivani";

Program obj = new Program();

String reverseString =obj.Reverse(myString);

Console.Write(reverseString);

Console.ReadKey();

}

string Reverse(string str)

{

char[] arr = str.ToCharArray();

Array.Reverse(arr);

return new string(arr);

}

}

Well, now heading towards Extension Methods…

Like name suggest, Extension Methods are extensions to typed instances. Extension Methods are static methods that can be invoked using instance method. For example when we have string type variable we get many built in methods and properties like...

strObj.Replace()

strObj.Split()

strObj.SubString()

ect

In the same way we can make our Reverse method available like strObj.Reverse(). So Reverse method will be available for all instances which are of string type.

Like we have Utility or common classes for our projects, we can have extension library having methods which works on a type.

Implementing Extension Methods:

Let’s convert same Reverse method into an extension method. I created new class for all extension methods as below:

public static class ExtensionLib

{

public static string Reverse(this string str)

{

char[] arr = str.ToCharArray();

Array.Reverse(arr);

return new string(arr);

}

}

If you notice, the changes I have method to the function are:

1) Introduced this before first parameter. First parameter’s type will always tell compiler that, that extension method is going to operate on the type used for first parameter.

2) Added public and static modifiers to Reverse method

3) Note that new class also has public and static modifiers

You are ready to use this extension method now:

class Program

{

static void Main(string[] args)

{

String myString = "Sanjivani";

Console.Write(myString.Reverse());

Console.ReadKey();

}

}

Please note that, my Extension method class and the program where I wanted to use this extension method were in same namespace, so I did not add extension method namespace in my Program class. But if both are in different namespaces, you will have to add extension method class namespace in your client program.

Your comments and knowledge on the topic are always welcome. I will appreciate your contribution :)

Sunday, 28 March 2010

Shantaram

I recently completed “Shantaram” book and picked up new book in my hand “Superstar India” by Shobha De and I realized I should write my feelings for Shantaram before getting involved in another book. It took approximately six months to me to complete Shantaram, there were many gaps in between though. Now after completing this book, definitely I am going to miss Shantaram reading in my daily life...

I came to know about the book from my husband. I was not much involved into reading books before marriage. After marriage I started getting more time in MRT (local trains) so I took these opportunities to read books from my ever dreamed list. But Shantaram was not in my list. I took time to pick up that book to read, thinking this is so big book and I was afraid that I won’t complete the book. I thought to read other books first and I did so and after 3-4 books I picked up Shantaram in my hand. I heard so much praise about this book from my husband that I could not wait any more and finally picked up the book.

The impression I was having before reading this book was, this is a true story (non fiction), my husband told that to me intentionally. And I was expecting a lot from this book then, I was curious to know how was Shantaram/Lin’s (author and main character in the book) in India. Most of the people definitely take bad and good experiences in their life. Few can be very serious and critical which the person might feel, it can only happen with him. I do also have faced many realities in my life and I was just thinking, will my any of experiences matches with him (I know that is crazy to think like that :D). But even there might have been same experience; definitely a foreigner will perceive that in different way. I haven’t been to any WAR or worked for any MAFIA.. but the common thing I found in Lin’s life experience is to live in slum with no option in hand. Seeing slum’s life so closely and observing people there. I never told this to anybody in my life, but my best and close friends know this.

Anyway, one of the thing which was responsible towards my curiosity was, after I started this book, many people came to me and were asking me, oh you are reading Shantaram.. and they were curious to know how I am finding that. So they may get their answer here :)

When I started with first chapter, I realized I have to definitely keep dictionary with me if I really want picture author’s story, though I was getting its meaning from its context, I was so excited to grabs each and every aspect of the book.. indeed I was so excited to read that book with my full heart dedicated to that book. At the beginning I did refer to dictionary and obviously that I did not find it that interesting that I was thinking. I took a break of few days and again started the book with full determination. This time I did not care about adverbs author used and just went on.. I did grab all the context from the book.. may be I might missed few of the true meaning but I got its meaning, whole meaning of the book and I am thinking I may read this book again after few years.

Initial few chapters are not of just introduction of characters and author has excellently described those characters in his book. In fact I can imagine those characters. In my office, I have a team mate, and I found character of Prabhakar exactly matches with him. So whenever I see my team mate it reminds me of Prabhakar. So even there would be years after reading this book, character s of Shantaram book will remain always in my mind. Not only Prabhakar, but I found a girl in my office, and she reminds me of Karla :) I imagine, if Karla would be in real life, she must have to be like her (in appearance).

I enjoyed the book, especially when suspense’s started coming in the story. And I was so eager to read next pages to know what I am thinking as an answer to that suspense is true or not :)

Shantaram, is not of one type of book, which we can say it is a romantic book or it is a suspense or thriller book. I found it is ALL. It has thriller, suspense, romance, comedy, action (lot of actions :)) And just imagine when you are reading the book, and you know it is a true story how interesting that would be. But then I got to know not the entire book is true. I watched Gregory David Robert’s video on You Tube and got to know all events in this book are real and characters are friction. But when you will read the book, it is unbelievable that those character’s descriptions are fiction. Hats off to Gregory David Roberts and congratulations too! He has succeeded in describing characters as real ones.

I did not enjoy Afghanistan War part much because I was just curious to know suspense’s. And in my thoughts those long Afghanistan chapters were not related to the suspense’s which answers I was looking for. But ending of Afghanistan gives you more pleasure because there you will discover something important :), So then I realized it has also a meaning to read those Afghanistan war chapters. But you know it really need patience to complete those Afghanistan war chapters.

In many of the points, I was feeling like crying and sad however most of the moments were so romantic. I wish I could describe those moments here but it will reveal surprises involved in the book so I won’t write about any of the moments here.
Since it has all Mafia and Underworld related stories, be ready to get familiar with abusing language. But it also gives a decent society an idea how underworld people think and live and this language is part of their life, I think without those that languages they can’t survive or express themselves :)

I like all characters of the book, but if they were real characters I would definitely like to meet Prabhakar, Karla, of couse the king Kadar Khan, Dadier, Lisa.

I don’t want to reveal any of the event of the book because I don’t want to spoil your reading and give you presumptions.. go for the book and discover your own perceptions.

So, I found the book very good and after completing the book I still miss the book, I wish there would be more chapters to that :)

Monday, 22 March 2010

Using statement/keyword in C#

I came across a question “What is use of using in C#” and I decided to write on it. I hope this blog will help you in knowing “using” statement/keyword better.

The Basic Syntax:

1) For one object

using (MyClass objMyClass = new MyClass())

{

//Use objMyClass

}

2) For Multiple objects

using (MyClass objMyClass = new MyClass(),

objMyClass1 = new MyClass())

{

//Use objMyClass and objMyClass1

}

3) Syntax 3 (Not recommended)

MyClass objMyClass = new MyClass()

using (objMyClass)

{

//Use objMyClass

}

// objMyClass can be used out of using block as well

We will see why it is not recommended in this blog later. If I explain it here then you may not follow it without knowing its main use first.

“using” statement can be used in following scenarios.

Scenario 1: Importing namespace

A well known use of “using” keyword is for importing namespace into classes.

Examples:

using System.Collections.Generic;

using System.Linq;

using System.Text;

Scenario 2: Disposing object automatically

If object is delcared in using statement (like shown in syntax 1), that object becomes out of scope and get destroyed as soon as it leaves using block.

In the syntax 1, the care has to be taken that MyClass should implement IDisposable interface. That means, we can’t declare object of the class which do no implement IDisposable.

My MyClass class looks like below:

class MyClass:IDisposable

{

// Track whether Dispose has been called.

private bool disposed = false;

// Pointer to an external unmanaged resource.

private IntPtr handle;

// The class constructor.

public MyClass(IntPtr handle)

{

this.handle = handle;

}

public MyClass()

{

}

public void DisplayName()

{

Console.WriteLine("MyClass\n");

Console.ReadKey();

}

#region IDisposable Members

public void Dispose()

{

// throw new NotImplementedException();

Dispose(true);

// This object will be cleaned up by the Dispose method.

// Therefore, you should call GC.SupressFinalize to

// take this object off the finalization queue

// and prevent finalization code for this object

// from executing a second time.

GC.SuppressFinalize(this);

}

#endregion

// Dispose(bool disposing) executes in two distinct scenarios.

// If disposing equals true, the method has been called directly

// or indirectly by a user's code. Managed and unmanaged resources

// can be disposed.

// If disposing equals false, the method has been called by the

// runtime from inside the finalizer and you should not reference

// other objects. Only unmanaged resources can be disposed.

private void Dispose(bool disposing)

{

// Check to see if Dispose has already been called.

if (!this.disposed)

{

// If disposing equals true, dispose all managed

// and unmanaged resources.

if (disposing)

{

// Dispose managed resources.

// component.Dispose();

}

// Call the appropriate methods to clean up

// unmanaged resources here.

// If disposing is false,

// only the following code is executed.

CloseHandle(handle);

handle = IntPtr.Zero;

}

disposed = true;

}

// Use interop to call the method necessary

// to clean up the unmanaged resource.

[System.Runtime.InteropServices.DllImport("Kernel32")]

private extern static Boolean CloseHandle(IntPtr handle);

// Use C# destructor syntax for finalization code.

// This destructor will run only if the Dispose method

// does not get called.

// It gives your base class the opportunity to finalize.

// Do not provide destructors in types derived from this class.

~MyClass()

{

// Do not re-create Dispose clean-up code here.

// Calling Dispose(false) is optimal in terms of

// readability and maintainability.

Dispose(false);

}

}

To just test if we can declare object of class without having IDisposable interface, try to execute following code:

using (MyClass1 objMyClass1 = new MyClass1())

{

objMyClass1.DisplayName();

}

And here MyClass1 looks like:

class MyClass1

{

public void DisplayName()

{

Console.WriteLine("MyClass\n");

Console.ReadKey();

}

}

You will get following error:

'UsingKeyword.MyClass1': type used in a using statement must be implicitly convertible to 'System.IDisposable'

The reason for not allowing classes without IDisposable interface is:

“using” statement is shotcut to try/catch/finally block, having Dispose method call in finally block.

Thus,

using (MyClass objMyClass = new MyClass())

{

//Use objMyClass

objMyClass.DisplayName();

}

is similar to

MyClass objMyClass = new MyClass();

try

{

objMyClass.DisplayName();

}

finally

{

if (objMyClass != null)

((IDisposable)objMyClass).Dispose();

}

Thus, we get following benefits from “using”:

1. It ensures that using statement calls the Dispose method on the object in the correct way.

2. Within the using block, the object is read-only and cannot be modified or reassigned.

3. The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

4. If you declare any un-managed object in using block, you don't need to explicitly dispose that object. Once the block execution is over, the Dispose will be called automatically.

Scenario 3: Taking care of multiple objects at the same time (Syntax 2)

We can pass multiple object of the same type to using statement. We cannot create multiple objects of different types in one using block. Thus if I write syntax 2 as below, then it is invalid.

using (MyClass objMyClass = new MyClass(),

MyClass1 objMyClass1 = new MyClass1())

{

//Use objMyClass and objMyClass1

}

That is the reason, we don’t have to write type name from second object onwards. In below example, we cannot give type of the class name for second object since it is understood that, type will be same as used for first object.

using (MyClass objMyClass = new MyClass(),

MyClass objMyClass1 = new MyClass())

{

//Use objMyClass and objMyClass1

}

Scenario 5: Aliasing to namespaces

// Define an alias for the nested namespace.
    using Project = PC.MyCompany.Project;

Scenario 5: Aliasing to classes

Like aliases to Namespaces we can have aliases to classes as well.

// Using alias for a class.
using AliasToMyClass = NameSpace1.MyClass;   
 
 

Answer to why Syntax 3 is not recommended

Wait! Don’t scroll to look at syntax 3, to help you to understand it better, I have put it below J

MyClass objMyClass = new MyClass()

using (objMyClass)

{

//Use objMyClass

}

// objMyClass can be used out of using block as well

As we know by now, unmanaged resources referenced/used by object get destroyed as soon as it leaves “using” block. So even object is accessible after using block, it may not have access to unmanaged resources and if we try to access object, it may be risky to use it because object may not be available in fully initialized state. For this reason, it is generally better to instantiate the object in the using statement and limits its scope to the using block.

 

References:

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

http://msdn.microsoft.com/en-us/library/system.idisposable.dispose%28VS.71%29.aspx