Wednesday, August 12, 2015

All About Assemblies

This article is concerned with how to manage the .NET assemblies in your Project or GAC (Global Assembly Cache). All .NET programs that are constructed from these assemblies and almost everything you do in .NET leads to the creation of an assembly of some order. Every program runs on a layer of Software and Hardware abstraction called CLR (Common Language Runtime). CLR cannot directly convert the code to hardware platform (binary form). It has to perform some specific checks like version information, security permissions, properties, etc. The file or programming unit that satisfies all these needs of CLR is called an Assembly. Furthermore, assemblies are classified into two main types called Private assemblies and Shared assemblies.

Shared Assemblies

  1. Global Assembly Cache (GAC) = the path of gac is [parent directory] : [win dir] \assembly. Also you can view the GAC through Control Panel=> Administrative tools => Microsoft .NET Framework 3.0 Configuration. Under 'My Computer' node Click "Assembly Cache". It is the directory for assemblies. Assemblies residing in a GAC are shared by the number of applications. Each assembly is uniquely identified by its Strong Name.
  2. Creating a Shared Assembly = Every program that is written on the .NET Framework platform is an assembly. The difference is that if we want to use it as an assembly or not. OK. Write an errorless program such as the one I have given below... here I create an assembly called StrongFile that contains a class called Strong which has a method called Greeting.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    public class strong
        {
            public string Greeting(string name)
            {
                return ("Your assembly says Hi : " + name);
            }
            static void Main(string[] args)
            {
            }
        }
    Now assign the Strong Name to the assembly by using sn.exe (if you are a Visual Studio user). For Express Edition users, you can name it by going under Properties Page=>under Signing Tab => give the name, without using password protection. Here we are creating an assembly that will be shared by external developers, so assigning passwords creates sharing conflicts, hence do not make assembly password protected since we want to use it for global purposes.
    Note = Express Edition users must set the output type of the application to the Class library to get the assembly, so click on Properties=>Application=>OutputType and set it to Class Library.
    Edit the AssemblyInfo.cs file in the Properties folder of our project directory, i.e., StrongFile=>Properties=>AssemblyInfo.cs. Mention the following lines in the code that we created earlier.
    [assembly: AssemblykeyFile("FileKey.snk")] 
    Now build the Project; this will create signed StrongFile.dll in the bin=>Release=>StrongFile.dll. Drag it to GAC. Now we can use our StrongFile assembly whenever we want it. Just reference it!
  3. Changing the Version of our Assembly = we can simply change the version of our assembly by editing the AssemblyInfo.cs again.
    You can change the version by simply going to Project=>"Project" Properties=>Application=>Assembly Information=>Assembly Version. Build the Project. Don't forget to put the new assembly in GAC
    Note: You may notice though that after the project build, there is no assembly version change in Windows Explorer, but don't worry. Still place this new assembly in GAC - there you can see the new version ofStrongFile. Be sure to make changes only in the Assembly version NOT AssemblyFileVersion. For the changes to take effect, change something in our StrongFile code like I change here:
    public class strong
    {
            public string Greeting(string name)
            {
                return ("Your 'NEW' assembly says Hi : " + name);
            }
            static void Main(string[] args)
            {
            }
    } 
    After placing the new Assembly in GAC:

Private Assemblies

There is a minor difference between Traditional DLL and Assembly. Traditional DLLs could be copied to the client's directory for the client to use it and no other programs could know about them (that is the reason why still some game and software can be cracked). Assemblies take this feature. If there are only few applications that would ever use your library assembly, you can put them in the relevant client applications directory instead of putting in GAC. This will save your time in strong naming the assembly, editing AssemblyInfo.cs etc. Those assemblies which can be put in the applications directory and which do not need a strong name are called "Private Assemblies". Private assemblies can be installed/uninstalled without any fear of breaking the application. You may notice that one of our shared assembly StrongFile's properties is LocalCopy set tofalse, this means this assembly could not be copied locally to the applications' directory, but private Assembly has this property default "true" i.e., they are able to copy locally.
Another important concept related to private assemblies is "Delayed Signing"... which we going to study in the next section. Delayed Signing = It is possible that you come to a situation where you have to give your assembly for further modification to an external person/developer, but you cannot give him the private key of the assembly, then how could he work? This problem has been solved by the Delayed Signing technique. In this, we can skip the signing of the assembly with the private key and turn off the assembly verification. So now, the Assembly signs with only Public key. Now you can give the developer the assembly and public key only, there is no need of private key. This can be done like this, we have already created "StrongFile" assembly.
With the help of sn.exe, we can extract the public key in the file:
Syntax : sn -p [infile] [outfile] 
Extract the public key in key pair in [infile] and export it to the [outfile].
sn /p FileKey.snk PublicKey.snk   
This will create the file "PublicKey.snk" which contains the public key of our assembly StrongFile.
Now it's time to edit the AssemblyInfo.cs like this:

Build Assembly StrongFile again.
Note = If you delayed signing of assembly by Properties Signing tab, then you need not edit AssemblyInfo.cs.
Now we have to turn off the verification process in this way:
sn /Vr StrongFile.dll
Then, you will get the following message:

Now you can send the developer your assembly with the public key file only, i.e., StrongFile.dll assembly withThePublicKey.snk only. After he is done with his work, you can reassign the assembly with a private key like this:
sn /R StrongFile.dll FileKey.snk
NOTE
  1. Be careful about turing on/off the verification because an assembly with verification off can be replaced by any other assembly without being detected.Games and many wares are cracked in this way. Malicious users have replaced unsigned DLLs with the original ones. Even high engineered engines have failed to detect these changes.
  2. All sn.exe options are case-sensitive and must be typed exactly.
  3. If you are using Visual C# Express Edition, then you would not be able to use the "Visual Studio 2008 command Prompt". In this case, these utilities lay in the SDK's bin folder - the full path is "C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin", then let your command prompt in there and you are set to use it.To use these utilities permanently, change the Environment variables to the bin folder.
  4. Still Visual C# Express Edition is compact and lightweight, but it has its own drawbacks; like you would not able to use Configuration Tool that lies in the Control Panel=>Administrative tools. Moreover, these editions use lesser amount of Help Documentation.
Now we are moving to the last section of this article i.e. Manifests.

Manifests

An assembly is a self-describing programming unit. How is each assembly different from one another where assemblies store their information? The answer is "Manifests". The manifest identifies the assembly. It describes, lists other assemblies it depends on, all types and resources exposed by the assembly or used by assembly, its security requirements. Manifests can be viewed with the IL Dissembler - Intermediate Language Dissembler (ildasm.exe).
Using IL DASM = Go to Visual Studio 2008 command prompt and type ildasm - a window appears like this:

Here I open StrongFileApp.exe. Click on the MANIFEST and you will see:

You can see all the assemblies that our application referenced. If you further expand StrongFileApp node, then you can clearly see that every information of application is revealed like namespace, methods, buttons, etc.

ILDASM is used in debugging and testing of applications.

Monday, July 13, 2015

C# Collection Tutorial-Part-5

Queue
The Queue works like FIFO system , a first-in, first-out collection of Objects. Objects stored in a Queue are inserted at one end and removed from the other. The Queue provide additional insertion, extraction, and inspection operations. We can Enqueue (add) items in Queue and we can Dequeue (remove from Queue ) or we can Peek (that is we will get the reference of first item ) item from Queue. Queue accepts null reference as a valid value and allows duplicate elements.
Some important functions in the Queue Class are follows :
  Enqueue : Add an Item in Queue
  Dequeue : Remove the oldest item from Queue
Peek : Get the reference of the oldest item

Enqueue : Add an Item in Queue
  Syntax : Queue.Enqueue(Object)
  Object : The item to add in Queue
days.Enqueue("Sunday");

Dequeue : Remove the oldest item from Queue (we don't get the item later)
  Syntax : Object Queue.Dequeue()
  Returns : Remove the oldest item and return.
days.Dequeue();

Peek : Get the reference of the oldest item (it is not removed permanently)
  Syntax : Object Queue.Peek()
  returns : Get the reference of the oldest item in the Queue
days.peek();

The following CSharp Source code shows some of commonly used functions :
using System;
using System.Collections;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            Queue days = new Queue();
            days.Enqueue("Sunday");
            days.Enqueue("Monday");
            days.Enqueue("Tuesday");
            days.Enqueue("Wednsday");
            days.Enqueue("Thursday");
            days.Enqueue("Friday");
            days.Enqueue("Saturday");

            MessageBox.Show (days.Dequeue().ToString ());
            
            if (days.Contains("Monday"))
            {
                MessageBox.Show("The queue contains Monday");
            }
            else
            {
                MessageBox.Show("Does not match any entries");
            }
        }
    }
}

When you execute the above C# source code , you will get Sunday in the messagebox and then it check the Monday is exist in the queue or not. 

C# Collection Tutorial-Part-4

NameValueCollection is used to store a collection of associated String keys and String values that can be accessed either with the key or with the index. It is very similar to C# HashTable, HashTable also stores data in Key , value format .
NameValueCollection can hold multiple string values under a single key. As elements are added to a NameValueCollection, the capacity is automatically increased as required through reallocation. The one important thing is that you have to importSystem.Collections.Specialized Class in your program for using NameValueCollection.
Adding new pairs
  NameValueCollection.Add(name,value)
  NameValueCollection pair = new NameValueCollection();
pair.Add("High", "80");

Get the value of corresponding Key
  string[] NameValueCollection.GetValues(index);
  NameValueCollection pair = new NameValueCollection();
  pair.Add("High", "80");
string[] vals = pair.GetValues(1);

using System;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Specialized;

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

        private void button1_Click(object sender, EventArgs e)
        {
            NameValueCollection markStatus = new NameValueCollection();
            string[] values = null;

            markStatus.Add("Very High", "80");
            markStatus.Add("High", "60");
            markStatus.Add("medium", "50");
            markStatus.Add("Pass", "40");

            foreach (string key in markStatus.Keys)
            {
                values = markStatus.GetValues(key);
                foreach (string value in values)
                {
                    MessageBox.Show (key + " - " + value);
                }
            } 
        }
    }
}

C# Collection Tutorial-Part-3

Stack 
The Stack class represents a last-in-first-out (LIFO) Stack of Objects. Stack follows the push-pop operations. That is we can Push (insert) Items into Stack and Pop (retrieve) it back . Stack is implemented as a circular buffer. It follows the Last In First Out (LIFO) system. That is we can push the items into a stack and get it in reverse order. Stack returns the last item first. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.
Commonly used methods :
  Push : Add (Push) an item in the Stack data structure
  Pop : Pop return the last Item from the Stack
Contains: Check the object contains in the Stack

Push : Add (Push) an item in the Stack data structure
  Syntax : Stack.Push(Object)
  Object : The item to be inserted.
  Stack days = new Stack();
days.Push("Sunday");

Pop : Pop return the item last Item from the Stack
  Syntax : Object Stack.Pop()
  Object : Return the last object in the Stack
days.Pop();

Contains : Check the object contains in the Stack
  Syntax : Stack.Contains(Object)
  Object : The specified Object to be search
days.Contains("Tuesday");

The following CSharp Source code shows some of important functions in Stack Class:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            Stack days = new Stack();
            days.Push("SunDay");
            days.Push("MonDay");
            days.Push("TueDay");
            days.Push("WedDay");
            days.Push("ThuDay");
            days.Push("FriDay");
            days.Push("SaturDay");
            if (days.Count ==7)
            {
                MessageBox.Show(days.Pop().ToString ());
            }
            else
            {
                MessageBox.Show("SaturDay does not exist");
            }
        }
    }
}

When you execute this C# program add seven items in the stack . Then it check the count is equal to 7 , if it is seven then pop() the item. The message box will display SaturDay. 

C# Collection Tutorial-Part-2

HashTable
Hashtable in C# represents a collection of key/value pairs which maps keys to value. Any non-null object can be used as a key but a value can. We can retrieve items from hashTable to provide the key. Both keys and values are Objects.
The commonly used functions in Hashtable are :
  Add  : To add a pair of value in HashTable
  ContainsKey : Check if a specified key exist or not
  ContainsValue : Check the specified Value exist in HashTable
Remove : Remove the specified Key and corresponding Value

Add : To add a pair of value in HashTable
  Syntax : HashTable.Add(Key,Value)
  Key : The Key value
  Value : The value of corresponding key
  Hashtable ht;
ht.Add("1", "Sunday");

ContainsKey : Check if a specified key exist or not
  Synatx : bool HashTable.ContainsKey(key)
  Key  : The Key value for search in HahTable
  Returns : return true if item exist else false
ht.Contains("1");

ContainsValue : Check the specified Value exist in HashTable
  Synatx : bool HashTable.ContainsValue(Value)
  Value : Search the specified Value in HashTable
  Returns : return true if item exist else false
ht.ContainsValue("Sunday")

Remove : Remove the specified Key and corresponding Value
  Syntax : HashTable.Remove(Key)
  Key : The key of the element to remove
ht.Remove("1");

The following source code shows some important operations in a HashTable
using System;
using System.Collections;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            Hashtable weeks = new Hashtable();
            weeks.Add("1", "SunDay");
            weeks.Add("2", "MonDay");
            weeks.Add("3", "TueDay");
            weeks.Add("4", "WedDay");
            weeks.Add("5", "ThuDay");
            weeks.Add("6", "FriDay");
            weeks.Add("7", "SatDay");
            //Display a single Item 

            MessageBox.Show(weeks["5"].ToString ());
            //Search an Item 
            if (weeks.ContainsValue("TueDay"))
            {
                MessageBox.Show("Find");
            }
            else
            {
                MessageBox.Show("Not find");
            }
            //remove an Item 
            weeks.Remove("3");
            //Display all key value pairs
            foreach (DictionaryEntry day in weeks )
            {
                MessageBox.Show (day.Key + "   -   " + day.Value );
            }
        }
    }
}

When you execute this C# program it will add seven entries in the hashtable. The first message it will display the item 5. Then it check the value "TueDay" is existing or not . Next it remove the third item from HashTable. Finaly it displays all items exist in the HashTable. 

C# Collection Tutorial-Part-1

CSharp Collections are data structures that holds data in different ways for flexible operations . C# Collection classes are defined as part of the System.Collections or System.Collections.Generic namespace.
Most collection classes implement the same interfaces, and these interfaces may be inherited to create new collection classes that fit more specialized data storage needs. The following tutorial shows how to implement collection classes in C# programming.

ArrayList is one of the most flexible data structure from CSharp Collections. ArrayList contains a simple list of values. ArrayList implements the IList interface using an array and very easily we can add , insert , delete , view etc. It is very flexible because we can add without any size information , that is it will grow dynamically and also shrink .
c-sharp-arraylist
  Add : Add an Item in an ArrayList
  Insert : Insert an Item in a specified position in an ArrayList
  Remove : Remove an Item from ArrayList
  RemoveAt: remove an item from a specified position
Sort : Sort Items in an ArrayList

How to add an Item in an ArrayList ?
  Syntax : ArrayList.add(object)
  object : The Item to be add the ArrayList
  ArrayList arr;
arr.Add("Item1");

How to Insert an Item in an ArrayList ?
  Syntax : ArrayList.insert(index,object)
  index : The position of the item in an ArrayList
  object : The Item to be add the ArrayList
  ArrayList arr;
arr.Insert(3, "Item3");

How to remove an item from arrayList ?
  Syntax : ArrayList.Remove(object)
  object : The Item to be add the ArrayList
arr.Remove("item2")

How to remove an item in a specified position from an ArrayList ?
  Syntax : ArrayList.RemoveAt(index)
  index : the position of an item to remove from an ArrayList
ItemList.RemoveAt(2)

How to sort ArrayList ?
  Syntax : ArrayList.Sort()

The following CSharp source code shows some function in ArrayList

using System;
using System.Collections;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            int i = 0;
            ArrayList ItemList = new ArrayList();
            ItemList.Add("Item4");
            ItemList.Add("Item5");
            ItemList.Add("Item2");
            ItemList.Add("Item1");
            ItemList.Add("Item3");
            MessageBox.Show ("Shows Added Items");
            for (i = 0; i < = ItemList.Count - 1; i++)
            {
                MessageBox.Show(ItemList[i].ToString());
            }
            //insert an item 
            ItemList.Insert(3, "Item6");
            //sort itemms in an arraylist 
            ItemList.Sort();
            //remove an item 
            ItemList.Remove("Item1");
            //remove item from a specified index 
            ItemList.RemoveAt(3);
            MessageBox.Show("Shows final Items the ArrayList");
            for (i = 0; i < = ItemList.Count - 1; i++)
            {
                MessageBox.Show(ItemList[i].ToString());
            }
        }
    }
}
When you execute this C# program , at first add five items in the arraylist and displays. Then again one more item inserted in the third position , and then sort all items. Next it remove the item1 and also remove the item in the third position . Finally it shows the existing items. 

Difference between int, Int16, Int32 and Int64

 In the learning phase developer are not much aware of the difference between primitive, FCL (framework class library), reference, and value types. This cause bugs and performance issues into the code. In this article, I would like to expose the different behavior of integer type.

int

  1. It is a primitive data type defined in C#.
  2. It is mapped to Int32 of FCL type.
  3. It is a value type and represent System.Int32 struct.
  4. It is signed and takes 32 bits.
  5. It has minimum -2147483648 and maximum +2147483647 capacity.

Int16

  1. It is a FCL type.
  2. In C#, short is mapped to Int16.
  3. It is a value type and represent System.Int16 struct.
  4. It is signed and takes 16 bits.
  5. It has minimum -32768 and maximum +32767 capacity.

Int32

  1. It is a FCL type.
  2. In C#, int is mapped to Int32.
  3. It is a value type and represent System.Int32 struct.
  4. It is signed and takes 32 bits.
  5. It has minimum -2147483648 and maximum +2147483647 capacity.

Int64

  1. It is a FCL type.
  2. In C#, long is mapped to Int64.
  3. It is a value type and represent System.Int64 struct.
  4. It is signed and takes 64 bits.
  5. It has minimum –9,223,372,036,854,775,808 and maximum 9,223,372,036,854,775,807 capacity.

Note

  1. A number of developers think that int represents a 32-bit integer when the application is running on a 32-bit OS and it represents a 64-bit integer when the application is running on a 64-bit OS. This is absolutely wrong.
  2. In C# int is a primitive data type and it always mapped to System.Int32 whether the OS is 32-bit or 64-bit.
What do you think?
I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.