Friday, November 9, 2012

Windows Message Queue (MSMQ) with Threading using C#.NET

In last post we learned how to create a simple message queue. In this article we are going to write a C# app to use the message queue in thread, so that one thread can be used to send messages and other to read it.


1) Create a console application in C#

2) Declare class level variable

   static bool StopThread = false;

2) Write function to get message queue instance


private static MessageQueue GetStringMessageQueue()
        {
            MessageQueue msgQueue = null;
            string queueName = @".\private$\MyStringQueue";
            if (!MessageQueue.Exists(queueName))
            {
                msgQueue = MessageQueue.Create(queueName);
            }
            else
            {
                msgQueue = new MessageQueue(queueName);
            }
            return msgQueue;
        }

3)  Create function to send message to queue


  private static void SendStringMessageToQueue()
        {
            while (StopThread == false)
            {
                string msg = Console.ReadLine();
                if (msg == "x")
                {
                    Console.WriteLine("Stopping write thread...");
                    StopThread = true;
                    break;
                }
                else
                {
                    MessageQueue msgQueue = GetStringMessageQueue();
                    msgQueue.Send("New Message send to message queue at " + DateTime.Now.ToString() + "- " + msg);
                }
            }
        }


4) Create function to read message


    private static void ReadStringMessageFromQueue()
        {
            MessageQueue msgQueue = GetStringMessageQueue();
            msgQueue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });

            Message msg;
            while (StopThread == false)
            {            
                if (StopThread == true)
                {
                    Console.WriteLine("Stopping read thread...");
                    break;
                }
                try
                {
                    msg = msgQueue.Receive(new TimeSpan(0, 0, 2));
                    Console.WriteLine(msg.Body.ToString());
                }
                catch (Exception ex)
                {
                }
            }
        }

5) Now create threads within static main method


  static void Main(string[] args)
        {
            Console.WriteLine("Press x to stop thread");

            Thread sendMsgThread =  new Thread(new ThreadStart(SendStringMessageToQueue));
            Thread readMsgThread = new  Thread(new ThreadStart(ReadStringMessageFromQueue));

            sendMsgThread.Start();
            readMsgThread.Start();
         
        }

Thursday, November 8, 2012

Windows Message Queue (MSMQ) Using C#.Net

This article is about creating windows message queue using C#.NET.


In this article we will create a private queue example. Lets develop an app and understand how the private queue works


 1) Create a console application using Visual Studio

 2) In Program.cs create a static method to create/get a private queue. Don't forget to include the "System.Messaging" namespace

private static MessageQueue GetStringMessageQueue()
 {
 MessageQueue msgQueue = null;
 string queueName = @".\private$\MyStringQueue";
 if (!MessageQueue.Exists(queueName))
 {
 msgQueue = MessageQueue.Create(queueName );
 }
 else
 {
 msgQueue = new MessageQueue(queueName );
 }
 return msgQueue;
 }

3) So now we have the queue, lets send a message as given below

private static void SendStringMessageToQueue()
 {
 MessageQueue msgQueue = GetStringMessageQueue();
 msgQueue.Send("New Message send to message queue at "+ DateTime.Now.ToString());
 }

4) Given below is the function to read the message from queue

private static void ReadStringMessageFromQueue()
 {
 MessageQueue msgQueue = GetStringMessageQueue();
 msgQueue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
 Message msg = msgQueue.Receive(); Console.WriteLine(msg.Body.ToString());
 }

5) That's it! Now lets call the functions from 'static main'

static void Main(string[] args)
 {
 SendStringMessageToQueue();
 ReadStringMessageFromQueue();
 Console.ReadLine();
 }


Wasn't that easy! Well this is the basic queue...to make it more useful you have to send the message from one thread and read from another thread or application.

 Happy coding guys!

Thursday, August 30, 2012

Setup and Deployment project for Windows service

In last post we learned to create a simple windows service and used 'installutil' to install the service from console window.

In this post we will learn how to create a setup and deployment project to make the installation process easy!

1) Create a setup and deployment project. Setup project is available in 'Other Project Types' -> Setup and Deployment ->Windows Studio installer


2) Right Click on the project and Select 'Add -> Project Output'
3) Add Primary Output of the project created in previous post

4) Right click View-> Custom Actions

5) Right click on 'Install' and select 'Custom Actions'
6) Select 'File System on Target Machine' from dropdown and Select 'Application Folder' click 'Ok'
7) Select 'Primary Output from ....'
8) Do the same for install ,commit,rollback and uninstall
10) We are done! Build the project and right click and select install. This will install the service in your machine

11) To start the service go to service window (run Services.msc) and select the service and right click on the service and click start!

Tuesday, August 7, 2012

Create Windows Service using C#.NET

1) Create a console Application in .NET and name it "WinServiceTest"

2) Create a class to write data to file as given below


    public class TestWriteFile
    {
        public static bool Shutdown = false;
        Thread fileWriteThread;
        public static void WriteCurentTime()
        {
            while (Shutdown == false)
            {
                string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(TestWriteFile)).CodeBase).Replace("file:\\","");
                using (FileStream ofs = File.Open(path + "\\test.txt", FileMode.Append))
                {
                    UTF8Encoding enc = new UTF8Encoding();
                    String tmpstr = DateTime.Now.ToString() + "\n";
                    ofs.Write(enc.GetBytes(tmpstr), 0, enc.GetByteCount(tmpstr));
                    ofs.Close();
                }
                Thread.Sleep(10000);//sleep for 10 seconds
            }
        }
        public void StartProcess()
        {
            fileWriteThread = new Thread(new ThreadStart(WriteCurentTime));
            fileWriteThread.Start();
        }
        public void StopProcess()
        {
            Shutdown = true;
            fileWriteThread.Join();
        }
    }


3) Add reference to System.ServiceProcess

4) Add service class WinServiceTestService.cs which inherits from ServiceBase.cs


public class WinServiceTestService: ServiceBase
    {
        TestWriteFile oprocessor;
        public static void Main(string[] args)
        {
            ServiceBase.Run(new WinServiceTestService());
        }
        public WinServiceTestService()
        {
            this.ServiceName = "My Win Service Test";
        }
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            oprocessor = new TestWriteFile();
            oprocessor.StartProcess();
        }
        protected override void OnStop()
        {
            base.OnStop();
            oprocessor.StopProcess();
        }
    }




Ok... now we have to create the installer to install the service.

5) Add reference to System.Configuration.Install

6) Write Code for installer as given below


using System.Configuration.Install;
using System.ComponentModel;
using System.ServiceProcess;

namespace WinServiceTest
{
    [RunInstaller(true)]
    public class WinServiceTestInstaller : Installer
    {
        public WinServiceTestInstaller()
        {
            var processInstaller = new ServiceProcessInstaller();
            var serviceInstaller = new ServiceInstaller();

            // Service Account Information
            processInstaller.Account = ServiceAccount.LocalSystem;
            processInstaller.Username = null;
            processInstaller.Password = null;

            serviceInstaller.DisplayName = "My Win Service Test Process";
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            serviceInstaller.ServiceName = "My Win Service Test Process";

            this.Installers.Add(processInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }
}




7) Remove "static" from the "Main" function in Program.cs file

We are done! Windows service is ready. Now we have to install it. For installing we can use 'InstallUtil'.

Open Visual Studio command window and type "installutil /i WinServiceTest.ext" to install the service

To Start the service, open service manager right click on the task "My Win Service..." and click 'Start'

SQL statement to get domain name from URL

Given below is a SQL statement to extract domain name from URLs stored in a table
CREATE TABLE #tmpurl (url varchar(1000))

INSERT INTO #tmpurl (url)VALUES ('http://yahoo.com/')
INSERT INTO #tmpurl (url)VALUES('http://yahoo.com/test')
INSERT INTO #tmpurl (url)VALUES('http://www.yahoo.com/test')
INSERT INTO #tmpurl (url)VALUES('https://www.yahoo.com/test')
INSERT INTO #tmpurl (url)VALUES('https://www.yahoo.com/test?test=a')
INSERT INTO #tmpurl (url)VALUES('https://www.yahoo.com?test=a')

SELECT 
url,
substring(
substring(url,charindex('://',url)+3,len(url)),
0,
case when charindex('/',substring(url,charindex('://',url)+3,len(url)))>0  
then charindex('/',substring(url,charindex('://',url)+3,len(url)))
when charindex('?',substring(url,charindex('://',url)+3,len(url)))>0  
then charindex('?',substring(url,charindex('://',url)+3,len(url)))
else
len(url)
end
)
FROM #tmpurl

Wednesday, March 28, 2012

LINQ - Get distinct values from collection

Below Code snippet shows how to select distinct values from generic collection using LINQ


public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}

List students = new List();
students.Add(new Student { ID = 1, Name = "Adam", Age = 15 });
students.Add(new Student { ID = 2, Name = "Tom", Age = 15 });
students.Add(new Student { ID = 3, Name = "John", Age = 15 });
students.Add(new Student { ID = 4, Name = "Abraham", Age = 15 });
students.Add(new Student { ID = 5, Name = "Abraham", Age = 15 });


/*Find students having same name*/
var samename = students.GroupBy(x => x.Name).Where(g => g.Count() > 1).Select(y => new { Code = y.Key, Desc = y.First() }).ToDictionary(z => z.Code, z => z.Desc);


/*Select distinct name of students*/
var distinctnames = students.GroupBy(x => x.Name).Where(g => g.Count() >0).Select(y => new { Code = y.Key, Desc = y.First() }).ToDictionary(z => z.Code, z => z.Desc);



Friday, January 6, 2012

ASP.NET web method call using AJAX (jQuery)

This article is about how to call a server side function (web method) from client side (aspx page) using AJAX(provided by Jquery).

Its interesting and easy to implement. As always- lets go directly to an example and see how to implement it...



In this example we will create a webmethod which will return a message to client side

1) Create an ASP.NET Application.

2) Add a new page 'WebForm1.aspx' and make it the start up page.

3) In WebForm1.aspx include jQuery file as given below. If you do not have jQuery file, you can download the latest files from http://jquery.com/

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>

4) In code behind page (WebForm1.aspx.cs) create a webmethod to return some data as given below. Make sure to add the attribute [WebMethod()] to the function. You have to include the namespace System.Web.Services. (using System.Web.Services;)

[WebMethod()]
public static string GetData(int userid)
{
    /*You can do database operations here if required*/
    return "my userid is" + userid.ToString();
}


5) Add script tags and include the function to call the web method. Pass the parameter (in this case 'userid') to web method as JSON object

function asyncServerCall(userid) {
    jQuery.ajax({
 url: 'WebForm1.aspx/GetData',
 type: "POST",
 data: "{'userid':" + userid + "}",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (data) {
     alert(data.d);
 }

    });
}


6) Add button on aspx page and call the ajax function on click event.

<input type="button" value="click me" onclick="asyncServerCall(1);" />

7) DONE! Run the app and click the button, you can see that the webmethod is called and data is returned.

Wasn't that easy? Let me know if you face any issue in running this example. I used Visual Studio 2010 to run this app.