25.3.08

Calling SP in C#.NET

SqlConnection Con= new SqlConnection(Connection);
Con.Open();
SqlParam[] SqlPar = new SqlParam[1];
SqlPar[0] = new SqlParam("@name", SqlDbType.BigInt);
SqlPar[0].Value = name;
string SqlQuery = "SP-Name";
SqlCommand SqlCmd = new SqlCommand(SqlQuery, Con);
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCmd.CommandTimeout = 0;
SqlCmd.Parameters.Add(SqlPar[0]);
SqlDataReader DBReader = SqlCmd.ExecuteReader();
ItemTypeCode = "";
ParentItemID = -1;
if (DBReader.Read())
{
ItemTypeCode = DBReader.GetString(4).Trim();
ParentItemID = DBReader.GetInt64(5);
}
DBReader.Close();
Con.Close();

Begin Transaction & Mark in SQL

BEGIN { TRAN TRANSACTION }
[ { transaction_name @tran_name_variable }
[ WITH MARK [ 'description' ] ]
]
[ ; ]
Arguments :
transaction_name
Is the name assigned to the transaction. transaction_name must conform to the rules for identifiers, but identifiers longer than 32 characters are not allowed. Use transaction names only on the outermost pair of nested BEGIN...COMMIT or BEGIN...ROLLBACK statements.
@tran_name_variable
Is the name of a user-defined variable containing a valid transaction name. The variable must be declared with a char, varchar, nchar, or nvarchar data type. If more than 32 characters are passed to the variable, only the first 32 characters will be used; the remaining characters will be truncated.
WITH MARK [ 'description' ]
Specifies that the transaction is marked in the log. description is a string that describes the mark. If description is a Unicode string, values longer than 255 characters are truncated to 255 characters before being stored in the msdb.dbo.logmarkhistory table. If description is a non-Unicode string, values longer than 510 characters are truncated to 510 characters.
If WITH MARK is used, a transaction name must be specified. WITH MARK allows for restoring a transaction log to a named mark.
Remarks
BEGIN TRANSACTION represents a point at which the data referenced by a connection is logically and physically consistent. If errors are encountered, all data modifications made after the BEGIN TRANSACTION can be rolled back to return the data to this known state of consistency. Each transaction lasts until either it completes without errors and COMMIT TRANSACTION is issued to make the modifications a permanent part of the database, or errors are encountered and all modifications are erased with a ROLLBACK TRANSACTION statement.
BEGIN TRANSACTION starts a local transaction for the connection issuing the statement. Depending on the current transaction isolation level settings, many resources acquired to support the Transact-SQL statements issued by the connection are locked by the transaction until it is completed with either a COMMIT TRANSACTION or ROLLBACK TRANSACTION statement. Transactions left outstanding for long periods of time can prevent other users from accessing these locked resources, and also can prevent log truncation.
Although BEGIN TRANSACTION starts a local transaction, it is not recorded in the transaction log until the application subsequently performs an action that must be recorded in the log, such as executing an INSERT, UPDATE, or DELETE statement. An application can perform actions such as acquiring locks to protect the transaction isolation level of SELECT statements, but nothing is recorded in the log until the application performs a modification action.
Naming multiple transactions in a series of nested transactions with a transaction name has little effect on the transaction. Only the first (outermost) transaction name is registered with the system. A rollback to any other name (other than a valid savepoint name) generates an error. None of the statements executed before the rollback is, in fact, rolled back at the time this error occurs. The statements are rolled back only when the outer transaction is rolled back.
The local transaction started by the BEGIN TRANSACTION statement is escalated to a distributed transaction if the following actions are performed before the statement is committed or rolled back:
An INSERT, DELETE, or UPDATE statement that references a remote table on a linked server is executed. The INSERT, UPDATE, or DELETE statement fails if the OLE DB provider used to access the linked server does not support the ITransactionJoin interface.
A call is made to a remote stored procedure when the REMOTE_PROC_TRANSACTIONS option is set to ON.
The local copy of SQL Server becomes the transaction controller and uses Microsoft Distributed Transaction Coordinator (MS DTC) to manage the distributed transaction.
A transaction can be explicitly executed as a distributed transaction by using BEGIN DISTRIBUTED TRANSACTION
Marked Transactions
The WITH MARK option causes the transaction name to be placed in the transaction log. When restoring a database to an earlier state, the marked transaction can be used in place of a date and time.
Additionally, transaction log marks are necessary if you need to recover a set of related databases to a logically consistent state. Marks can be placed in the transaction logs of the related databases by a distributed transaction. Recovering the set of related databases to these marks results in a set of databases that are transactionally consistent. Placement of marks in related databases requires special procedures.
The mark is placed in the transaction log only if the database is updated by the marked transaction. Transactions that do not modify data are not marked.
BEGIN TRAN new_name WITH MARK can be nested within an already existing transaction that is not marked. Upon doing so, new_name becomes the mark name for the transaction, despite the name that the transaction may already have been given. In the following example, M2 is the name of the mark.
A. Naming a transaction eg:
DECLARE @TranName VARCHAR(20);
SELECT @TranName = 'MyTransaction';
BEGIN TRANSACTION @TranName;
USE AdventureWorks;
DELETE FROM AdventureWorks.HumanResources.JobCandidate
WHERE JobCandidateID = 13;
COMMIT TRANSACTION @TranName;
GO
B. Marking a transaction eg:
BEGIN TRANSACTION CandidateDelete
WITH MARK N'Deleting a Job Candidate';
GO
USE AdventureWorks;
GO
DELETE FROM AdventureWorks.HumanResources.JobCandidate
WHERE JobCandidateID = 13;
GO
COMMIT TRANSACTION CandidateDelete;
GO

17.3.08

Joins in SQL

Joins In Sql Server:
******************
1. Cross join
2. Inner join
3. Outer join
Left Outer join
Right Outer join
Full outer join
4. Self join

Eg:
1. Cross join
************
select * from emp
select * from dept
select empid, location from emp cross join dept

2. Inner join
***********
select empid, ename , a.deptno , location from emp a inner join dept b on
a.deptno = b.deptno

3. Outer join
************
Left Outer Join
select empid, a.deptno ,salary, location from emp a left outer join dept b on
a.deptno = b.deptno
Right Outer Join
select empid, a.deptno ,salary, location from emp a right outer join dept b on
a.deptno = b.deptno
Full Outer Join
select empid, a.deptno ,salary, location from emp a full outer join dept b on
a.deptno = b.deptno

4. Self Join
**********
select a.empid, a.deptno , a.salary from emp a join emp b on
a.empid = b.empid

select a.empid, a.deptno , a.salary , a.mgrid from emp a , emp b where
a.empid = b.mgrid

DDL & DML

DDL
****
Data Definition Language (Create, Alter, Drop, Truncate)
Eg:
create table emp (empid int, empname varchar(20))
drop table emp
truncate tabel emp
alter table emp drop empname
alter table emp add column empname varchar(20)
alter table emp add constraint pk_emp primary key(empname) //pk_emp is primary key

DML
*****
Data Manipulating Language (Select, Update, Delete, Insert)
Eg:
select * from emp
update emp set empid = 10 where empid = 20
delete emp //Delete all the records in the table
delete from emp where empid = 20
insert into emp values(vv,'srsre')

DCL
*****
Data Control Language (Revoke, Commit, Rollback, Grant)

12.3.08

Exception Handiling

try {// Throw your exception}
catch{//Caught Exception}
finally {// Run your clean-up here}

Also, code in a catch block gets called *only* if an exception is thrown. Code in a finally block gets called if an exception is thrown or if an exception is *not* thrown.
URL:- http://www.jaggersoft.com/pubs/ExceptionHandlingInCSharp.htm
The fundamental thing that exceptions allow you to do is to separate the essential functionality from the error handling. In other words, we can rewrite the mess above like this:
...
public sealed class PainLess
{
public static int Main(string[] args)
{
try
{
string filename = args[0];
char[] source = ReadSource(filename);
Process(filename, source);
return 0;
}
catch (SecurityException caught) { ... }
catch (IOException caught) { ... }
catch (OutOfMemoryException caught) { ... }
...
}
private static char[] ReadSource(string filename)
{
FileInfo file = new FileInfo(filename);
int length = (int)file.Length;
char[] source = new char[length];
TextReader reader = file.OpenText();
reader.Read(source, 0, length);
reader.Close();
return source;
}
}
There are several things to notice about this transformation.
The numeric integer error codes that utterly failed to describe the errors they represented (e.g. what does 2342 mean?) are now descriptively named exception classes (e.g. SecurityException).
The exception classes are not tightly coupled to each other. In contrast, each integer code must hold a unique value thus coupling all the error codes together.
There is no throw specification on ReadSource. C# does not have throw specifications.
However, by far and away the most important thing to notice is how much cleaner, simpler and easier to understand ReadSource has become. It now contains only the statements required to implement its essential functionality. It makes no apparent concession to error handling. This is possible because if an exception occurs the call stack will unwind all by itself. This version of ReadSource is the "ideal" we are aiming it. It is as direct as we can make it.
Ironically, exceptions allow us to get close to this ideal version of ReadSource but at the same time prevent us from quite reaching it. ReadSource is an example of code that acquires a resource (a TextReader), uses the resource (Read), and then releases the resource (Close). The problem is that if an exception occurs after acquiring the resource but before releasing it then the release will not take place. The solution has become part of the context. Nevertheless, this "ideal" version of ReadSource is useful; we can compare forthcoming versions of ReadSource to it as a crude estimate of their "idealness".
finally?
The solution to this lost release problem depends on the language you're using. In C++ you can release the resource in the destructor of an object held on the stack (the misnamed Resource Acquisition Is Initialization idiom). In Java you can use a finally block. C# allows you to create user-defined struct types that live on the stack but does not allow struct destructors. (This is because a C# destructor is really a Finalize method in disguise and Finalize is called by the garbage collector. Structs, being value types, are never subject to garbage collection.) Therefore, initially at least, C# must follow the Java route and use a finally block. A first cut implementation using a finally block might look like this: private static char[] ReadSource(string filename)
{
try
{
FileInfo file = new FileInfo(filename);
int length = (int)file.Length;
char[] source = new char[length];
TextReader reader = file.OpenText();
reader.Read(source, 0, length);
}
finally
{
reader.Close();
}
return source;
}
This version has had to introduce a try block (since a finally block must follow a try block) which isn't in the ideal solution but apart from that it's the same as the "ideal" version of ReadSource. It would be a reasonable solution if it worked. But it doesn't. The problem is that the try block forms a scope so reader is not in scope inside the finally block and source is not in scope at the return statement.
finally?
To solve this problem you have to move the declarations of reader and source outside the try block. A second attempt might be: private static char[] ReadSource(string filename)
{
TextReader reader;
char[] source;
try
{
FileInfo file = new FileInfo(filename);
int length = (int)file.Length;
source = new char[length];
reader = file.OpenText();
reader.Read(source, 0, length);
}
finally
{
reader.Close();
}
return source;
}
This version has moved the declaration of reader and source out of the try block and consequently assigns to reader and source rather than initializing them. That's another difference (and two extra lines) from the "ideal" version of ReadSource. Nevertheless, you might consider it a reasonable solution if it worked. But it doesn't. The problem is that assignment is not the same as initialization and the compiler knows it. If an exception is thrown before reader is assigned then the call to reader.Close() in the finally block will be on reader which won't be assigned. C#, like Java, doesn't allow that.
finally?
Clearly you have to initialize reader. A third attempt therefore might be: private static char[] ReadSource(string filename)
{
TextReader reader = null;
char[] source;
try
{
FileInfo file = new FileInfo(filename);
int length = (int)file.Length;
source = new char[length];
reader = file.OpenText();
reader.Read(source, 0, length);
}
finally
{
reader.Close();
}
return source;
}
This version introduces null which isn't in the "ideal" version of ReadSource. Nevertheless, you might still consider it a reasonable solution if it worked. But it doesn't (although it does compile). The problem is the call to reader.Close() could easily throw a NullReferenceException.
finally?
One way to solve this problem is to guard the call to reader.Close(). A fourth attempt therefore might be: private static char[] ReadSource(string filename)
{
TextReader reader = null;
char[] source;
try
{
FileInfo file = new FileInfo(filename);
int length = (int)file.Length;
source = new char[length];
reader = file.OpenText();
reader.Read(source, 0, length);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
return source;
}
Of course, the guard on reader.Close() isn't in the "ideal" version of ReadSource. But this is a reasonable version if only because it does, finally, work. It's quite different from the "ideal" version but with a bit of effort you can refactor it to this: private static char[] ReadSource(string filename)
{
FileInfo file = new FileInfo(filename);
int length = (int)file.Length;
char[] source = new char[length];
TextReader reader = file.OpenText();
try
{
reader.Read(source, 0, length);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
return source;
}
In some cases you might be able to drop the null guard inside the finally block (you can in the above case) but in general this is the best you can do with a finally block solution. (Consider if file.OpenText returned null, or if reader was assigned to inside the try block, or reader was passed as a ref/out argument inside the try block.) You have to add a try block, a finally block, and an if guard. And if you are using Java you have to do those three things every time. And therein is the biggest problem. If this solution was truly horrible and completely and utterly different to the ideal solution it wouldn't matter a jot if we could abstract it all away. But in Java you can't. The Java road stops here, but the C# road continues.
using Statements
In C#, the nearest you can get to the "ideal" version is this: private static char[] ReadSource(string filename)
{
FileInfo file = new FileInfo(filename);
int length = (int)file.Length;
char[] source = new char[length];
using (TextReader reader = file.OpenText())
{
reader.Read(source, 0, length);
}
return source;
}
This is pretty close. And as I'll explain shortly it has a number of features that improve on the "ideal" version. But first let's look under the lid to see how it actually works.
using Statement Translation
The C# ECMA specification states that a using statement: using (type variable = initialization)
embeddedStatement
is exactly equivalent to: {
type variable = initialization;
try
{
embeddedStatement
}
finally
{
if (variable != null)
{
((IDisposable)variable).Dispose();
}
}
}
This relies on the IDisposable interface from the System namespace: namespace System
{
public interface IDisposable
{
void Dispose();
}
}
Note that the cast inside the finally block implies that variable must be of a type that supports the IDisposable interface (either via inheritance or conversion operator). If it doesn't you'll get a compile time error.
using TextReader Translation
Not surprisingly, TextReader supports the Disposable interface and implements Dispose to call Close. This means that this: using (TextReader reader = file.OpenText())
{
reader.Read(source, 0, length);
}
is translated, under the hood, into this: {
TextReader reader = file.OpenText();
try
{
reader.Read(source, 0, length);
}
finally
{
if (reader != null)
{
((IDisposable)reader).Dispose();
}
}
}
Apart from the cast to IDisposable this is identical to the best general Java solution. The cast is required because this is a general solution.
Do It Yourself?
It's instructive to consider what would happen if TextReader didn't implement the IDisposable interface. The lessons from this will show us how to implement Disposability in our own classes. One solution is the Object Adapter pattern. For example: public sealed class AutoTextReader : IDisposable
{
public AutoTextReader(TextReader target)
{
// PreCondition(target != null);
adaptee = target;
}
public TextReader TextReader
{
get { return adaptee; }
}
public void Dispose()
{
adaptee.Close();
}
private readonly TextReader adaptee;
}
which you would use like this: using (AutoTextReader scoped = new AutoTextReader(file.OpenText()))
{
scoped.TextReader.Read(source, 0, length);
}
To make things a little easier you can create an implicit conversion operator: public sealed class AutoTextReader : IDisposable
{
...
public static implicit operator AutoTextReader(TextReader target)
{
return new AutoTextReader(target);
}
...
}
which would allow you to write this: using (AutoTextReader scoped = file.OpenText())
{
scoped.TextReader.Read(source, 0, length);
}
struct Alternative
AutoTextReader is a sealed class intended, as its name suggests, to be used as a local variable. It makes sense to implement it as a struct instead of class: public struct AutoTextReader : IDisposable
{
// exactly as before
}
Using a struct instead of a class also gives you a couple of free optimizations. Since a struct is a value type it can never be null. This means the compiler must omit the null guard from generated finally block. Also, since you cannot derive from a struct its runtime type is always the same as its compile time type. This means the compiler can usually omit the cast to IDisposable from the generated finally block and thus avoid a boxing operation. (specifically, it can avoid the cast if Dispose is a public Implicit Interface Implementation rather than a non-public Explicit Interface Implementation). In other words, this: using (AutoTextReader scoped = file.OpenText())
{
scoped.TextReader.Read(source, 0, length);
}
is translated into this: {
AutoTextReader scoped = new file.OpenText();
try
{
scoped.TextReader.Read(source, 0, length);
}
finally
{
scoped.Dispose();
}
}
It should come as no surprise that I prefer the using statement solution to the finally block solution. In fact, the using statement solution scores several extra points in comparison to the "ideal" solution. A using statement:
Works! It always releases the resource.
Is an extensible mechanism. It allows you to create an abstraction of resource release. Creating your own resource releaser types such as AutoTextReader is easy.
Allows you to pair up the resource acquisition with the resource release. The best moment to organize the resource release is the moment you acquire the resource. If you borrow a book from a library you're told when to return it as you borrow it.
Says explicitly, in syntax, that you are using a resource.
Creates a scope for the variable holding the resource. Look carefully at the compiler translation of a using statement and you'll see that it cleverly includes a pair of outer braces: using (AutoTextReader scoped = file.OpenText())
{
scoped.TextReader.Read(source, 0, length);
}
scoped.TextReader.Close(); // scoped is not in scope here
This is reminiscent of C++ declarations in conditions. Both allow you to restrict the scope of a variable so it's only usable when in scope and is only in scope when usable.

6.3.08

Message Queueing

file:///D:/Prathap/Knowledge%20Transfer/- http://www.c-sharpcorner.com/UploadFile/rajkpt/101262007012217AM/1.aspx

Message Queuing using C# 2005:

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:
Normal Message
Acknowledgement Message
Respond Message
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.
Figure 1:
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 QueuingCreating a Message QueueIn 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 QueueTo 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 transactionaldead-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.

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.