Friday, October 29, 2010

C# 5.0 Asynchronous Made Easy

After I introduced about Future Of C# 5.0 I was not aware of what Microsoft is thinking about it. But today after I saw PDC 2010 the main concern that Microsoft is pointing to on the release of C# 5.0 is the pain related to deal with asynchronous operations using Threads. It simplifies the existing MultiThreading model with Task based model, which now simplified with greater extent with the use of two new keywords yet not introduced as "await" and "async".

The History

Before the introduction of these features, we generally rely on traditional approaches of creating Thread from a ThreadPool and consuming a method which needed to be asynchronously called for. Again when the Thread finishes, or during the lifetime of the Thread we need callbacks to notify UI after a while, so that the user gets an impression that the background is updating the system. This breaks the way we write or the way we think of programming. The programmer needs to create the program to device in such a way that it handles continuity of the application by writing custom callbacks to the system or even use Dispatcher to update the UI thread from background. Thus the code becomes more and more complex as we add up more functionalities to the system.

The Present

In this PDC, Anders Hejlsberg introduces two new investments on C# which is probably now still in CTP to allow asynchronous calls to the applications very simple and easy to handle. The two keyword which were introduced recently are "async" and "await". Let me introduce these two keywords for the time being.

Monday, October 25, 2010

Create Enumeration as Bit Flags

Enumeration is one the important feature of C#. Enumeration allows you to name a variable to make sense for the program. It is in general impossible to understand numeric status values when there is more than two values for a single state of object.  In such a case we give a logical name for the numeric integer and use the Logical name of it to call that particular state.

For instance :
Say you want to define the nature of a person.

public enum Character
 {
       Caring,
        Honest,
        Loving,
        Desparate,
        Obedient, 
        Logical,
        Practical
}
You might name these characteristics using numeric values, say you have Honest as 1, Loving as 2 etc. But it would be more logical to use an Enum instead.

Hmm... Putting it further, Enum might also come very handy when you want to use a combination of the same. Say for instance, a person can be both Logical and Caring. Now how could you define this? Do you need to define enumeration values for each of them ? I guess that would not be a good choice either.

Flags attribute in Enum plays a vital role if you want to use the values of an enumeration in combinations. So that each combination of enumeration values are mutually exclusive and does not overlap with another value of Enum. For bit fields, it is very easy and yet very handy to use Flags attribute rather than using your own logic to define the flags yourself.

Sunday, October 24, 2010

DLR using Reflection.Emit (In Depth) Part 2

In my previous post, I was discussing how you could create your own assembly at runtime or rather how you could compile an assembly type dynamically using Reflection.Emit.  In this post I will take it further by giving away a number of examples for your better understanding how to build your own custom types dynamically during runtime. I will also try to cover up a portion of MSIL concepts so that you could unleash the power of MSIL easily in your application.

The Basics

To build a dynamic type, the most important thing that we have discussed already are Builder classes. The BCL exposes a number of Builder classes that enables us to generate MSIL code dynamically during runtime and hence you can compile the same to produce the output.


From the above figure I have put some of the most important Builder classes marked in Red. But ultimately, you need instructions to run for your application. To write your IL Expression, Reflection.Emit provides a class call ILGenerator. ILGenerator (marked in blue) enables you to write your IL for a method or property. OpCodes are Operation code that determined Computer instructions. So while writing your instructions you need to pass your OpCodes and generate the instruction set for the Method.

Now going further with our example, let me demonstrate the code one by one so that you could easily build your own Code generator. 

Implement IBuilder for your Assembly

Lets move to the actual implementation of IBuilder interface. As per our discussion, IBuilder contains 4 members, Sum, Divide, Multiply & substract.

public interface IBuilder
{
    float Sum(int firstnum, int secondnum);
    float Substract(int firstnum, int secondnum);
    float Multiply(int firstnum, int secondnum);
    float Divide(int firstnum, int secondnum);
}

Download Sample Application - 66 KB

Saturday, October 23, 2010

DLR using Reflection.Emit (In Depth) Part 1

I love C#, I Love .NET. Do you agree ? Hmm, But I mean it :)

Well, lets put it in other words, " The more I see the framework, the more I discover in .NET". Yes, after putting my efforts with Reflection classes, I thought I could make some research on code generation. I took the CodeDom being the best alternative to generate code. Sooner or later, I found out, CodeDom actually allows you to build your assembly but it is does not allow you to dynamically compile a part of the assembly at runtime, but rather it invokes the compiler to do that. So rather than CodeDom, I thought there must be something else which fruits my needs.

Next I found out one, using Expression Trees. If you are already following me, I think you know, few days back I have already written about Expression Trees and Lamda Decomposition. So it is not a good time to recap the same. Later on, I did some research on MSIL, and found it worth learning. If you are going to grow with .NET, it would be your added advantage if you know about MSIL. Hence I started looking at the MSIL. Finally I found out a number of classes which might help you to build a Type dynamically. Let me share the entire thing with you.

Introduction

Reflection.Emit like CodeDom allows you to build your custom assembly and provides you a number of Builder classes which might be compiled during Runtime, and hence invoke DLR capabilities of C#. The library also exposes one ILGenerator which might be used later to produce the actual MSIL by putting efforts to emit Operation codes.  So finally after you write your OpCodes correctly, you could easily able to compile the type dynamically during runtime. In this post,  I would use ILDASM to see the IL generated from our own class, that I define, and later on I would try to build the same class dynamically.

What is Reflection ? 

If you are struck with Reflection, then you need to really gear yourself a bit to go further. Let me give a brief explanation of Reflection. Reflection is actually a technique to read a managed dll which is not being referenced from the application and call its types. In other words, it is a mechanism to discover the types and call its properties at runtime. Say for instance, you have an external dll which writes logger information and sends to the server. In that case, you have two options.
  1. You refer to the assembly directly and call its methods.
  2. You use Reflection to load the assembly and call it using interfaces. 
If you want to build really a decoupled architecture for your application, something like which could be plugged in later in the application, it is always better to choose the 2nd option. Let me clarify a bit more, say you want your customer to download the logging dll from your server and plugin to the application when needed. Believe me, there is no other alternative than using Reflection. Reflection classes allows you to load an external assembly to your application and call its types at run time.

To know more try Reflection Overview

What is Reflection.Emit ? 

Being a part of Reflection, Reflection.Emit namespace list you a number of classes which you can use to build your type. As I have already told you, Reflection.Emit actually provides you some Builder classes like AssemblyBuilder, ModuleBuilder, ConstructorBuilder, MethodBuilder, EventBuilder, PropertyBuilder etc. which allows you to build your IL dynamically during run time. The ILGenerator provides you the capabilities to generate your IL and place the same for a method. Generally, it is very rare that a developer need these capabilities to generate an assembly at runtime, but it is great to find these capabilities present in the framework.

Now lets see what is required to build an assembly.


Saturday, October 16, 2010

Hidden Facts of C# Structures in terms of MSIL

Did you ever thought of a program without using a single structure declared in it ?  Never thought so na? I did that already but found it would be impossible to do that, at least it does not make sense as the whole program is internally running on messages passed from one module to another in terms of structures.

Well, well  hold on. If you are thinking that I am talking about custom structures, you are then gone too far around. Actually I am just talking about declaration of ValueTypes. Yes, if you want to do a calculation, by any means you need an integer, and System.Int32 is actually a structure. So for my own program which runs without a single ValueType declared in it turns out to be a sequence of Print statements. Does'nt makes sense huh! Really, even I thought so. Thus I found it is meaningless to have a program which just calls a few library methods (taking away the fact that library methods can also create ValueType inside it) and prints arbitrary strings on the output window.

Please Note : As struct is actually an unit of ValueType, I have used it synonymously in the post.

So what makes us use Structures so often? 

The first and foremost reason why we use structures is that
  • They are very simple with fast accessibility.
  • It is also created on Thread local stack, which makes it available only to the current scope and destroyed automatically after the call is returned. It doesn't need any external invisible body to clear up the memory allocated henceforth.
  • Most of the primitives have already been declared as struct.
  • In case of struct we are dealing with the object itself, rather than with the reference of it.
  • Implicit and explicit operators work great with struct and most of them are included already to the API.
Download Sample - 24KB

Tuesday, October 5, 2010

ASP.NET 4.0 In - Depth Session PART 2 On 10th OCT

Guys, after completing the Part 1 of the Session, its time to go beyond it and show you a few more advanced concepts from ASP.NET 4.0.  The remaining part of the Session includes :


Grayed Portion is already covered in PART 1

  1. State Management Enhancements
  2. Client side Enhancements
  3. Deployment
  4. Overview of Dynamic Data

I will present this Session  with Abhijit Jana on 10th October (the next Sunday) from 2 P.M IST. Please visit http://www.dotnetfunda.com/misc/onlinesession.aspx for more details.


If you missed out the Previous Session, you can follow the link to download PPT, the Video and the Source codes :

Download PPT, Sample Code & Video1
Download PPT, Sample Code & Video1

I hope the next session would be as good as this one. Nominate yourself for the same.(You need to register before you nominate yourself) Thank you all for your support.

Be there.

Note : If you have already nominated for the Session you do not need to Renominate yourself.

Monday, October 4, 2010

Lazy Load XAML content from External File and Vice Versa

XAML is the most flexible language built ever. More I see XAML, more I know about it. Today while tweaking around with XAML code, I found XAML could be loaded dynamically from any XML string. That means if you have a xaml in a xml file you can probably load the part of the XAML into your ContentControl or to any control element you want and the UI will appear instantly.

Once you compile a XAML it produces BAML. BAML is in binary format for the XML, so if you can pass a BAML into the UI separately somehow during runtime,you would be seeing the content instantly in the Window. In this post I am going to discuss how easily you could load a Dynamic content of XAML file into a normal WPF ContentControl just like what we do for normal htmls.

What is XamlReader and XamlWriter? 

If you look into the implementation of these classes you could wonder how flexible these are. They are highly capable of parsing the whole content of the file. It uses a XAMLDictionary which holds all the XAML elements that a XAML can see. The Reader parses the Xml content very cautiously to ensure it makes the XAML file to contain no reference of outside. Thus the class is used to Refactor the XAML from outside and hence allows you to put the content anywhere such that everything will be applied on that instantly.

XamlReader exposes methods like Load / Parse which allows you to parse a file content into BAML. Hence each of them returns an binary object which you can put into the Content.

Download Sample Application - 56 KB

Sunday, October 3, 2010

Building a CRUD in RESTful Services of WCF

WCF is being popular day by day. Many of us is building services using WCF and want other application made on different architecture to communicate or inter operate with each other. REST or Representational State Transfer is a Design Pattern to build a service so that it works the same way as service works but it will eventually use Web Request - Response mechanism to communicate between clients rather than using SOAP messages.  In this post, I will give you a step by step approach how you could build your own WCF service using REST.

What is REST ?

REST abbreviated as Representational State Transfer is coined by Roy Fielding is a Design pattern for Networked system. In this pattern the Client invokes a Web request using an URL, so the basic of REST pattern is to generate unique URI to represent data.

If you look into Roy Fielding's quote on REST it says :
"Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: a network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use."

That means REST is intended for Web applications where the browser invokes each request by specifying unique Uri.

REST Based Services


Download Sample Application - 200KB

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!