Tuesday, July 14, 2009

Differences between Idictionary and Hashtable

Both Idictionary and Hashtable are use to store data in a (Key,Value) format.
Here " Key " is any unique token which is used to identify its corresponding data or value uniquely, "Value" is the data which you want to store it can be any thing string, integer, float etc..
Both(Idictionary and Hashtable) are derived from System.Collections Class. are used for

1) Inserting Data
2) Deleting data
3) Modifying Data
4) Searching for a particluar value

Idictionary:

In Idictionary we need to clearly define what type of value we want to store. let say we want to store both key and value as strings, here is the syntax


IDictionary < string,string > Name;
Name= new Dictionary < string,string >

So in the above we have created Name as Idictionary where Key and value both takes strings.

Hashtable:

In hashtable no need to define any signature i.e you can store any kind of values. Hashtable take every key and value as an object but not as the value you have entered means eventhough we have entered Key and value as strings Hashtable internally treats them as objects but not as strings.

In the same hashtable you can store different values let say we have store Ist entry as (string, int) 2nd entry can be any thing let say (int, float). Since Hashtable treat every key or Value as an object .

Hashtable namelist;
nameList= new Hashtable();

Differences between Hashtable and Idictionary:
  • In Idictionary we need to explicitly define signature i.e what type of Key and value we want to store. Hashtable no need to define any structure or signature.

  • In Idictionary once we have defined signature there is no chance of entering values other than the signature we have specified. where as within the same hashtable we can enter any type of key,value pair.

  • In Hashtable we required Boxing and Unboxing to do any kind of manipulation with values. where as for Idictionary we don't require any kind of boxing and unboxing as we are already defined the signature.

  • Hashtable is useful if you don't know what all kind of values you might be storing in it. Idictionary is used if you know exactly what kind of (key , value) pair you will be using.Let say if you know that both Key and value are always strings then use Idictionary.

  • Hashtable is costly as every operation(inserting, modifying, deleting..) requires either Boxing or UnBoxing but where as Idictionary doesn't require any such things since we know the signature before hand.


Monday, July 13, 2009

How to Run any Application at System start up

The below lines will create a registry entry at following path "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", this is the path from where windows will start all the applications at the system start up.

RegistryKey regKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

//Give the name of exe as first parameter . Here Sample.exe is the name of exe. The second parameter should be path from where it will start executing the exe's. Here
"Application.ExecutablePath" will directly give the path of exe.

regKey .SetValue("Sample", Application.ExecutablePath.ToString());

Thursday, July 9, 2009

How to Read and write to a Xml document in c#

Following things i will be covering in this blog

1) Creating a Xml file.
2) Writing in to a Xml file .

Creating a Xml File :

  • To create a Xml file first we need to know the directory structure or the path where it has to create the Xml file. If the specified directory structure doesn't exist we need to create it.

Note : Make sure that you give only the path but not till the file Name.


Eg: If you want your xml file at


"C:\\Documents and Settings\\All Users\\Desktop\\Sample\\SampleConfig.xml"
give the path till SampleFolder if you give full path(till the file name in this
case Sampleconfig.xml) it will create the Folder by name SampleConfig.xml .

string xmlFilePath="C:\\Documents and Settings\\All Users\\Desktop\\Sample";

if (!Directory.Exists(xmlFilePath))
Directory.CreateDirectory(xmlFilePath);


//Now append the filename to the path
xmlFilePath+= "\\SampleConfig.xml";


So in the above code snippet it will create a folder by name Sample.

Once we know the path we can now create the xml file.


XmlTextWriter txtWriter = new XmlTextWriter(filePath, null);


//This method is used to validates whether we are writing well-formed xml document(its optional)


txtWriter.WriteStartDocument(true);

//To create the xml file with indentation if we don't give this it keeps writing as a single line.Its optional.


txtWriter.Formatting = Formatting.Indented;


txtWriter.WriteStartElement("EmpDetails");
txtWriter.WriteStartElement("EmpID");
txtWriter.WriteEndElement();
txtWriter.WriteStartElement("EmpName");
txtWriter.WriteEndElement();
txtWriter.WriteStartElement("Age");
txtWriter.WriteEndElement();
txtWriter.WriteEndElement();

It writes the following lines

<EmpDetails>

<EmpID />

<EmpName />

<Age />

</EmpDetails>"



Here the important to point to note is that how we are creating parent node and child nodes. Here "EmpDetails" is the root node and EmpID,EmpName and Age are the child nodes. To create Parentnode close its corresponding EndElement(WriteEndElement()) at the end of its Child nodes.

From the above code snippet we can see WriteEndElement() of EmpDetails node is written at the end,after all the child nodes are completed but where as for other nodes we are writing at the very next line. We can create nested nodes too.

  • We can create Xml nodes with default values, by using "WriteElementString" method of XmlTextWriter


txtWriter.WriteElementString("Age", "24");

so here it will create a node with default value of age as 24.
  • We have till now created only the nodes but still they are not written in to the file, to do so we need to make use of "Flush" method.

//This method writes above data in to Xml file

txtWriter.Flush();

Its always good practice to close the XmlTextWriter if its no longer in use.

txtWriter.Close();

Writing in to Xml:
  • To write in to xml, first we need to know the path from where we need to get the xml file.
  • Load the Xml in to XmlDocument.
  • Traverse through each node and check whether its the same node for which we need to give the value.

Step1 :


XmlDocument xmlDoc = new XmlDocument();
filePath+=file://sampleconfig.xml/;

Step2 :


xmlDoc.Load(filePath);

Step3:


XmlNodeList xmlNodeList;

//This gives the list of child nodes


xmlNodeList = xmlDoc.DocumentElement.ChildNodes;

//Traverse through Each node and give the values


foreach (XmlNode childNode in xmlNodeList)
{
if (childNode.NodeType == XmlNodeType.Element)
{
if (childNode.Name == "EmpID")
childNode.InnerText = "12345";
if (childNode.Name == "EmpName")
childNode.InnerText = "OM";
if (childNode.Name == "Age")
childNode.InnerText = "24"; }
}

To save the configuration file use the save method of XmlDocument.


xmlDoc.Save(filePath);

Monday, July 6, 2009

How to Read and write Asynchronously to Socket ?

C# provides built in methods to read and write data asynchronously in to the sockets. All this methods are non-blocking methods so we can still continue processing other steps without waiting for Asynchronous callback to complete since they are executed in a different thread.

Read Data Asynchronously :

socket.BeginReceive is a method defined in System.Net.Sockets to read data from a connected socket.
Syntax:(one of the overloaded methods)

BeginReceive(byte [] buffer, int offset, int size, Socket flags, AsyncCallback, object state)

Here

buffer = array of system byte to store data
offset = position in buffer parameter from which it has to store data
size = number of bytes it can received
Socket flags = bitwise combination of socket flags
AsyncCallback = a delegate which is invoked when we have received something from socket
state = a user defined object which contians information about receive operation. This is also passed to EndReceive method.Generally it will have atleast the socket from which it has to read.

Example :

byte[] buffer = new byte[BufferSize];

public class StateObject
{
public Socket workSocket = null; // Client socket.
public byte[] buffer = new byte[BufferSize];
}
StateObject state=new StateObject();

Sock.BeginReceive(buffer, 0, 1024, 0, new AsyncCallback(ReadCallback), state);

So here buffer is the bytearray to store data starting from offest ,0 and to the maximun of 1024 bytes . ReadCallback is the delegate which is invoked when we received something on socket.

The asynchronous BeginReceive operation must be completed by calling the EndReceive method.

To cancel a pending BeginReceive, call the Close method.




public void ReadCallback(IAsyncResult ar)
{

// Retrieve the state object and the handler socket from the asynchronous state object.
state = (StateObject)ar.AsyncState;

if (state != null)
{
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);

//Convert the bytedata to string
string content = System.Text.ASCIIEncoding.ASCII.GetString(state.buffer, 0, bytesRead);

}

Send data Asynchronously:
A Method called BeginSend is used to start sending data asynchronously on a socket. We can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginSend method.

The callback method make use of EndSend method used to send data.

Syntax:

BeginSend(byte [] buffer, int offset, int size, Socket flags, AsyncCallback, object state) ;

Example :

Let sey we need to send string "HelloWorld".

string str="HelloWorld";
byte[] byteData = Encoding.UTF8.GetBytes(str);

sock.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), sock);

So here SendCallback is used as delegate to send data

private void SendCallback(IAsyncResult ar)
{

// Retrieve the socket from the state object.
sock = (Socket)ar.AsyncState;

// Complete sending the data to the remote device.
int bytesSent = sock.EndSend(ar);
}