December 6, 2012

C# - WebBrowser Control

1. Introduction to WebBrowser Control

The "Dotnet WebBrowser Control" provides the capability of browsing the web pages to your application. You can also display your own HTML content through the web browser control. That means you can generate all fancy report and display that in a web browser control. In this article, I will show how can you design simple browsing window (When you are browsing using this sample, Do not provide any personal information. This is just a sample that demonstrates the use of WebBrowser control ). At the end, I will show how do you display the user content and hook button click in the user content to the c# methods.

2. About the sample

The screen shot of the sample is shown below:

The user will type the web address in the Address Bar. To navigate to the typed web address, they should click the Go button. The stop and reload to the same job as every browser is doing today. When the sample is navigating and consuming the web content, the progress bar shows how much the current load content is progressed. The information bar shows what part of the page content is currently getting loaded. When you run the sample you may notice for fully downloading a page, there may be multiple navigation start and end and each denotes that to fully construct the page the sample download the content from the different location. OK, let us start developing the sample.

3. Designing the Web Browser using Visual Studio

The browser we are going to create is composed of ToolStrip, StatusStrip, and the WebBrowser control. First, the toolbar is created and then the required controls on the toolbars are placed. This step is shown in the below video:

Video 1: Setting up the toolbar
In the video, you will not see the buttons for user content. We will add that later. Next, we should add the StatusStrip control to the sample application form. Once the status control is added, a Progress bar and a label for displaying the information are placed in the StatusStrip control. This is shown in the below video:
 Video 2: Setting up the status bar.
Finally, we added the WebBrowser control to our sample. Note that when you place the WebBrowser control on the form, it automatically occupies the entire free area in which it is dropped.
Video 3: Place the WebBrowser control.
Tags for coding: //WEB_BR, //WEB_CS
WEB_BR: Coding shows some basic WebBrowser supports
WEB_CS: Coding shows displaying the user content and handling the control events from those scripts

4. WebBrowser basic actions

WebBrowser control provides rich functionalities and in this sample, we will see only the basic actions like loading a web page, stopping the current page load and refreshing the page load.
1) In the Go button click handler, we take the web address provided in the Address box and navigate to that page. In the meantime, we display the status text "Loading". The Navigate method will absorb the content from the web address specified by the user and displays that in WebBrowser control.
private void btnGo_Click(object sender, EventArgs e)
    //Web_BR 01: Navigate to the URL
    Status_Information.Text = "Loading...";
2) Canceling the page load as well as refreshing the loaded/partly loaded page content are straight forward. We should simply call the corresponding methods in the WebBrowser control to do so. Below are the handler functions for Stop and Reload buttons
private void btnStop_Click(object sender, EventArgs e)
    //Web_BR 02: Stop Loading the Page

private void btnReload_Click(object sender, EventArgs e)
    //Web_BR 03: Refresh the Page

5. Designing Status Information for WebBrowser Control

When we load a web page on a browser; say IE; to fully load the document, the browser has to navigate to different web locations. Say, for example, the website having a lot of YouTube videos and review about the video (Page’s own content is review) also contains a FaceBook like a page on the same page. When we browse to that website, the browser will load the review content of the video from the page itself, then it navigates to the YouTube and FaceBook to get other required information. So, to load a document completely, the browser should navigate to three web addresses even though the user specifies only one address in the address bar of the sample browser.
When the browser is navigating to a different site for loading some portion of the document, we will get two events namely "Navigating Event" and "Navigated Event". The first event says that the navigation is about to start and the second event says, navigation is completed. When the web page document is fully loaded, we get the "DocumentCompleted Event".
We handled all the three events to display the status information:
private void frmWebBrowser_Load(object sender, EventArgs e)
    //Web_BR 04: Hide the visibility of the status bar
    Status_PB.Visible = false;

private void Browser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
    //Web_BR 06: Provide some information about the current navaigation
    Status_PB.Visible = true;
    Status_Information.Text = "Navigating " + e.Url.ToString() + " for " + e.TargetFrameName;

private void Browser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
    //Web_BR 07: Provide some information about the current navaigation
    Status_Information.Text = "Navigated..";

private void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    //Web_BR 08: Provide some information about the current navaigation
    Status_PB.Visible = false;
    Status_Information.Text = "Web Page Loaded";
Note that we hide the progress in the status bar during the form load. And, we enable that when the Browser starts its first navigation for the page. Once we receive the "doumentcompleted event", we again disable the progress bar. Below given video shows loading the web page in our browser sample:
Video 4: Sample in Action: Navigate to a Page

6. Create Plain custom HTML for WebBrowser Control

When we click the custom button 1 from the tool strip, the browser loads custom script 1 as shown below. We access this HTML button shown in the below picture from the C# code and hook the click event of this button to the c# method.
The ToolStrip of our browser sample application is modified to include two more buttons and each button loads two different user content in the web browser control. The below video shows adding these two buttons to the ToolStrip control:
Video 5: Modify ToolStrip Control
Once the buttons are added, using the Visual Studio IDE, the custom web content (Shown in the Picture Above) is created. The formatted content of the IDE created HTML page is given below:
<html >
   <title>Button Click by ID</title>
 <body>The button placed below is a html button. The button is accessed by C# and a handler method(in C#) is provided at runtime
   <input id='BtnTest' style='z-index: 100; left: 8px; width: 102px; position: absolute;top:60px' type='button' value='button'/>
In the above script, we gave an Id (BtnTest) to the “input” control. In addition, the control type is specified as a button. Notice that we don’t provide handler now. At runtime, the browser sample will get this button from the loaded HTML content, and dynamically specifies the handler to the button click. Video 6 shows creating and formatting the HTML shown above using the visual studio IDE. 
Video 6: Creating the HTML content for the browser
Note that we changed the double quotes as single quotes and this will avoid formatting the HTML content when we assign it as a string to the WebBrowser control later.

7. Hooking the event at runtime

1) In the above script, the HTML designer not aware of which function to be called and that is decided at the runtime. The first thing we should do is adding a private flag customDoc1. This flag will be set when the WebBrowser control is loading the user HTML script.
//Web_CS 01: Declare boolean tag for document 1 and 2
private bool customDoc1 = false;
2) In the button click handler (For the first user script), we assigned the above-created user content 1 to the web browser control by setting the "DocumentText Property".
//Web_CS 02: Place the Html document with a button having proper Id
private void btnUser1_Click(object sender, EventArgs e)
    //Setting this property will load the document and raise document completed
    Browser.DocumentText = "<html ><head><title>Button Click by ID</title></head><body>The button placed below is a html button. The button is accessed by C# and a handler method(in C#) is provided at runtime<input id='BtnTest' style='z-index: 100; left: 8px; width: 102px; position: absolute;top:60px' type='button' value='button'/></body></html>";
    customDoc1 = true;
3) As we specified the new content for the WebBrowser control (By setting the DocumentText), the browser will load the content and fires the Document Completed event once the load is fully done. In the event handler, we get the HTML button by its id and store that as "HtmlElement". Then we do provide the event handler to its click event using the delegate "HtmlElementEventHandler". Finally, we reset the boolean flag customDoc1 to false.
//Web_CS 03: Get the Html button from the loaded document
//           Script. Then attach the C# method as click handler
if (customDoc1 == true)
    //03.1 : Get html Element
    HtmlElement btnElem = Browser.Document.GetElementById("BtnTest");

    //03.2 : Hook the C# method to the event
    if (btnElem != null)
        btnElem.Click += new HtmlElementEventHandler(Html_test_button_Hanlder);
    //03.3 : Reset the Tag
    customDoc1 = false;
4) The handler function for the html button click is shown below:
//Web_CS 04: Create a button handler for Html Button
void Html_test_button_Hanlder(object sender, HtmlElementEventArgs evArg)
    MessageBox.Show("Click event of the Script button Handled");
In this section, we created an HTML content with a button in it. Then the HTML content is loaded into the WebBrowser control. Once the user content is loaded completely, we get the HTML button instance from the loaded document and attached c-sharp method as click event handler. In this case, the HTML document designer not aware of the c-sharp handler. In some cases, the HTML script knows which function to call on the c-sharp code library. In that case, they (The script developer) do provide the click handler during the HTML design itself. We see that in the next section.

8. Setting the click handler from External source

Look at the second custom script shown below:
<html >
         <title>Button Click Hooked to External Method of C#</title>
      <body>The scripting person knows which c# function to call. So the well known c# method is tied in the OnClick Attribute
          <input style='z-index: 100; left: 8px; width: 102px; position: absolute;top: 44px'
          type='button' onclick='window.external.ShowMessageE()'  value='button'/>
In this script, the input button is not specified with the id. In the OnClick event, the handler function external.ShowMessageE is specified as an event handler. The external here specifies that the function ShowMessageE() is available from the external source. In our case, the external source is C# as the WebBrowser control is going to load it.
1) In the WebBrowser sample, first, we included the required namespace. This is to make the class "HtmlSupportingMethods" that we are going to implement soon as a COM visible class.
//Web_CS 05: Declare the required namespace
using System.Runtime.InteropServices;
2) In the button click the second user content is specified as the "DocumentText". This document is loaded just the same way we loaded the first script. The only difference is, here we used the verbatim string (@stringcontent) to retain the format of the string as it is.
//Web_CS 06: Set the Html as document content of the browser control.
private void btnUser2_Click(object sender, EventArgs e)
    string htmldoc = @"<html >
    <title>Button Click Hooked to External Method of C#</title>
    <body>The scripting person knows which c# function to call. So the well known c# method is tied in the OnClick Attrubite<input
            style='z-index: 100; left: 8px; width: 102px; position: absolute;top: 44px'
            type='button' onclick='window.external.ShowMessageE()'  value='button'/>

    //Setting this property will load the document and raise document completed
    Browser.DocumentText = htmldoc;
3) The class HtmlSupportingMethods contains only one public method, which is accessed by our custom script 2 as Window.external.ShowMessageE(). As this method is accessed by the external scripting world, we mark the class as COM compatible by declaring the class with the "[ComVisible(true)] Attribute" 
//Web_CS 07: External scripting methods. This class is set with the ComVisible attribute
//           as it's methods are going to be accessed by the html document content that
//           will be loaded by the Web Browser control
public class HtmlSupportingMethods
    public void ShowMessageE()
        MessageBox.Show("External Method Accessed");
4) There is one final step. How does the content loaded on the WebBrowser control knows where should it get the External Source? We should link the C# HtmlSupportingMethods with the HTML script. We do that in the form load as shown below:
//Web_CS 08: Set the Scripting Object. This should a com visible object
Browser.ObjectForScripting = new HtmlSupportingMethods();
The browser sample in action can be found in the below video. The video shows both the user HTML document and hooking the HTML button click to C# code.
Video 7: Testing the scripting support
Source Code: Download

October 30, 2012

ASP.Net - Dynamically updating web config file in .net

1) Introduction

Website settings are supplied by the web.config file. The settings are like connection strings, how many users allowed etc. Sometimes the situation arises that the configuration settings to be added or revoked without re-starting the server. In this article, we will see a demo of how do we add new settings when the site is running. Imagine that the page we are going to develop is used by the web admin of the site. The goal is adding a new web setting dynamically, and in the meantime, the server will function as usual without any re-start.

2) About the sample

The page design screenshot is provided below.

In the username section of the page, we add the session variable for the user name when the Set User Name button is clicked. The Get User Name button will retrieve the session variable content and displays that the label next to it.

In the Application Settings section of the page, we add a web setting dynamically by clicking the Store button. We should provide a setting name and an associated value to it in the corresponding text boxes. By clicking the Retrieve button, we can get the setting value by supplying the setting name.

In this demo, we are going to add new setting by clicking the Store button and make sure that session we set before this operation is kept unchanged. OK, Let us start.

3. Session Variable

A session identifies a user connecting to the website and the session continues until he/she disconnects from it. Now the session variable is one, which has the scope of the connected user session and the variable goes out-of-scope when he/she disconnects the web session. Therefore, once we define and assign a value to a session variable, the content is available for all the pages within that session.

In our sample, we store and retrieve the user name as the session variable.

1) In the button click handler for the Set User Name, we are setting the content of the username in a session variable called “User Name”. Here, the username is the Key and the value is whatever we specify in the text box next to Set User Name.

//Sample 01: Store a session variable
protected void btnSetUser_Click(object sender, EventArgs e)
    Session["User Name"] = txtUserName.Text;

2) When Get User Name button is clicked, we get the “User Name” session variable and display that in the value textbox. Before doing so, we are checking the session variable UserName is actually having any value. If we don’t have a value, then we display session is lost. Actually, the message becomes meaningless when the session is not yet created. This session variable is just for demo purpose and our goal is modifying the web application setting without loosing the session variables. So, do not worry about the validation message and how meaningful it is in a variety of situations.

//Sample 02: Retrieve session variable Name
protected void btnGetUserName_Click(object sender, EventArgs e)
    if (null != Session["User Name"])
        lblSession.Text = Session["User Name"].ToString();
        lblSession.Text = "The Session variable is lost";

3) In the clear button click event handler, we cleared some of the form fields for convenience while entering the new values

//Sample 03: Clear the form
protected void btnClear_Click(object sender, EventArgs e)
    lblSession.Text = "";
    txtName.Text = "";
    txtValue.Text = "";

OK, Let us test what we have written in the two button click events. The video below shows setting and retrieving the username in a session variable called User “User Name”.

Video Steps

  1. The solution is run in debug mode
  2. Then, the user name for the session is set by clicking the Set User Name
  3. Finally, the username in the session is retrieved by clicking the Get User Name

4. Retrieving the App Settings

1) We use the WebConfigurationManager to retrieve the application settings that is previously saved in the web.config file. When we click the Retrieve button after supplying the setting name, the settings value is retrieved and displayed in the value text box. The code for that is given below.

//Sample 06: Retrieve the Setting
protected void btnRetrieve_Click(object sender, EventArgs e)
    string value = "";
    if (WebConfigurationManager.AppSettings[txtName.Text] != null )
        value = WebConfigurationManager.AppSettings[txtName.Text];
    txtValue.Text = value;

2) Have a look at the section of code taken from the web.config file, which is given below:

    <add key="pageTitle" value="" />

In this, we have only one application setting. The setting name is pageTitle and the value is  Now watch the video below which shows retrieving the setting value for the given key pageTitle.

Video Steps

  1. In the web.config current application setting section is previewed
  2. Moved to DynamicSettings.aspx and Run toolbar button is clicked
  3. In the form Setting name (pageTitle) is given and setting value is retrieved

5. Dynamically storing the Settings

The settings are stored in the web configuration file under different sections. In this article, we are looking at the AppSettings section only. You can apply what you learn in this article to any configuration sections (With little exploration when required). Say for example ConnectionStrings. We use OpenWebConfiguration method of the WebConfigurationManager to dynamically add a new setting to the web configuration.

//Sample 05: Add New settings
protected void btnStore_Click(object sender, EventArgs e)
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
    config.AppSettings.Settings.Add(txtName.Text , txtValue.Text);

In the above code, we get the reference to the Configuration object by calling the OpenWebConfiguration available in the root directory of the web application. If it is not there then we get the settings from the default configuration of the machine. This configuration is the merged view of the all the available settings. Therefore, from the config instance, we get the Application settings to add the application-setting name and the associated value to it. In our sample application setting and the name is supplied by the user (Say web Admin). Once the settings added to the required data structure, we call the save method on the config object.

It is time to check the code written for storing the application setting. The below-given video shows storing the configuration setting dynamically. It also shows that we add a new entry in the web.config file, we lose our session and application (Not shown in the demo) variables.

Video Steps

  1. The form is run in the debugger mode
  2. A first setting setting1 and corresponding value are added
  3. Then a second setting setting2 and corresponding value are entered
  4. Before clicking the store button, a session value is stored in a session variable
  5. Then, store button of the Application setting clicked to append one more setting (Setting2)
  6. The Get User Name button is clicked, and Session Variable content loss is shown
  7. At last, dynamically added web setting are shown in the web.config file

6. Dynamic Update of Web Settings without losing the Sessions

We did modification in the web.config dynamically and all the session variable contents are lost. This we saw in the previous video. To avoid this we should move the application settings to a new configuration file. This file is referred as External Configuration file. Add a new configuration file called settings.config by right-clicking the project name and selecting Add New Item from the displayed content menu. The picture given below shows entering the data in the Add New Item Dialog.

The external configuration file is added to the project after clicking the add button in the “add new item” dialog. Now go to the Web.Config file and remove or comment out the AppSettings section. The code given below shows the commented out piece of code in the web.config file.

<!-- Sample 07: Comment out AppSettings section 
    <add key="pageTitle" value="" />

Once the above code is commented out, we should specify the external file name in the web.config file to look for the AppSettings in it. Web.config file entry for that is shown below:

<!-- Sample 08: Specify the external settings source  -->
<appSettings configSource="settings.config"/>

Now add the AppSettings that is commented or Removed (From the original web.config file) to the newly created Settings.config file. The added AppSettings section is shown below:

<!-- Sample 09: Add the App settings in the external source file -->
 <add key="pageTitle" value="" />

That is all the code change required in the configuration to make the dynamic update of the web configuration file. Now we will not lose our session variables when a new entry is added to the web configuration. This time, new settings enter the Settings.config in place of the web.config. Watch this in the video given below:

Video Steps

1) The form is opened in the browser
2) The settings are entered in the Application Settings portion of the form
3) Also, the session variable is stored and retrieved in between the settings change

The settings stored in Settings.config file by the above testing (One shown in the video) is shown in the below picture:

There is one more point that should be noted here. The AppSettings by default does not require any server re-start when we append the settings dynamically. For other sections, you should always make sure that ReStartOnExternalChanges is set to False. This we should check on the machine.config file and the screenshot given below shows the default entry for the appsettings.

Examine the path:
 <DriveLetter>:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG for machine.config file. Say for example you want to add a new connection string in the web configuration, the first thing you should do is check the machine.config file and set the restartonExternalChanges=false. Then follow what you learned in this article.

Source Code: Download

October 11, 2012

.Net Remoting - Reading all incoming MSMQ Message

1) Introduction

In the previous article, we looked at writing into the message queue. We wrote separate messages as well as a class instance to it. In this short article, we will see how we can read all the Messages from the Queue.

2) About the sample

Reading message queue is done through the client application and its screenshot is given below:

Fig 1. Sample Application

The sample is created using C# Windows Application Project. By clicking the Read Messages, we get all the messages in the private queue Q1 and display that in the text box shown. In the next coming articles, we will see how we can use formatters while reading and writing messages. There is nothing more here to talk about the sample.

3) Source Code

1) As told in the previous article on dot net remoting, a reference to the MSMQ assembly (System. Messaging) is added. Once we have a reference with us, we can start using it in our C# code files. Like that, we provided the using statement in the form’s .cs file.

//Sample 01: To Use Message Queue
using System.Messaging;

2) A class level variable QueueName is declared and it is holding the Queue with a path to it. This Queue will be referred when the Read Messages button clicked by the user.

//Sample 02: Message queue to read
string QueueName = ".\\Private$\\Q1";

3) In the button click handler, we get a reference Q1 to the queue by specifying its name.

//Sample 03: Grab the Message Queue Q1
bool NoMessage = true;
MessageQueue Q1 = new MessageQueue(QueueName);

4) When you execute the Sample discussed in the previous article on dotnet remoting, you get four messages in the message queue named Q1. GetAllMessages function call of the MessageQueue will return the collection all the messaged that is not yet removed from the queue. In the below code we store all the messaged in AllMessages collection.

//Sample 04: Grab the Message Collection from the Queue
System.Messaging.Message[] AllMessages = Q1.GetAllMessages();

5) Next, we iterate through the collection class to read each individual messages from the collection retrieved. Once we have the message, we are interested in the content of the message. First, we take the BodyStream from the message and this body stream is actually an IO.Stream instance. As message body, we are having is in the form of a stream, we used the Read method to retrieve the streaming content in the byte array of 1024 max.

//Sample 05: Iterate through each message
foreach (System.Messaging.Message theMessage in AllMessages)
    //Sample 5.1: Read the Message body as a Byte array
    NoMessage = false;
    byte[] data = new byte[1024];
    theMessage.BodyStream.Read(data, 0, 1024);

6) To display the message in the textbox, the byte array is converted into a text string using the ACCIIEncoding. Once we have the body of the message in the form of string we will display that in the text box. The code for that is shown below.

//Sample 5.2: Convert the byte array to string and display it
string strMessage = ASCIIEncoding.ASCII.GetString(data);

4. Running the Sample

Below given video shows the sample in action. Note that the video shows, writing into the message queue using the sample application created in the previous article on dotnet remoting and then reading those messages from the sample created in this article.

Source Code : Download

October 10, 2012

[ Win32 MFC ] - File Processing using CreateFile, ReadFile and WriteFile APIs

1) Introduction

In this article, we will look at the example of using the CreateFile and OpenFile win32 API functions with a MFC Dialog based application. Win32 is a very rich API that supplies numerous functions and MFC is just a Framework wrapped over those functions to form logical functioning unit. Win32 API library is in native format that means it is in C style (Procedural Approach) whereas MFC is a OOPS based Framework API. OK, let us start with the sample.

2) About the Sample

Have a look at the below screenshot

This sample is created to copy the file content from source location to destination location. This plain file content copy operation is already supported by the operating system and this example is taken just for demo purpose. However, you can extend the operation to transform source content to destination by skipping some words or adding something to the word etc.

Specify the file name to copy in the Source File Path and specify the destination file name in which you need a copy of the source file content. The CopyFile Win32 API will do this task easily. However, in this article we are going to explore the Win32 file processing functions. The sample is created using the VC++ dialog based application.

Creating the dialog based application is shown in the below video.

Once the dialog-based application is created, control variables added to the edit box controls. This is shown in the below video:

3) Copy Content Button Handler

1) First, the win32 handles to the files are declared and these handles are hcopysource, hCopyDest. Next the variables bytes_read, bytes_written are used to store number bytes read and written depending on the file processing operation. The buffer variable is used as the cache by the program to temporarily store the data read from the file.

//Sample 01: Declarations Required
HANDLE hcopysource, hCopyDest;
DWORD bytes_read, bytes_written;
CHAR buffer [4095];

2) Next, we read input entered by the user from the text box control variables to the string variables Source_file, Dest_file. The GetWindowText functions return the text key-in in the text boxes.

//Sample 02: Get the User input
CString Source_file, Dest_file;

3) The Win32 API function CreateFile is used to open the file entered by the user. The OPEN_EXISTING tag will tell the API to open the file when it already exits and fail otherwise. Once the file content that we are going to copy is opened, we store its handle in the hcopysource. The GENERIC_READ flag tells that we going to open the file for reading purpose.

//Sample 03: Create the Source File
if (hcopysource == INVALID_HANDLE_VALUE)
         AfxMessageBox("Unable to Open Source File");

4) The same way we store the destination file handle. Here it is expected that the file does not exist in the destination folder and we always try to create the file as new file in the location specified. The flag GENERIC_WRITE tells that we are going to use this file for writing something on it. The CREATE_ALWAYS attribute tells that we are always going to create the file. If it doesn’t exists in the destination location the API will create a new file and if it is there in that location then the function will just open it. Therefore, the tag always creates the file and gives back the handle.

//Sample 04: Create Destination File
if (hcopysource == INVALID_HANDLE_VALUE)
         AfxMessageBox("Unable to Destination Source File");

5) We use ReadFile API to read the data from the source file. Once the call succeeded, we will get the read content in the buffer variable. Note the usage of the while loop and when the file content is more that 4095 bytes, the read operation will be performed in batches. That is, 4095 or less (That will be last read) bytes will be read in each batch. The bytes_read variable will tell us how many bytes are read from the source file. Say for example, the file has 5000 bytes of data, and the first read batch will read all 4095 bytes the remaining 5 bytes are read in the next iteration. This way, we use the bytes_read variable when writing the data to the destination file using the API function WriteFile.

//Sample 05: Read the Source file content in a batch of 4095 or Lesser, then
//                        write to destination file
while (::ReadFile(hcopysource, buffer, 4095, &bytes_read, NULL) && bytes_read > 0)
         ::WriteFile(hCopyDest, buffer, bytes_read, &bytes_written, NULL);
         if (bytes_read != bytes_written)
                 AfxMessageBox("Something Gone wrong while writing to destination. Aborting the operation");
AfxMessageBox("File contents copied to destination");

6) Once the Operation is completed, we close the file HANDLES opened the button click event and display a message stating the content of the file copied to the destination.
//Sample 06: Do the Clean-Up work
Below given video shows the Copy file operation using the Win32 API used in Dialog based MFC Application.

Source Code : Download

October 4, 2012

.Net Remoting - Sending Message through MSMQ

1) Introduction

MSMQ stands for "Microsoft Message Queue". MSMQ is a message storage area where one more application contacts to send or receive the messages. The message is packed information and it can be plain text in XML or Binary or another supported format. Look the Fig.1 below:


Message Queues allows communication between one or more application and in the meantime it won’t force the application being communicated should be in live connection. Application 1 can send information and quit or do another task. Application 2 when free looks at the queue and catches the passed-in communication.

MSMQ can maintain one or more queue. In the above picture, three queues are shown for an example. We are going do develop a sample in this article, which will send and receive the information through the MSMQ as shown in fig.1. We are going to use only one queue say Q1. Nevertheless, you can create multiple queues based on the need.

2) Installing MSMQ Windows Component

MSMQ is a windows component like IIS services. So first, you should make sure that the MSMQ component is installed on your machine. To do that, go to the services window by typing services.msc in the run prompt. Make sure that the services shown in Fin.2 are available and running on your machine:


If the services are not available then the MSMQ windows component is not installed on your machine. The video given below shows how you can install the MSMQ in Win 7. The steps are same for windows XP also. Only the user interface displays changed slightly.

Video 1
1) Control panel is invoked
2) Program Features is opened
3) Turn Windows Feature On/Off is selected from side pane
4) From the window displayed, MSMQ component is selected and installed.
If you are using the WindowsXP, Add/Remove Windows Components should be selected as shown in Fig.3.
Once you install the MSMQ component, it is a good practice to restart the machine for a smooth launch of the MSMQ services. However, this step is not a mandatory one.

3) Accessing the MSMQ

Once MSMQ windows component is installed on your machine, you can access it through the computer management utility. There are many ways available to invoke the computer management. Fig.4 shows the computer management and MSMQ location in the left side tree. In the run prompt, one should type "mmc.exe compmgmt.mmc" to invoke the computer management.


The video shown below is loading the computer management using other two methods. In the first method, we loading it through the Administrative tools and in the second method we are using the window explorer to load it. In windows explorer, we invoked the context menu for the My Computer icon then selected the menu option Manage.

Video 2


1) From the start menu, administrator tool is accessed
2) Then, the computer management option selected from the displayed menu.
3) The Computer management window is closed
4) Windows explorer is opened
5) Manage option is selected by right clicking the My Computer icon
6) Location MSMQ is navigated from the displayed Computer Management administration window.

4) About the Sample

The sample application’s screenshot is shown below in fig.5

When we click the send button, the details entered into the textboxes are posted to the MSMQ as separate messages. The send button also forms a class instance with all three details and sends it as a single message. There is nothing more to talk about this sample at this moment. Let us start with developing the sample.
This sample deals with only sending the message to MSMQ. In the next article, a separate sample will be given and that will read message send by a sample application that we are going to discuss in this article.

5) Providing reference to MSMQ

When we started the C# Windows application project, the IDE will not provide the reference to the MSMQ DLL. Therefore, we cannot access the message queuing functionalities. To bring the message queuing capabilities to the application we should provide assembly reference to the "System.Messaging". This is shown in the below video:

Video 3


1) From the project, explorer reference node is right clicked
2) From the context menu Add reference… is invoked
3) From the displayed dialog, the Assembly binary for System.Messaging is selected
4) Then in the source window using statement for the messaging is provided
The using statement included in the source code is below:

//Sample 01: Include the required namespace
using System.Messaging;

6) Create MSMQ

You can create the Message Queue from the computer management screen itself. But, I will leave that to you to explore it yourself (Not a big deal). First, we declared a variable that holds the Queue Name:

//Sample 02: Message Queue Name
string QueueName = ".\\Private$\\Q1";

The . notation says that the queue is on the local machine. You can try the queue on a remote machine by replacing the dot with system name. Then we specified that the queue is a private queue and queue name is Q1. Once you see the Q1 in the Computer Management screen, you will come to know about the above statement easily.

Next, we checked that the queue specified above exists or not. When it doesn't exist, we create that queue. Checking the existence and creating the queue is done in the form load of the sample. This code is shown below:

private void frmSender_Load(object sender, EventArgs e)
    //Sample 03: Check Queue Exists, if not create it.
    if (!MessageQueue.Exists(QueueName))

The Queue Q1 is shown in the below video.

Video 4

1) Computer management is accessed
2) Then, inside the Management window, MSMQ is navigated
3) Queue created in the Form Load is shown

7) Person Class

We are going to send the person class instance to the MicroSoft Message Queue. To add a person class right-click on the project name and select Add Class. The complete person class is shown below:

//Sample 04: The person class that needs to be sent to MSMQ
public class Person
    public string m_name;
    public string m_age;
    public string m_occupation;
    public Person() { }
    public void SetDetails(string name, string occ, string age)
        m_name = name;
        m_age = age;
        m_occupation = occ;

As we are going to send the instance of the Person class to the message queue, we specified that it should be serializable by marking the class with the arttribute [Serializable()]. Also, note that we provided a public constructor as well as a default constructor (A constructor that won’t take any parameter(s) ). The member that we want to include in the message body is set with the public scope.

8) Sending Message to the created Queue

When we click the send button of our sample application, the queue is referenced and through that, we will send the message. Note that the queue existence is already performed in the form load. In the click event handler of the send button, we are just going to get a reference to the existing queue.

//Sample 04: Get the reference the Queue that exists/created (During for load)
MessageQueue Q1 = new MessageQueue(QueueName);
Person p = new Person();
p.SetDetails(txtName.Text, txtOccupation.Text, txtAge.Text);

Here, we first get a reference to the Q1 queue. Then, an object for a person is created and the person’s details are set through a member function. We are going to send this instance p to the message queue using the "default xml formator". We will explore other formators in a different article later.
Sending message to the message queue is done through a call to Send member function. First, we sent three string messages, which are nothing, but the Person’s details collected from the form. All these three messages are separate entries in the Queue Q1. Next, we sent all the three information packed inside the instance called p as a single message. Below is the code:

//Sample 06: Now send the person to the message queue

The below video shows the complete application in action:

Video 5

1) The sample exe is loaded
2) Data entered into the form and send button is clicked
3) Q1 in the message queue is navigated
4) All four messaged are shown [Three string and one class instance in xml format]

Note reading the queue is not shown in the article. We see that in the next article on Dotnet.remoting. See U then.

Source Code: Download

Like this site? Tell it to your Friend :)