Showing posts with label CSharp. Show all posts
Showing posts with label CSharp. Show all posts

Thursday, 26 January 2012

Dot Net Assembly and How to Create Assembly

Dot Net Assembly and How to Create Assembly

An assembly is a partially compiled code library for use in deployment, versioning and security. The .NET assembly is the standard for components developed with the Microsoft.NET. Dot NET assemblies may or may not be executable.Assemblies are a functional unit of sharing and reuse the common language runtime. It provides the common language runtime with the information it need to be aware of type implementations. To the runtime, a type does not exist outside contest of an assembly. Assemblies are the fundamental part of the runtime.


In Physical term Assembly is a collection of physical files that owned by the assembly. These assemblies called static assemblies can include .NET Framework type (Interfaces and Classes) as well as the resources for the assembly (Bitmap, JPEG files, Resources files etc...). In addition, Common Language Runtime provides API’s that script engine use to create dynamic assemblies when executing script. These assemblies are run directly and never saved to disc, though we can save to disk.



Assembly concepts


An assembly forms a logical unit of functionality, a logical dll. An assembly forms the fundamental unit of Deployment, Version Control, Reuse, Activation Scoping and Security Permission. It is important to understand what an assembly is not. An assembly is not a unit of application deployment. It is a unit of class deployment, and these assemblies can be packed for deployment in several ways.


Assembly Contents


In general an assembly consists of for elements

1. The assembly manifests.
2. Metadata.
3. Microsoft intermediate language (MSIL).
4. A set of resources.



There are several ways to group these elements in an assembly. You can group all elements in a single physical file or it can be contained in several files.


1. Assembly Manifest


Assembly manifest contains Assembly Name, version number, culture, and strong name, list of all files, Type references, and referenced assemblies. Assembly manifest contain information on all items considered part of an assembly, this information is known as assembly metadata. Manifest indicates what items are exposed outside of the assembly and what items are accessible only within the current assembly's scope. Assembly manifest also contain collection of reference to other assemblies, these references are resolved at runtime base on the information stored in the manifest. The assembly's manifest contains all the information need to use an assembly.

 

All assemblies have a manifest and all application that use the runtime must be made up of an assembly or assemblies. The entire file make up the assembly must be listed in the manifest. Manifest can be sorted in several ways. For an assembly with one associated file, the manifest is incorporated into the Portable Executable (PE) file to form a Single file Assembly. A Multi file Assembly can be created with either the manifest as a standalone file or incorporated with one of the PE file in the assembly.
 

The manifest contain following information’s
 

1. Assembly Name
Contain a textual string name of the Assembly.
2. Version Information
It Consists of Major and Minor Version number, a Version and a build number. These numbers are used by the runtime enforcing version policy.
3. Shared Name Information
It contains the public key from the publisher and a hash of the file contains the manifest signed with the publisher private key.
4. Culture, Processor and OS Support
It contains information on the Culture, Processor and OS of Assembly support. For this release, the Processor and OS information is ignored by the runtime.
5. List of all Files in the Assembly
It consist of a hash of each files contained in the assembly and relative path to the file from the manifest file.
6. Type Reference Information
It contains the information used by the runtime to map a type reference to the file that contains its declaration and implementation.
7. Information on Referenced Assembly
It contains a list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly’s name, metadata and the public key if the assembly is shared.
A developer can also set custom assembly attribute in code. These attribute are informational only and are not used by the runtime in any way. Custom attribute includes.
1. Title: - provide a friendly name, which include spaces. For e.g. Name of an assembly may be comdlg, while assembly title would be Microsoft Common Dialog control.
2. Description: - A short description of the assembly.
3. Default Alias: - Provides a friendly default alias in case the assembly name is not friendly or a GUID.
4. Configuration Information: - consists of a string that can be set to any value for configuration information such as Retail or Debug.
5. Product Information: - such as Trademark, Copyright, Product, company etc.


2. Metadata


Metadata describes all classes and class members that are defined in the assembly, and the classes and class members that the current assembly will call from another assembly. Meta data is a binary Information describing your code that is either stored in a >NET Framework Portable executable (PE) file or in the memory. When your code is complied into a PE file, Metadata is inserted into one portion of the file while your code is converted to Microsoft Intermediate Language (MSIL) and inserted into another. Every type and members are defined and referred in file or assembly described in Metadata. When code is executed CLR run time loads the Metadata information into in-memory data structure that it references when it requires information about code class, members, inheritance etc. Runtime refection services are used to retrieve information from in-memory data structure.

Many key .NET Framework benefits are from the runtime usage of metadata. Metadata provide a common frame of reference that enables communication between the runtime, compliers, debuggers, and code that has been complied into MSIL. It enables the runtime to locate and load your code, generate native code at runtime, and provide memory management services. The runtime able to track which portion of your code is allowed to access and preventing it from assessing memory that it shouldn't. Metadata also helps the runtime and garbage collection keep the track of memory that will be released back into operating system that is no longer is needed. The information stored in the metadata also enables the CLR to enable security by tracking the access privileges that your code request and granted.

Microsoft Intermediate Language (MSIL)

It is also known as Common Intermediate Language. You can use any .Net compliers for compiling the .Net application and converted into MSIL. The main purpose of this Intermediate code formation is to have a platform independent code. You can run the MSIL code on any platform provided appropriate run time environments are installed on the specific platform you wish to run. The.NET compiler can generate code written using any supported languages and finally convert it to the required machine code depending on the target machine.

Types of Assembly

Mainly there are 3 Types of Assemblies
1. Private assembly- can be accessed only by single application
2. Public/shared assembly-can be accessed by multiple applications in a system.
3. Satellite Assemblies- Used for Multilingual application

Creating and Calling Private Assembly


Creating .dll for Private Assembly


1. Open MSVS then click the File->New ->Project, New Window will open, from that select Visual C# from Project Types and select "Class Library" from Templates, name the project as PrivareClassLibrary




2. Then new Class1.cs form will open and change the class name to MyClass, then write the below code in the form


using
System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace
PrivateClassLibrary
{
public class MyClass
{
public string Display()
{
return "Hi-From Private Assembly";
}

}

}

3. Then click on Build->Build PrivateClassLibrary

4. Then go to your project saved folder->PrivateClassLibrary->Bin->Debug there you can see the .dll file ( PrivateClassLibrary.dll)

Calling Private Assembly


Select New project as mentioned above, click on WindowsFormsApplication instead of class library, change name as ClassLibraryCalling, then press ok. New window will open, and then Right Click the References in the Solution Explore-> Add Reference, new window will open, Click the Browse Tab, locate the PrivateClassLibrary.dll and click the file and the press ok. Now you can see the PrivateClassLibrary appeared in the Reference


Then select the form and add a button write this code in the form


using
System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace
ClassLibraryCalling
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private
void button1_Click(object sender, EventArgs e)
{
PrivateClassLibrary.MyClass obj = new PrivateClassLibrary.MyClass();
MessageBox.Show(obj.Display());
}
}
}

We are calling class object like PrivateClassLibrary.MyClass obj because we placed our class MyClass in PrivateClassLibrary Namespace




Creating and Calling Public Assembly


Creating .dll for Public Assembly


Private Assemblies are placed in Global Assembly Cache(GAC), the one of the main difference between public and private assembly is that Public assembly is do not copied to Bin/Debug folder of the application, it can be referred any application but only one copy is stored. In order to create a public assembly we need to do mainly three things

1. Create a strong name to Assembly
2. Associate strong name with assembly
3. Install the public assembly in GAC

Creating Assembly

1. Create a class files (use above same steps used in Private assembly) and name it as "PublicClassLibrary" and paste the following code in the class file

using
System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PublicClassLibrary
{
public class MyClass
{
public string Display()
{
return "Hi-From Private Assembly";
}
}
}

3. Then click on Build->Build PublicClassLibrary


4. Then go to your project saved folder->PublicClassLibrary->Bin->Debug there you can see the .dll file (PublicClassLibrary.dll)


5. Creating Strong Name

Open Visual Studio Command Prompt


In order to pace the dll file in the GAC we need to create a Strong Name for the assembly, Strong name is a combination of Private key and public key, for creating strong name click Start->Programs-> Microsoft Visual Studio 2008( or your version) -> Visual Studio Tools -> Visual Studio 2008 Command Prompt , then go to the Application folder where your class file is located. Then Type the following command sn –k dllfilename.key
sn –k PublicClassLibrary.key
Then you get a following message that “Key pair written to PublicClassLibrary.key “
You can see new file PublicClassLibrary.key is created at that folder.

6. Associate strong name with assembly

Open the PublicClassLibrary Application, Select PublicClassLibrary properties from project tab and new window will open with name PublicClassLibrary, from the signing tab(Left side-Bottom) check 'Sign the assembly' check box, select PublicClassLibrary.key file using 'Choose a strong name key file combo box'. Then close the window and Build the solution again using Build->Build Solution



7. Installing Assembly in GAC

GAC is a folder name Assembly in Windows, In order to place assembly in GAC, using Visual Studio Command Prompt go to the Bin/Debug folder where assembly (Dll) file is placed, Type
 

gacutil -i PublicClassLibrary.dll
After that you will get a message that “Assembly successfully added to the cache”. Now the assembly is placed in GAC and you can refer it to any other project.

Calling Public Assembly


Select New project as mentioned above, click on WindowsFormsApplication instead of class library, change name as PublicClassLibraryCalling, then press ok. New window will open, and then Right Click the References in the Solution Explore-> Add Reference, new window will open, Click the Browse Tab, locate the PublicClassLibrary.dll and click the file and the press ok. Then add a button in the form and write the following code in the form


using
System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace
WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private
void button1_Click(object sender, EventArgs e)
{
PublicClassLibrary.MyClass obj = new PublicClassLibrary.MyClass();
MessageBox.Show(obj.Display());
}
}
}

If you place an assembly in GAC, it will not create any copy of Assembly in Bin folder of Application.


Download This Program


Donload Private Assembly
Donload Public Assembly


In Order work Public Assembly program you need to place the Assembly in GAC as explained above

Sunday, 22 January 2012

Introduction to Delegates and Events

This lesson introduces delegates and events. Our objectives are as follows:
  • Understand What a Delegate Is
  • Understand What an Event Is
  • Implement Delegates
  • Fire Events

Delegates

During previous lessons, you learned how to implement reference types using language constructs such as classes and interfaces. These reference types allowed you to create instances of objects and use them in special ways to accomplish your software development goals. Classes allow you to create objects that contained members with attributes or behavior. Interfaces allow you to declare a set of attributes and behavior that all objects implementing them would publicly expose. Today, I'm going to introduce a new reference type called a delegate.
A delegate is a C# language element that allows you to reference a method. If you were a C or C++ programmer, this would sound familiar because a delegate is basically a function pointer. However, developers who have used other languages are probably wondering, "Why do I need a reference to a method?". The answer boils down to giving you maximum flexibility to implement any functionality you want at runtime.
Think about how you use methods right now. You write an algorithm that does its thing by manipulating the values of variables and calling methods directly by name. What if you wanted an algorithm that was very flexible, reusable, and allowed you to implement different functionality as the need arises? Furthermore, let's say that this was an algorithm that supported some type of data structure that you wanted to have sorted, but you also want to enable this data structure to hold different types. If you don't know what the types are, how could you decide an appropriate comparison routine?  Perhaps you could implement an if/then/else or switch statement to handle well-known types, but this would still be limiting and require overhead to determine the type. Another alternative would be for all the types to implement an interface that declared a common method your algorithm would call, which is actually a nice solution. However, since this lesson is about delegates, we'll apply a delegate solution, which is quite elegant.
You could solve this problem by passing a delegate to your algorithm and letting the contained method, which the delegate refers to, perform the comparison operation. Such an operation is performed in Listing 14-1.
Listing 14-1. Declaring and Implementing a Delegate: SimpleDelegate.cs
using System;

// this is the delegate declaration
public delegate int Comparer(object obj1, object obj2);

public class Name
{
    public string FirstName = null;
    public string LastName = null;

    public
Name(string first, string last)
    {
        FirstName = first;
        LastName = last;
    }

   
// this is the delegate method handler
    public
static int CompareFirstNames(object name1, object name2)
    {
        string n1 = ((Name)name1).FirstName;
        string n2 = ((Name)name2).FirstName;

        if
(String.Compare(n1, n2) > 0)
        {
            return 1;
        }
        else if (String.Compare(n1, n2) < 0)
        {
            return -1;
        }
        else
        {
            return 0;
        }
    }

    public
override string ToString()
    {
        return FirstName + " " + LastName;
    }
}

class
SimpleDelegate
{
    Name[] names =
new Name[5];

    public
SimpleDelegate()
    {
        names[0] =
new Name("Joe", "Mayo");
        names[1] =
new Name("John", "Hancock");
        names[2] =
new Name("Jane", "Doe");
        names[3] =
new Name("John", "Doe");
        names[4] =
new Name("Jack", "Smith");
    }

    static
void Main(string[] args)
    {
        SimpleDelegate sd =
new SimpleDelegate();

       
// this is the delegate instantiation
       
Comparer cmp = new Comparer(Name.CompareFirstNames);

        Console.WriteLine("\nBefore Sort: \n");

        sd.PrintNames();

        // observe the delegate argument
        sd.Sort(cmp);

        Console.WriteLine("\nAfter Sort: \n");

        sd.PrintNames();
    }

    // observe  the delegate parameter
    public void Sort(Comparer compare)
    {
        object temp;

        for
(int i=0; i < names.Length; i++)
        {
            for (int j=i; j < names.Length; j++)
            {
                // using delegate "compare" just like
                // a normal method
                if ( compare(names[i], names[j]) > 0 )
                {
                    temp = names[i];
                    names[i] = names[j];
                    names[j] = (Name)temp;
                }
            }
        }
    }

    public
void PrintNames()
    {
        Console.WriteLine("Names: \n");

        foreach
(Name name in names)
        {
            Console.WriteLine(name.ToString());
        }
    }
}

The first thing the program in Listing 14-1 does is declare a delegate. Delegate declarations look somewhat like methods, except they have the delegate modifier, are terminated with a semi-colon (;), and have no implementation. Below, is the delegate declaration from Listing 14-1.
public delegate int Comparer(object obj1, object obj2);
This delegate declaration defines the signature of a delegate handler method that this delegate can refer to. The delegate handler method, for the Comparer delegate, can have any name, but must have a first parameter of type object, a second parameter of type object, and return an int type. The following method from Listing 14-1 shows a delegate handler method that conforms to the signature of the Comparer delegate.
    public static int CompareFirstNames(object name1, object name2)
    {
        ...
    }

Note: The CompareFirstNames method calls String.Compare to compare the FirstName properties of the two Name instances. The String class has many convenience methods, such as Compare, for working with strings. Please don't allow the implementation of this method to interfere with learning how delegates work. What you should concentrate on is that CompareFirstNames is a handler method that a delegate can refer to, regardless of the code inside of that method.
To use a delegate, you must create an instance of it. The instance is created, similar to a class instance, with a single parameter identifying the appropriate delegate handler method, as shown below.
        Comparer cmp = new Comparer(Name.CompareFirstNames);
The delegate, cmp, is then used as a parameter to the Sort() method, which uses it just like a normal method. Observe the way the delegate is passed to the Sort() method as a parameter in the code below.
        sd.Sort(cmp);
Using this technique, any delegate handler method may be passed to the Sort() method at run-time. i.e. You could define a method handler named CompareLastNames(), instantiate a new Comparer delegate instance with it, and pass the new delegate to the Sort() method.

Events

Traditional Console applications operate by waiting for a user to press a key or type a command and press the Enter key. Then they perform some pre-defined operation and either quit or return to the original prompt that they started from. This works, but is inflexible in that everything is hard-wired and follows a rigid path of execution. In stark contrast, modern GUI programs operate on an event-based model. That is, some event in the system occurs and interested modules are notified so they can react appropriately. With Windows Forms, there is not a polling mechanism taking up resources and you don't have to code a loop that sits waiting for input. It is all built into the system with events.
A C# event is a class member that is activated whenever the event it was designed for occurs. I like to use the term "fires" when the event is activated. Anyone interested in the event can register and be notified as soon as the event fires. At the time an event fires, registered methods will be invoked.
Events and delegates work hand-in-hand to provide a program's functionality. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event. The delegate may be one of the pre-defined .NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires. Listing 14-2 shows a couple different ways to implement events.
Listing 14-2. Declaring and Implementing Events: Eventdemo.cs
using System;
using System.Drawing;
using System.Windows.Forms;

// custom delegate
public delegate void Startdelegate();

class Eventdemo : Form
{

    // custom event
    public event Startdelegate StartEvent;

    public Eventdemo()
    {
        Button clickMe =
new Button();

        clickMe.Parent =
this;
        clickMe.Text = "Click Me";
        clickMe.Location =
new Point(
            (ClientSize.Width - clickMe.Width) /2,
            (ClientSize.Height - clickMe.Height)/2);

        // an EventHandler delegate is assigned
        // to the button's Click event
        clickMe.Click += new EventHandler(OnClickMeClicked);

        // our custom "Startdelegate" delegate is assigned
        // to our custom "StartEvent" event.
        StartEvent += new Startdelegate(OnStartEvent);

        // fire our custom event
        StartEvent();
    }

    // this method is called when the "clickMe" button is pressed
    public void OnClickMeClicked(object sender, EventArgs ea)
    {
        MessageBox.Show("You Clicked My Button!");
    }

    // this method is called when the "StartEvent" Event is fired
    public void OnStartEvent()
    {
        MessageBox.Show("I Just Started!");
    }

    static
void Main(string[] args)
    {
        Application.Run(
new Eventdemo());
    }
}

Note: If you're using Visual Studio or another IDE, remember to add references to System.Drawing.dll and System.Windows.Forms.dll before compiling Listing 14.2 or just add the code to a Windows Forms project. Teaching the operation of Visual Studio or other IDE's is out-of-scope for this tutorial.
You may have noticed that Listing 14-2 is a Windows Forms program. Although I haven't covered Windows Forms in this tutorial, you should know enough about C# programming in general that you won't be lost. To help out, I'll give a brief explanation of some of the parts that you may not be familiar with.
The Eventdemo class inherits Form, which essentially makes it a Windows Form. This automatically gives you all the functionality of a Windows Form, including Title Bar, Minimize/Maximize/Close buttons, System Menu, and Borders. A lot of power, that inheritance thing, eh?
The way a Windows Form's application is started is by calling the Run() method of the static Application object with a reference to the form object as its parameter. This starts up all the underlying Windows plumbing, displays the GUI, and ensures that events are fired as appropriate.
Let's look at the custom event first. Below is the event declaration, which is a member of the Eventdemo class. It is declared with the event keyword, a delegate type, and an event name.
    public event Startdelegate StartEvent;
Anyone interested in an event can register by hooking up a delegate for that event. On the next line, we have a delegate of type Startdelegate, which the event was declared to accept, hooked up to the StartEvent event. The += syntax registers a delegate with an event. To unregister with an event, use the -= with the same syntax.
        StartEvent += new Startdelegate(OnStartEvent);
Firing an event looks just like a method call, as shown below:
StartEvent();
This was how to implement events from scratch, declaring the event and delegate yourself. However, much of the event programming you'll do will be with pre-defined events and delegates. This leads us to the other event code you see in Listing 14-2, where we hook up an EventHandler delegate to a Button Click event.
        clickMe.Click += new EventHandler(OnClickMeClicked);
The Click event already belongs to the Button class and all we have to do is reference it when registering a delegate. Similarly, the EventHandler delegate already exists in the System namespace of the .NET Frameworks Class Library. All you really need to do is define your callback method (delegate handler method) that is invoked when someone presses the clickMe button. The OnClickMeClicked() method, shown below, conforms to the signature of the EventHandler delegate, which you can look up in the .NET Framework Class Library reference.
    public void OnClickMeClicked(object sender, EventArgs ea)
    {
        MessageBox.Show("You Clicked My Button!");
    }

Any time the clickMe button is pressed with a mouse, it will fire the Click event, which will invoke the OnClickMeClicked() method. The Button class takes care of firing the Click event and there's nothing more you have to do. Because it is so easy to use pre-defined events and delegates, it would be a good idea to check if some exist already that will do what you need, before creating your own.

C# 4.0 dynamic keyword for Dummies – Under the hood


  1. C# 4.0 dynamic keyword
  2. C# Dynamic Binding – Language Binding

Static Typing or Early Binding

Let us start with a bare minimum program. Fire up VS2010 and try the following code.
image

It is obvious that this won’t compile. Simply because, the compile/design time checking ensures type safety - and as we don’t have a method named SomeStupidCall in our Human class, we can’t compile the same.

image

So, that is what you get.

Duck Typing or Dynamic Typing or Late Binding
 
Now, let us take a step back, and modify the above code like this. Change the type of variable h to ‘dynamic’. And Compile. Here is a little surprise!! You got it compiled!!  By using ‘dynamic’ keyword, you just told the compiler, “dude, don’t bother if SomeStupidCall() is there in the Human 


typeimage

And now, run the application. The application will break for sure. But hey, that is your fault, not the compiler’s.

image
By the way, why we call dynamic typing as ‘Duck typing’?
image
Here we go, Quoted from Wikipedia
In duck typing, one is concerned with just those aspects of an object that are used, rather than with the type of the object itself. For example, in a non-duck-typed language, one can create a function that takes an object of type Duck and calls that object's walk and quack methods. In a duck-typed language, the equivalent function would take an object of any type and call that object's walk and quack methods. If the object does not have the methods that are called then the function signals a run-time error. It is this action of any object having the correct walk and quack methods being accepted by the function that evokes the quotation and hence the name of this form of typing.
Now, why you need ‘dynamic’ at all?
I hope the above scenario is ‘good’ enough to give you an ‘evil’ impression about the dynamic features. But, wait. There are lot of scenarios where the dynamic features can really simplify things for you. For example, let us assume a reflection based scenario, where you load a type (from an external assembly or so), to invoke a member. Here is a quick example. You’ll see how to use dynamic as an easier alternative for reflection. This is much more evident when you deal with scenarios like COM interop etc. We’ll see more interesting uses later.

image

How a ‘dynamic’ type is getting compiled?

Let us get back to a basic example. Consider a human class, with a Walk() method and Age property. Now, let us create a new Human and assign this to a dynamic variable ‘h’.

image

Let us build the above application. Fire up Reflector, open the binary executable of the app, and have a look at the same. With a bit of cleanup, this is the relevant part of the disassembled code - which is the equivalent 'statically’ typed code generated by the compiler, for the ‘dynamic’ code we wrote above.
You’ll see a ‘SiteContainer’, for keeping track of the context, and two call site fields.
image
And here is the disassembled code for the member invocations. It might be interesting to note that, the variable ‘h’ is compiled as a simple CLR ‘object’.

Wow, from the CLR point of few, there is nothing like a ‘dynamic’ type. Instead, all member invocations to our ‘dynamic’ object are modified; in such a way that they are piped through a dynamic Call Site. The Call Site is initialized with the Binder responsible for run time binding. In this case, you may note that the C# run time binder will be used to invoke the members(Microsoft.CSharp.RuntimeBinder.Binder ‘s InvokeMember will return a CallSite binder, that’ll be used by the Call Site).

image

You might be thinking how the code will be generated for scenarios where, you have a method that accepts or returns a ‘dynamic’ type, or a property that gets or sets a dynamic type. Let us try this out. Change our above Human class in the above example, to something like this. Note that now Walk method accepts a dynamic type, and Age property is also modified to get/set dynamic types.

image

Have a sneak peak using Reflector. You’ll note that, the compiler has generated a special [Dynamic] attribute to the input parameter of Walk() method. Also, the getter and setter of the Age property is also decorated with the [Dynamic] attribute, as shown below.

image 

And here is some code of the final form of our experiment. Create a Console app in C# 4.0, to play with this.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Runtime.CompilerServices;  
  6. using Microsoft.CSharp.RuntimeBinder;  
  7.   
  8. namespace DynamicTest  
  9. {  
  10.     class Human  
  11.     {  
  12.         public void Walk(dynamic place)  
  13.         {  
  14.             Console.WriteLine("I'm walking to " + place);  
  15.         }  
  16.         public dynamic Age { getset; }  
  17.     }  
  18.   
  19.     class Program  
  20.     {  
  21.           // Methods  
  22.     private static void Main(string[] args)  
  23.     {  
  24.         //dynamic h = new Human();  
  25.         //h.Walk("Paris");  
  26.         //h.Age = 10;  
  27.   
  28.         //will get compiled to  
  29.   
  30.         object h = new Human();  
  31.   
  32.         //Create the site 1 if it is null  
  33.         if (SiteContainer0.Site1 == null)  
  34.         {  
  35.             SiteContainer0.Site1 = CallSite<Action<CallSite, objectstring>>.Create  
  36.                 (Binder.InvokeMember(CSharpBinderFlags.ResultDiscarded, "Walk",   
  37.                 nulltypeof(Program), new CSharpArgumentInfo[]   
  38.                 { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),   
  39.                   CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.LiteralConstant   
  40.                   | CSharpArgumentInfoFlags.UseCompileTimeType, null) }));  
  41.         }  
  42.         SiteContainer0.Site1.Target(SiteContainer0.Site1, h, "Paris");  
  43.   
  44.         //Create the site 2 if it is null  
  45.         if (SiteContainer0.Site2 == null)  
  46.         {  
  47.             SiteContainer0.Site2 = CallSite<Func<CallSite, objectintobject>>.Create  
  48.                 (Binder.SetMember(CSharpBinderFlags.None, "Age"typeof(Program),   
  49.                 new CSharpArgumentInfo[]   
  50.                 { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),   
  51.                     CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.LiteralConstant |   
  52.                     CSharpArgumentInfoFlags.UseCompileTimeType, null) }));  
  53.         }  
  54.         SiteContainer0.Site2.Target(SiteContainer0.Site2, h, 10);  
  55.     }  
  56.       
  57.   
  58.     // Nested Types  
  59.     [CompilerGenerated]  
  60.     private static class SiteContainer0  
  61.     {  
  62.         // Fields  
  63.         public static CallSite<Action<CallSite, objectstring>> Site1;  
  64.         public static CallSite<Func<CallSite, objectintobject>> Site2;  
  65.     }  
  66.   
  67.     }  
  68.   
  69. }  
  70.  

     

    C# Dynamic Binding – Language Binding

    Language binding is a form of dynamic binding which occurs when a dynamic object does not implement IDynamicMetaObjectProvider.
  71.   Language binding comes in handy when working around imperfectly designed types or the inherent limitations in the .NET type system. A common problem is that when using numeric types is they have no common interface. Using dynamic binding, methods can be bound dynamically and the same also applies for operators:
     
    static dynamic Mean (dynamic xObj, dynamic yObj)
    {
    return (xObj + yObj) / 2;
    }
    static void Main()
    {
    int xObj = 3, yObj = 4;
    Console.WriteLine (Mean (xObj, yObj));
    }

    The benefit here is clear — you can avoid duplicating code for each numeric type. However, in doing so you will lose static type safety, risking runtime exceptions as opposed to getting compile time errors.

  72. Note that dynamic binding only circumvents static type safety, runtime type safety is still perserved. In contrast when using reflection, you cannot circumvent member accessibility rules using dynamic binding.
    Language runtime binding behaves very similarly to static binding when the runtime types of the dynamic objects are known at compile time. In the above example, the behavior of the program would be identical if Mean was hardcoded to work with the int type.
     

Anonymous Types In C# 3.0

This post is about the Anonymous types in C#, and the object initializer syntax.

It is well known that starting from C# 3.0, you can initialize an object like this.

  1. var boy = new { Name = "Jim", Age = 2 };  
You specify the properties of an object, and at compile time, the compiler will create a new (anonymous) type, with the properties you specify, and with a constructor that can take the same number of arguments.

Now, let us examine our anonymous type in detail by using reflection. We'll examine whether the type is a class, along with the type's name. If you run this,

  1. static void Main(string[] args)  
  2.         {  
  3.   
  4.             var boy = new { Name = "Jim", Age = 2 };  
  5.   
  6.             Console.WriteLine("Name=" + boy.GetType().Name);  
  7.             Console.WriteLine("BaseType=" + boy.GetType().BaseType.Name);  
  8.             Console.WriteLine("Asm=" + boy.GetType().Assembly.FullName);  
  9.             Console.WriteLine("IsClass=" + boy.GetType().IsClass);  
  10.         }  

You'll get some output like
Name=<>f__AnonymousType0`2
BaseType=Object
Asm=AnonymousTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
IsClass=True

Needless to say, the Name will be a random name, and the Assembly's name depends on your own project name. The key point is, we just established that the type is there in the assembly - which means, as I mentioned, the compiler created a type at compile time itself. You can have a look at the IL if you are interested.

Now, let us examine the observation that the anonymous type has a constructor that takes the same number of arguments as that of properties (i.e, in this case, the number of constructor arguments will be equal to the number of properties we specified in the object initializer, of types string and int). We can do that easily by creating a new instance of the anonymous type we have, using reflection. Add this to the tail end of the last piece of code.

  1. //These two calls will fail with a run time exception, Just keep them commented  
  2. //var newboy = Activator.CreateInstance(boy.GetType(), null);  
  3. //var newboy = Activator.CreateInstance(boy.GetType(), new object[] { "Joe"});  
  4.   
  5. //Only this will work. Creating a new boy  
  6. var newboy=Activator.CreateInstance(boy.GetType(),new object[]{"Joe",2});  
  7.   
  8. //Just write back the name of new boy  
  9. Console.WriteLine(newboy.GetType().GetProperty("Name").GetValue(newobj, null));  

You can see that only the last call will work, as we need to pass the same number of arguments while instantiating.

Note that you can have arrays of anonymous types as well, like this.

  1. var guys = new[]  
  2.          {  
  3.                  new {Name="Joe", Age=10},  
  4.                  new {Name="James", Age=22},  
  5.                  new {Name="Jim", Age=23},  
  6.                  new {Name="Jerard", Age=10},  
  7.          };  

Further more, I just want to mention one more point. You may not need to assign the property explicitly, when you use the object initializer syntax. Consider this code.

  1. var guy1 = new { Name = "Ken", Age = 30 };  
  2. var guy2 = new { guy1.Name, Age = 30 };  
  3.   
  4. Console.WriteLine(guy1.GetType().Name + " - " + guy1.Name);  
  5. Console.WriteLine(guy2.GetType().Name + " - " + guy2.Name);  


The key point to note here is, for guy 2, we are not explicitly specifying the Name property. Instead, we are just specifying that the name of Guy2 is same as Guy1. The compiler will assume the property name from the given parameter's name (in fact, the last part of the specified parameter, in this case 'Name') - This is called Projection. Obviously, you'll find that both guy1 and guy2 are of the same type as well.

Can you guess the output of this code as well?

  1. string Name = "Guy2";  
  2.   
  3. var guy1 = new { Name = "Ken", Age = 30 };  
  4. var guy2 = new { Name, Age = 30 };  
  5.   
  6. Console.WriteLine(guy1.GetType().Name + " - " + guy1.Name);  
  7. Console.WriteLine(guy2.GetType().Name + " - " + guy2.Name);  


Why anonymous types are interesting? Because we use them in various ways, especially while using LINQ syntax. Here is a basic example


  1. var oldGuys = from guy in guys  
  2.                           where guy.Age > 20  
  3.                           select new { guy.Name };  

Top 7 Coding Standards and Guideline Documents For C#/.NET Developers


As you may already know, it is easy to come up with a document - the key is in implementing these standards in your organization, through methods like internal trainings, Peer Reviews, Check in policies, Automated code review tools etc. You can have a look at FxCop and/or StyleCop for automating the review process to some extent, and can customize the rules based on your requirements.
Anyway, here is a list of some good Coding Standard Documents. They are useful not just from a review perspective - going through these documents can definitely help you and me to iron out few hidden glitches we might have in the programming portion of our brain.
So, here we go, the listing is not in any specific order.
1 – IDesign C# Coding Standards
IDesign C# coding standards is a pretty decent and compact (27 pages) Coding Standards Document. It covers a Naming conventions, Best practices and Framework specific guidelines. Example:
image
The document even has guidelines for project settings, build configuration, versioning etc. Good work by IDesign guys. You can download the document here
2 – Encodo C# Handbook
Encodo C# handbook is bit more recent, and has 72 pages of guidelines on Structure, Formatting, Naming. It also has a ‘Patterns and Best Practices’ section, which is a must read for any .NET/C# developer.
image
You can download the Handbook here.
3 – Microsoft Framework Design Guidelines
MSDN has a section on guidelines for Designing class libraries, which covers a set of best practices related to Type Design, Member Design etc. You can find it here.
4 – Denni’s C# Coding Standards document
Dennis created an initial version of C# coding standards, which was published as Philips Health Care C# coding standards document (~70 pages). The document categorizes the guidelines to categories like Naming, Exception Handling, Control Flow etc.
  • Update: Dennis kindly pointed that the Initial Version I linked here earlier has now been superseded by the Coding Guidelines for C# 3.0 and C# 4.0. Paul Jansen of Tiobe will update his site soon regarding the new version - But in meantime, download the guidelines and some companion documents here: http://csharpguidelines.codeplex.com/
5 – Microsoft’s All-In-One Code Framework Coding Guideline
Microsoft’s All In One Code framework has a Coding Style Guideline document. The Microsoft All-In-One Code Framework is a free, centralized code sample library provided by the Microsoft Community team. It has typical code samples for all Microsoft development technologies, and a code style guideline document with that. Thanks to Kevin for pointing out this guideline document with All In One Code Framework (See the comments)
6 – Brad’s Quick Post on Microsoft Internal Coding Guidelines
Brad had a post on Microsoft Internal coding standards (I’m not sure whether he still follow that in Google, if at all he uses C# there). It is a short post, and is mainly on Styling and Naming conventions.
7 – Mike’s C# Coding Style Guide
Mike Kruger (Sharpdevelop) had published a 13 page C# Coding Style guide. Again, the focus is on Casing, Naming conventions, Declaration style etc. A short and simple Style Guide.
So, if you are still confused about which document to choose - my recommendation is here for you - Based on your landscape, organizational climate, project and domain, go through these documents and pick the relevant recommendations – to formulate your very own 10 page ‘.NET/C# Coding standards/guidelines’ for your team.
Also, if you think I missed any prominent guideline document, list down the same in the comments section, and I’ll include that in the main post if it is relevant – My initial post was about 6 documents, but I expanded/modified the list later based on some feedback I received. Happy Coding.

Inserting in Excel file from C# collection using Open XML

Inserting in Excel file from C# collection using Open XML SDK 2.0


In this post I will show inserting rows in excel file from a c Sharp list using Open XML SDK. Open XML SDK is very useful when you don’t want to or cannot use Microsoft Office InterOP dll.
You can download it from below URL
http://www.microsoft.com/download/en/details.aspx?id=5124
Once you download and run the MSI follow the below steps.
Creating Data Source to be inserted in excel
Let us say you have class as below,
image
And below function returning list of bloggers. We are going to insert all the items from this list in Excel file.
01private List<Bloggers> GetDataToInsertInExcel()
02{
03List<Bloggers> lstBloggers = new List<Bloggers>
04{
05new Bloggers
06{
07Name = "Pinal Dave",
08Interest = "SQL Server",
09NumberofPosts = 1500,
10Speaker = true
11},
12new Bloggers
13{
14Name = "Mahesh Chand",
15Interest = "C Sharp",
16NumberofPosts = 1300,
17Speaker = true
18},
19new Bloggers
20{
21Name = "Debug Mode",
22Interest = "all",
23NumberofPosts = 400,
24Speaker = false
25},
26new Bloggers
27{
28Name = "Shiv Prasad Koirala",
29Interest = "ASp.Net",
30NumberofPosts = 500,
31Speaker = true
32},
33new Bloggers
34{
35Name = "Anoop Madusudhan",
36Interest = "WCF",
37NumberofPosts = 500,
38Speaker = false
39},
40};
41return lstBloggers;
42}
43 
44&nbsp;
45 
46&nbsp;
You are very much free to change data source to
  • Azure table
  • SQL Server table
  • SQL Azure table
Theoretically you can use any data source provided you are converting the result in List. If you are using SQL Server or SQL Azure, you can use LINQ to SQL to create data source.
Since now we have data source, let us insert the items of list in the excel file using open xml SDK.
Add Namespaces
You need to add below namespaces,
image
Have a Template
If you notice we have four properties in entity class. So there would be four columns in the excel sheet. Save an excel file with any name of your preference at any location of your preference. For purpose of this article I am saving it to the
image
There are three points worth noticing about the template
  1. All the columns [properties of entity class] is in first row in columns A, B,C,D
  2. Sheet is renamed to items. If you want you can have default name.
  3. Template excel file with name testupload is in d drive.
Opening the template file to insert rows

image
If you have save template Excel file with different name in different location then you will have to change the location in above code.
If you have changed the sheet name to item then you will fetch it as below,

image

If you have not renamed the sheet and want to insert in the first sheet, you can do like below. Make note of code in comment to fetch the first sheet.

image
Inserting the rows
Now document is open, so we need to insert rows one by one. So we will loop through all the items in list and call a function to create row. On successful return of the row from function we will append it to the open sheet.
image
If you notice above code snippet I have initialized index value to 2 because in first row of the excel sheet, we are putting the header. From second row onward items in each row would get inserted. I am making call to CreateContentRow function.
Creating the rows

image
In you notice above that in header columns string array, we are starting from A to D. It is because we have only four columns to insert. If you have 6 columns to insert then string array would be from A to F.

In above snippet I am iterating through all the properties of the entity object and creating cell reference by appending index with column headers.
Next I need to find type of property .There may be three types
  1. String
  2. Integer
  3. Boolean
We need to check for the type of property and then create the cell to insert the value
Checking for String
image
Checking for Integer

image
Checking for Boolean
image
Putting all together all pieces of codes we discussed above, for your reference whole source code is as below,
001using System;
002using System.Collections.Generic;
003using DocumentFormat.OpenXml.Packaging;
004using DocumentFormat.OpenXml.Spreadsheet;
005 
006namespace ConsoleApplication28
007{
008class Program
009{
010static void Main(string[] args)
011{
012CreatingAndUploadingExcel();
013}
014Public static bool CreatingAndUploadingExcel()
015{
016 
017using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open("d:\\LocalCollection.xlsx", true))
018{
019//WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
020 
021WorkbookPart workbookPart = myWorkbook.WorkbookPart;
022 
023IEnumerable<Sheet> Sheets = myWorkbook.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().Where(s=>s.Name=="items");
024if (Sheets.Count() == 0)
025{
026// The specified worksheet does not exist.
027return false;
028}
029 
030string relationshipId = Sheets.First().Id.Value;
031WorksheetPart worksheetPart = (WorksheetPart)myWorkbook.WorkbookPart.GetPartById(relationshipId);
032SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
033 
034int index = 2;
035foreach (var entity in GetDataToInsertInExcel())
036{
037 
038Row contentRow = CreateContentRow(index, entity);
039index++;
040sheetData.AppendChild(contentRow);
041}
042 
043workbookPart.Workbook.Save();
044 
045}
046 
047}
048string[] headerColumns = new string[] { "A", "B","C","D"};
049private Row CreateContentRow(int index, Bloggers objToInsert)
050{
051 
052Row r = new Row ();
053r.RowIndex = (UInt32) index;
054int i = 0;
055 
056foreach (var prop in objToInsert.GetType().GetProperties())
057{
058Cell c = new Cell();
059c.CellReference = headerColumns[i].ToString() + index;
060 
061if (prop.PropertyType.ToString().Equals("System.string", StringComparison.InvariantCultureIgnoreCase))
062{
063 
064var result = prop.GetValue(objToInsert, null);
065 
066if (result == null)
067{
068result = "";
069}
070 
071c.DataType = CellValues.String;
072InlineString inlineString = new InlineString();
073Text t = new Text();
074t.Text = result.ToString();
075inlineString.AppendChild(t);
076c.AppendChild(inlineString);
077 
078}
079 
080if (prop.PropertyType.ToString().Equals("System.int32", StringComparison.InvariantCultureIgnoreCase))
081{
082 
083var result = prop.GetValue(objToInsert, null);
084if (result == null)
085{
086result = 0;
087}
088 
089CellValue v = new CellValue();
090v.Text = result.ToString();
091c.AppendChild(v);
092 
093}
094 
095if (prop.PropertyType.ToString().Equals("System.boolean", StringComparison.InvariantCultureIgnoreCase))
096{
097 
098var result = prop.GetValue(objToInsert, null);
099if (result == null)
100{
101result = "False";
102}
103c.DataType = CellValues.InlineString;
104InlineString inlineString = new InlineString();
105Text t = new Text();
106t.Text = result.ToString();
107inlineString.AppendChild(t);
108c.AppendChild(inlineString);
109 
110}
111 
112 
113r.AppendChild(c);
114i = i + 1;
115}
116 
117return r;
118 
119}
120private List<Bloggers> GetDataToInsertInExcel()
121{
122List<Bloggers> lstBloggers = new List<Bloggers>
123{
124new Bloggers
125{
126Name = "Pinal Dave",
127Interest = "SQL Server",
128NumberofPosts = 1500,
129Speaker = true
130},
131new Bloggers
132{
133Name = "Mahesh Chand",
134Interest = "C Sharp",
135NumberofPosts = 1300,
136Speaker = true
137},
138new Bloggers
139{
140Name = "Debug Mode",
141Interest = "all",
142NumberofPosts = 400,
143Speaker = false
144},
145new Bloggers
146{
147Name = "Shiv Prasad Koirala",
148Interest = "ASp.Net",
149NumberofPosts = 500,
150Speaker = true
151},
152new Bloggers
153{
154Name = "Anoop Madusudhan",
155Interest = "WCF",
156NumberofPosts = 500,
157Speaker = false
158},
159};
160return lstBloggers;
161}
162 
163}
164 
165}
166 
167public class Bloggers
168{
169public string Name { get; set; }
170public string Interest { get; set; }
171public int NumberofPosts { get; set; }
172public bool Speaker { get; set; }
173}
174 
175}
Now go ahead and open Excel file and you should get the row inserted. I hope this post was useful. Thanks for reading






Posted by October 4, 2011  Smile