Tuesday, 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();
    else
        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:

<appSettings>
    <add key="pageTitle" value="MsTechArticles.com" />
</appSettings>

In this, we have only one application setting. The setting name is pageTitle and the value is MsTechArticles.com.  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);
    config.Save();
}

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 
<appSettings>
    <add key="pageTitle" value="MsTechArticles.com" />
</appSettings>
-->

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 -->
<appSettings>
 <add key="pageTitle" value="MsTechArticles.com" />
</appSettings>

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

Thursday, October 11, 2012

[ Dot Net Remoting ] - MSMQ - Reading all incoming 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);
txtDisplay.AppendText(strMessage);
txtDisplay.AppendText(Environment.NewLine);
txtDisplay.AppendText("==================================================");
txtDisplay.AppendText(Environment.NewLine);



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

Wednesday, 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;
m_edit_ctrl_from.GetWindowText(Source_file);
m_edit_ctrl_to.GetWindowText(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
hcopysource = ::CreateFile (Source_file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
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
hCopyDest = ::CreateFile (Dest_file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
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");
                 ::CloseHandle(hcopysource);
                 ::CloseHandle(hCopyDest);
                 return;
         }
}
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
m_edit_ctrl_from.SetWindowText("");
m_edit_ctrl_to.SetWindowText("");
::CloseHandle(hcopysource);
::CloseHandle(hCopyDest);
Below given video shows the Copy file operation using the Win32 API used in Dialog based MFC Application.

Source Code : Download

Thursday, October 04, 2012

[ Dot Net Remoting ] - Using MSMQ for Sending Message


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:

Fig.1


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:

Fig.2



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
Steps:
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.
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.

Fig.4

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

Steps:

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

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


Steps

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))
        MessageQueue.Create(QueueName);
}

The Queue Q1 is shown in the below video.

Video 4


Steps
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
[Serializable()]
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
Q1.Send(txtName.Text);
Q1.Send(txtOccupation.Text);
Q1.Send(txtAge.Text);
Q1.Send(p);

The below video shows the complete application in action:

Video 5

Steps
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 Firend :)