Pages

Tuesday, April 17, 2012

Explaining GetHashCode method.

Every object you ever created or used in .NET has GetHashCode method along with Equals, GetType, and ToString methods.  This method is an instance method of an Object class from which any other class derives.
GetHashCodeIntelisense
GetHashCode() method returns an integer that identifies an object instance.  I also can repeat MSDN documentation but you can read it on your own.
You would want to override this method along with Equals() method in your class if the object of your class is going to be used as a key in Hashtable.
The best way to explain it is to show an example. In I was using class Point as an example.  I’m going to continue with this class.  So let assume that we have class like this:
   1: public class Point
   2: {
   3:   private readonly int _x;
   4:   private readonly int _y;
   5:
   6:   public Point(int x, int y)
   7:   {
   8:     _x = x;
   9:     _y = y;
  10:   }
  11: }
Next we want to use Point as a key in a Hashtable.  Remember that the key of the Hasthable must be unique.  In the code bellow we have two identical keys (line 2 & 4). We should expect ArgumentException.
   1: Hashtable hashtable = new Hashtable();
   2: hashtable.Add(new Point(2, 3), "Point 1");
   3: hashtable.Add(new Point(5, 3), "Point 2");
   4: hashtable.Add(new Point(2, 3), "Point 3");
However, no exception was thrown.  There are two reasons why exception is not thrown:
  1. Equals() method that is also an instance method of Object class will always indicate that Point in line 2 and line 4 are different. This expected because two objects have different references.
  2. GetHashCode() method returns different number for these objects.
Try to execute code bellow:
   1: static void Main(string[] args)
   2:  {
   3:    var point1 = new Point(2, 3);
   4:    var point2 = new Point(2, 3);
   5:    Console.WriteLine("point1 Hash: {0}"
   6:         , point1.GetHashCode());
   7:    Console.WriteLine("point2 Hash: {0}"
   8:         , point2.GetHashCode());
   9:    Console.WriteLine("point1 equal to point2: {0}"
  10:         , point1.Equals(point2));
  11:  }
You will get output similar to this one:
point1 Hash: 58225482
point2 Hash: 54267293
point1 equal to point2: False

You can see that we got different hash codes.
To solve this problem we override Equal() and GetHashCode() in our Point class.
First we override Equals() method:
   1: public override bool Equals(object obj)
   2: {
   3:   if (ReferenceEquals(null, obj)) return false;
   4:   if (ReferenceEquals(this, obj)) return true;
   5:   return ((Point)obj)._x == _x && ((Point)obj)._y == _y;
   6: }
You can see that I use ReferenceEquals() method that is static method of Object class.  It checks if the specified objects are the same.
Next we override GetHashCode() method:
   1: public override int GetHashCode()
   2: {
   3:   unchecked
   4:   {
   5:     return (_x * 397) ^ _y;
   6:   }
   7: }
The whole Point would look like this:
   1: public class Point
   2: {
   3:   private readonly int _x;
   4:   private readonly int _y;
   5:
   6:   public Point(int x, int y)
   7:   {
   8:     _x = x;
   9:     _y = y;
  10:   }
  11:
  12:   public override bool Equals(object obj)
  13:   {
  14:     if (ReferenceEquals(null, obj)) return false;
  15:     if (ReferenceEquals(this, obj)) return true;
  16:     return ((Point)obj)._x == _x && ((Point)obj)._y == _y;
  17:   }
  18:
  19:   public override int GetHashCode()
  20:   {
  21:     unchecked
  22:     {
  23:       return (_x * 397) ^ _y;
  24:     }
  25:   }
  26: }
Now if you try to execute the application the output should look exactly like this:
point1 Hash: 793
point2 Hash: 793
point1 equal to point2: True

Also if we try to add new Point(2, 3) twice, we get an ArgumentException as expected.

Working with UDL (Universal Data Link) files


Hello everyĐľne.

After 3 long weeks of vacation, I'm finally back!

I this blog post, I will show one simple method for creating connction strings using UDL files, as well as, how to use the UDL file directly from code-behind using C# language (for those working in VB.NET).

Many juniors who have problems creating connection strings manually, use the Microsoft Visual Studio.NET Data Components like SqlDataSource, AccessDataSource or similar so that the Wizard will do the job for them and place the connection string in Web.config.

Sometimes (especially if running on slower machine), the wizards may respond very slow or some developers does not want to use the VS.NET Wizards for connection strings, at all, because besides the connection string, the DataSource wizards usually perform some other actions too.

Hence, using UDL may be useful in such cases.

Let's pass throughout the procedure.

1. On your Desktop, create file with UDL extension i.e. test.UDL
- the file icon will look like this: (in WinXP) or (Win7)
2. Open the file icon and a wizard will appear.
3. Create your connection string. First (in the first tab) chose appropriate Provider. Then (in the second tab) construct the Connection by filling the required information (servername, database or similar).
4. Test Connection. If the connection is successful, click OK.
Once you are done, open the UDL file with NOTEPAD. Right click on it and go to Edit with Notepad or Open With notepad.
In notepad, you will have the connection string i.e.
[oledb]
; Everything after this line is an OLE DB initstring
Provider=SQLNCLI10.1;Integrated Security=SSPI;Persist Security Info=False;User ID="";Initial Catalog=MySampleDB;Data Source=.;Initial File Name="";Server SPN=""
So, the wizard has constructed connection string for me. This is for SQL Server. Only the bolded part should be copied and you can use it as connection string in your application.
Moreover, if you've already created an UDL file, you can use it in your application directly by calling the filename.
Here is an example:
Firstly, add the using System.Data; and using System.Data.OleDb; directives.
The test code is as follows:
01OleDbConnection con = new OleDbConnection("File Name="+Server.MapPath("\\test.udl"));
02
03try
04{
05    con.Open();
06    Response.Write("Connection open!");
07}
08catch (OleDbException ex)
09{
10    Response.Write(ex.Message);
11}
12finally
13{
14    con.Close();
15}

If you can notice, the connection string is only the path to the filename (which in our case is in the web application root folder) preceding with File Name=.
If you run this example, the message Connection Open! should be displayed. Moreover, you can add wrap this Response.Write("Connection open!") inside if (con.State == ConnectionState.Open) { Response.Write("Connection open"); }
I hope this was useful :)

Message Queuing using C#


Message Queuing is a message infrastructure and a development platform for creating distributed messaging applications for the Microsoft Windows Operating System. Message Queuing applications can use the Message Queuing infrastructure to communicate heterogeneous networks and with computers that may be offline. Message Queuing provides guaranteed message delivery, efficient routing, security, transaction support and priority based messaging. Administrative Privileges are required to create a queue.
 
With the release of MS Windows 2000, the name of Microsoft's message queuing solution changed from Microsoft Messaging Queue Server to Message Queuing. In the Windows Platform SDK, the term Messaging Queuing refers to all versions of the product. There are three different types of Message Queuing versions:
  • MSMQ 1.0: Microsoft Message Queue Server 1.0 product operates with MS Windows NT 4.0, Microsoft MS Windows 95, MS Windows 98, and MS Windows Me.
  • MSMQ 2.0: the Message Queuing service included in MS Windows 2000.
  • MSMQ 3.0: Message queuing service included in MS Windows XP Professional and Windows Server 2003 family. 
When to use Message Queue?
Message Queuing is useful when the client application is often disconnected from the network. For example, salespersons can enter order data directory at the customer's site. The application sends a message for each order to the message queue that is located on the client's system.
 
Message Queuing can also be useful in a connected environment. For example, the server of a website is fully loaded with order transactions at some specific time periods, say evening times or morning times, but the load is low at night time. The solution to this problem would be to buy a faster server or add an additional server to the system. However, the cheaper solution would be sending message queue.
 
There are different types of Message Queues: 
  1. Normal Message
  2. Acknowledgement Message
  3. Respond Message
  4. Report Message 
A message can have a priority that defines the order in which the message will be read from a queue. Commonly, messages are stored on the disk can be found in the \system32\msmq\stored directory.
 
Message Queuing Features
 
Message Queuing is a part of the Windows Operating System. Main features of this service are:
  • Messages can be sent in a disconnected environment. It is not necessary for the sending and receiving application to run at the same time.
  • A program can assign different priorities to messages when it puts the message in the queue.
  • Using Express mode, messages can be sent very fast. Express mode messages are just stored in memory.
  • Message Queues can be secured with access control lists to define which users can send or receive messages from a queue. We can also encrypt the data to avoid network sniffers from reading the data.
  • We can send the messages using guaranteed delivery. Recoverable messages are stored within files. They are delivered even in case the server reboots.
  • Message Queuing 3.0 supports sending multicast messages.

Message Queuing Products
Message Queuing 3.0 is a part of Windows Server 2003 and Windows XP, Windows 2000 comes with the Message Queuing 2.0, which did not have support for the HTTP protocol and multicast messages. You can install a message queue in Windows XP using Add or Remove Programs, a separate section within windows components where Message Queuing options can be selected. Within the message Queuing options, various components can be selected (refer Fig 1 and Fig 2).
Active Directory Integration:

Within this feature, message queue names are written to the Active Directory integration and to secure queues with Windows users and groups

Common:

The common subcomponent is required for base functionality with Message Queuing  

MSMQHTTP Support:

This support allows you to send and receive messages using the HTTP protocol.

Image1.jpg
Figure 1

Image2.jpg
Figure 2
Triggers:

With Triggers applications can be instantiated on the arrival of a new   message.
 
When Message Queuing is installed, the Message Queuing Service must be started. This service reads and writes messages and communicates with other Message Queuing servers to route messages across the network.
 
Now we will see how to send and receiving messages using C# programming.
Programming Message Queuing
Creating a Message Queue
In C#, we can also create Message Queues programmatically using the Create() method of MessageQueue class. With Create() method, the path of the new queue must be passed. The path consists of the hostname where the queue is located and the name of the queue. Now we will write an example, which will create on the localhost that is 'MynewPublicQueue'. To create a private queue, the path name must include private$. For example: \private$\MynewPrivateQueue.
 Once the create() method is invoked, properties of the queue can be changed. Using label property, the label of the queue is set to "First Queue". The following program writes the path of the queue and the format name to the console. The format name is automatically created with a UUID (Universal Unique Identifiers) that can be used to access the queue without the name of the server. Check out Code 1.

Code 1:
using System;
using System.Collections.Generic;
using System.Messaging;
using System.Text;
 
namespace FirstQueue
{
    class Program
    {
        static void Main(string[] args)
        {
            using (MessageQueue queue = MessageQueue.Create(@". \myqueue"))
            {
                queue.Label = "First Queue";
                Console.WriteLine("Queue Created:");
                Console.WriteLine("Path: {0}, queue.Path");
                Console.Writeline("FormatName: {0}, queue.FormatName");
            }
        }
    }
}
 
Finding a Queue
To identify the queue, you can use the path name and format name. You can also differentiate between public and private queues. Public queues are published in the Active directory. For these queues, it is not necessary to know the system where they are located.
Private queues can be found only in the name of the system where the queues located are known. You can find the public queues in the Active directory by searching for the queue's table, category or format name. You can also get all the queues on the machine.
The class MessageQueue has static methods to search for queues:
  • GetPublicQueuesByLable()
  • GetPublicQueuesByCategory()
  • GetPublicQueuesByMachine()
The method GetPublicQueues() return an array of all public queues in the domain.

Code 2:
using System;
using System.Messaging;
 
namespace FirstQueue
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (MessageQueue queue in MessageQueue.GetPublicQueues())
            {
                Console.WriteLine("queue.Path");
            }
        }
    }
}
 
You can also make queues private using the static method called GetPrivateQueuesByMachine(). This method returns all private queues from a specific system.
 
Opening Known Queues
If you the name of the queue, then it is not necessary to search for it. Queues can be opened using the path or format name.
 
Pathname
Pathname specifies the machine name and queue name to open the queue. The following code 3 opens the queue FirstQueue on local host. To make sure the queue exists, you use the static method MessageQueue.Exists().

Code 3:
using System;
using System.Messaging;
 
namespace FirstQueue
{
    class Program
    {
        static void Main(string[] args)
        {
            if (MessageQueue.Exists(@".\\FirstQueue"))
            {
                MessageQueue queue = new MessageQueue(@".\\FirstQueue");
            }
            else
            {
                Console.WriteLine("Queue .\\FirstQueue not Found");
            }
        }
    }
}
 
We can use different type identifiers when the queues are opened. Table 1 shows the syntax of the queue name for specific types.
 
Format Name
Format name can be given to open queue. The formatname is used for searching the queue in the Active Directory to get the host where the queue is located. In a disconnected environment, where the queue cannot be reached at the time the message is sent, it is necessary to use the format name.
Syntax of the format name queue is:
 
MessageQueue queue= new MessageQueue( @ "FormatName : Public=023423DFG-0984-3w45-K987-12638NU979HH")
 
Table 1
Queue Type
Syntax
Private queue
MachineName\Private$\QueueName
Public  queue
MachineName\QueueName
Journal queue
MachineName\QueueName\Journal$
Machine Journal queue
MachineName\Journal$
Machine dead letter queue
MachineName\DeadLetter$
Machine transactional
dead-letter queue
MachineName\XactDeadLetter$
 
Sending a Message
By using the Send method of the MessageQueue class, you can send the message to the queue. The object passed as an argument of the Send() Method is serialized queue. The Send() method is overloaded so that a Label and a MessageQueueTransaction object  can be passed. Now we will write a small example to check if the queue exists and if it doesn't exist, a queue is created. Then the queue is opened and the message "First Message" is sent to the queue using the Send() method.

The path name specifies "."  for the server name, which is the local system. Path name to private queues only works locally. Add the following code 4 in your Visual Studio C# console environment.

Code 4:
 
using System;
using System.Messaging;
 
namespace FirstQueue
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                if (!MessageQueue.Exists(@".\Private$\FirstQueue"))
                {
                    MessageQueue.Create(@".\Private$\FirstQueue");
                }
                MessageQueue queue = new MessageQueue(@".\Private$FirstQueue");
                queue.Send("First Message ", " Label ");
            }
 
            catch (MessageQueueException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
 
Build the application and view and run. You can view the message in the Component Management admin tool as shown in figure 3. By opening the message and selecting the body tab of the dialog, you can see the message was formatted using XML.
 
Receiving Messages
 
MessageQueue class can be used for reading messages. With the Receive() method, a single message is read and removed from the queue. We will write a small example to read the Private queue FirstQueue.
When you read a message using the XmlMessageFormatter, we have to pass the types of the objects that are read to the constructor or the formatter. In this example (Code 5), the type System.String is passed to the argument array if the XmlMessageFormatter constructor. The following program is read with the Receive() method and then the message body is written to the console.
Image3.jpg
Figure 3
Code 5:
using System;
using System.Messaging;
 
namespace FirstQueue
{
    class Program
    {
        static void Main(string[] args)
        {
            MessageQueue queue = new MessageQueue (@".\Private$\FirstQueue");
            Queue.Formatter = new XmlMessageFormatter( new string[]("System.String"));
            Message Mymessage = queue.Receive();
            Console.WriteLine(Mymessage.Body);                    
        }
    }
}
 
Receive() message behaves synchronously and waits until a message is in the queue if there is none. Try out the rest in Visual Studio 2005.
 
Conclusion
Message Queues can be created with MessageQueue.Create() method. But to create a Message queue you should have administrative rights.