Showing posts with label Whitepapers. Show all posts
Showing posts with label Whitepapers. Show all posts

ASP.Net is a stateless connection. The pages gets recreated every time the page is posted back to the server. In order to maintain the changes done by the user, asp.net has different state management techniques.

ASP.Net supports Client-side and Server-side State Management options as listed below. In this article we will see client-side management techniques.

Client-side State Management

In this approach, the state information is stored on the client's computer/browser in the form of a URL, Cookies or as Hidden Fields in the webpage. Client side approach is scalable as it stores data on multiple servers i.e. each users information on their own system. There is no need for the server to remember their individual preferences. But on the other hand, client-side approach can create performance bottle necks if large data is stored, as the data would travel between client and server during postbacks.

Lets see these techniques in details with examples.

a. QueryString: With this option, you can pass values from one page to another as query strings, appended to the end of the page's url. Use this option if you are not passing any important values like email id, or any other parameter value as it is visible to the user.

Building a QueryString
The values in the query string passed as key/value pairs seperated by an '&' (ampersand). You can use Server.Transfer or Response.Write method to redirect to the other page by concatenating the parameters as below.


http://www.test.com/test.aspx?day=14&month=07&year=2010


Getting values from the querystring
Below example shows how to get the day, month & year values from the querystring. You can get the querystring value by passing in the name of the querystring or by index to the Request.QueryString object.

Request.QueryString["day"] or Request.QueryString[0]
Request.QueryString["month"] or Request.QueryString[1]
Request.QueryString["year"] or Request.QueryString[2]


b. Cookies: Cookies store the information on the users system. Information like login information, user preferences are generally stored in cookies. Cookies can be accessed across multiple pages. This option is not used to store large values as the information travels back and forth between client & server.

Store the cookies values in Form1.aspx and redirect to Form2.aspx

Response.Cookies["firstname"].Value = "John";
Response.Cookies["lastname"].Value = "Deller";

Server.Transfer("~/form2.aspx");


Retrive cookies value in Form2.aspx page using a label control

lblFinal.Text = Request.Cookies["firstname"].Value + " " + Request.Cookies["lastname"].Value;


c. Hidden Fields: Hidden Fields are stored at the client's side, as HTML on the web page but they are not visible to the user in the page's output on the browser.

It can be viewed by the user by opening the page source hence not used to store important data. As hidden fields also travels back and forth on each requests, it is recommended not to store large data in the hidden fields to avoid performance issues. It can be used to store data related to the user & their preferences.

Store values in hidden field
Insert a placeholder tag which will be replaced by the one that you pass using the code as below:

Aspx page:
<asp:PlaceHolder ID="plHolder" runat="server"></asp:PlaceHolder>

Code:

HtmlInputHidden _htmlInputHidden = new HtmlInputHidden();
_htmlInputHidden.ID = "promotion";
_htmlInputHidden.Value = "50% discount on men's wear";

plHolder.Controls.Add(_htmlInputHidden);


Retrieving the value from hidden field

String strHiddenValue = ((HtmlInputHidden)plHolder.FindControl("promotion")).Value;


d. View State: View State are also stored as HTML on the web page, similar to hidden fields. The data stored in the view state is specific to that page, it cannot be passed to the other pages.

Data can be retained in the view state in between post backs. Most of the server controls in asp.net use view state to retain the data entered by the user during post backs. Custom values can be stored in the view state object.

Again, as this is passed between client and server during post backs, store small amount of data to avoid performance bottlenecks.

Storing value in view state: ViewState["test"] = "This is a test string";

Retrieving value from view state: String strViewState = ViewState["test"];

e. Control State: Control state is like View State but reserved for the custom control you develop. So if you are building your own custom control, its better to use Control State so the users using your control do not break your control by disabling View State.

Refer: http://www.pluralsight.com/community/blogs/fritz/archive/2004/07/01/472.aspx for more details & example.

References
http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

Update IIS Settings using Script

Posted by Techie Cocktail | 12:19 AM | , , | 0 comments »

Introduction
Internet Information Services (IIS) is a widely used Internet Services Platform for Microsoft Web Applications. The Web Applications are hosted on IIS by creating websites/virtual directories and/or application pools. Various settings need to be configured before and after the application is deployed on IIS. Some of the important settings are TCP Port, SSL Port, Connection Timeout, IIS log files properties, application pool settings and others.

Most of us configure these settings by going to the IIS Manager (start->Run->inetmgr) which everyone would be already aware of. But there is another approach to update the IIS Settings and that is using an IIS Admin script. The server administrators would know about its usage but for those who are not aware of this approache, you will believe that its quite easy to use it as well.

Lets see the script & related files locations and its usage. In this article, we would see how to read the existing websites, virtual directories (VDs) and app pools (APs) on IIS. Then we will see how to read the values of some their common configuration settings followed by updating the settings. We won't create or delete any websites, VD or APs.

Files and locations
The important files here are:
a. adsutil.vbs: This is THE script to GET or SET configuration settings in IIS.
Located at: C:\Inetpub\AdminScripts\

b. MetaBase.xml: This file stores the current IIS Settings in the XML Format.
Located at C:\%SystemRoot%\System32\Inetsrv\

c. MBSchema.xml: This file contains all the properties with their InternalName and datatypes. The internal names correspond to the property name that you would use to update the value using adsutil.vbs script.
Located at C:\%SystemRoot%\System32\Inetsrv\

These files should be secured and accessible only to administrators because of wrongly updated may break your web applications. But you need not exactly be worried because the backups of both of these XML Files are being maintained for us to rollback any changes which are located at C:\%SystemRoot%\System32\Inetsrv\History.

You can have a quick look at the Metabase files to get familiarized with the common property names and their datatypes that you require to update in IIS.

Let us now look at the usage of adsutil.vbs script and GET/SET some of the common properties.

Using the script
Commands to Analyze Websites, VDs & APs created on your IIS
a. The first thing is to list the instances of the websites, VDs and APs created on your iis. Using the instance name, you can target the settings that you need to read or update.

The below command enumerates the paths (instances) of all the websites, VDs, APs on your webserver. Using these paths, you can target the settings for the ones that you need to update.

c:\Inetpub\Adminscripts>adsutil.vbs enum /P /w3svc

The result will be something like this:

[/w3svc/1]
[/w3svc/1025764322]
[/w3svc/2]
[/w3svc/3]
[/w3svc/AppPools]

where [/w3svc/1], [/w3svc/2], [/w3svc/3] correspond to websites and results like [/w3svc/1025764322] are for VDs.

b. Get the details of a particular website.

c:\Inetpub\Adminscripts>adsutil.vbs enum /w3svc/1

Note: Do not include the /P (path) switch.

In the result, you will see the values of various configuration settings as in your IIS Manager for a website. The website name is determined by the 'ServerComment' property.

c. Get the details of a particular virtual directory.

c:\Inetpub\Adminscripts>adsutil.vbs enum /w3svc/1025764322

d. Read or update the details of specific property values.

Use GET to read and SET to update:

1. Get the ServerComment property value. This corresponds to your website name under Default Website.
c:\Inetpub\Adminscripts>adsutil.vbs GET /w3svc/1/ServerComment

2. Get the ServerBindings property value. This is corresponding to the TCP Port value in the website tab of your website.
c:\Inetpub\Adminscripts>adsutil.vbs GET /w3svc/1/ServerBindings

3. Get the SecureBindings property value. This is corresponding to the SSL Port value in the website tab of your website.
c:\Inetpub\Adminscripts>adsutil.vbs GET /w3svc/1/SecureBindings

4. Disable the Basic Authentication.
c:\Inetpub\Adminscripts>adsutil.vbs SET /w3svc/1/AuthBasic "False"

5. Set the ConnectionTimeout value to 120 seconds.
c:\Inetpub\Adminscripts>adsutil.vbs SET /w3svc/1/ConnectionTimeout 120

e. Get the list of App Pools.

c:\Inetpub\Adminscripts>adsutil.vbs enum /P /w3svc/AppPools

The above command gets the existing App Pools. To read or update the property value of an app pool, use GET or SET commands as shown in section d.

c:\Inetpub\Adminscripts>adsutil.vbs GET /w3svc/AppPools/<AppPoolName>/<InternalName>

The commands are easy to use and also you can get hold of the website, VDs or APs whose settings you need to update using the /P (path) in the command.

The only thing you need to know is the exact InternalName (PropertyName), that you can use in your commands. You can either refer to your Metabase xml file or for a quick check you can also use the below command and search through the appropriate name. Its result will have most of the common property names and their datatypes listed for you.

c:\Inetpub\Adminscripts>adsutil.vbs enum /w3svc

Isn't it easy and straightforward? Hope this makes your life easy and makes you happy too. Have fun!

References
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d3df4bc9-0954-459a-b5e6-7a8bc462960c.mspx?mfr=true

Message Queuing - MSMQ

Posted by Techie Cocktail | 9:07 AM | , | 1 comments »

MSMQ is a wonderful, easy and powerful methods by which messages can be stored and retrieved from an independent location. This store is unlike databases or a file server where objects can be sent and received independently. This article explains the basics of installing and configuring MSMQ followed by message send and recieve process using an example. MSMQ is further vast in itself. At the end of this article reference sites are available for more information on MSMQ.

What is MSMQ? How it works?
MSMQ is a message queuing system that enables applications to send and receive messages (objects). It is a seperate independent location where messages are stored and retrieved by applications. The receiving application need not be connected at the time when the sender is storing the messages. Messages can be received at a later time when the sender has finished its processing.

Messages can be an xml document, text, images, or in any other format that the receiving application understands. Message Queues can be private or public. Private queues limit their access to the local computer. Public queues are published is the active directory and can be found and accessed by computers in the network.

Before the applications can use the queues for message exchange, they need to be created first. You can use either create them manually or programmatically.

Lets us first see how to install and configure MSMQ. After we install and configure the queue, we will see how to send and receive messages to and from the queue with a good example.

Configuring Messaging Queue:
1. Go to 'Add or Remove programs' through Control Panel.
2. Click on 'Add/Remove Windows Components'.
3. Search for 'Application Server' & click on Details button.
4. Check mark 'Messaging Queue' and hit OK and follow the wizard till the end.

The location for 'Messaging Queue' may be different on your box, just search for 'Messaging Queue', it must exist somewhere in 'Add/Remove Windows Components' window.



Once it is installed, you should see 'Message Queuing' under 'Services and Applications' in Computer Management snap-in as below.



Creating Queues:
Queues can be created manually or programmatically.

Manual Approach:
1. Open the computer management snap-in.
2. Go to the 'Message Queuing' under the 'Services and Applications'.
3. Right click on the 'Private Queues' -> New -> Private Queue. Enter queue name and hit OK. Your queue gets created.



Programmatic Approach:
.Net provides System.Messaging namespace that contains MSMQ related classes.


MessageQueue msgQueue = MessageQueue.Create(@".\Private$\MyQueue");

Now as we know how to create queues, lets see how to send & retrieve to/from our created queue.

As an example, lets create an XML file. Then create a sender application to read and send the XML file to our queue and a receiving application to read and process the XML file.

XML File:
Lets name this xml file to msg.xml, its content as below.

<?xml version="1.0" encoding="utf-8" ?>
<topic>
<name>MSMQ</name>
</topic>

Sender Application:
This application reads the XML file into XMLDocument object (System.XML namespace), copies the Xml into the message body, serializes it using XmlMessageFormatter, and sends it to the Message Queue.
as message to our queue.

static void Main(string[] args)
{
//Create a private queue
MessageQueue msgQueue = MessageQueue.Create(@".\Private$\MyQueue");

//Loads xml into XMLDocument object
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"d:\msg.xml");

//Get the xml into the message body
Message msg = new Message();
msg.Body = xmlDoc;

//serialize the message before sending it to the queue
msg.Formatter = new System.Messaging.XmlMessageFormatter();
msgQueue.Send(msg, "msg1");
}

After executing this code, you will see the msg1 created in the queue as below.



Receiving Application:
As we serialized the message before sending to the queue, at the receiving end the message would need to be deserialized after receiving it and before we could process it further.

static void Main(string[] args)
{
//create & define the message queue
MessageQueue msgQueue = new MessageQueue();
msgQueue.Path = @".\private$\MyQueue";

//Receive the message from the queue.
Message msg = new Message();
msg = msgQueue.Receive();

//define the type of the message being received to deserialize it in the same format as sent
Type[] targettype = new Type[1];
targettype[0] = typeof(XmlDocument);
msg.Formatter = new System.Messaging.XmlMessageFormatter(targettype);

//get the xml message in the XMLDocument object and further process it
XmlDocument xmldoc = new XmlDocument();
xmldoc = (XmlDocument)msg.Body;


Console.Write(xmldoc.InnerXml);
Console.Read();
}

The above example shows how to retrieve a single message. If you want to receive more then one message you can use GetAllMessages() method of the queue and iterate through each message and further process them.

References:
a. MSMQ FAQs: http://www.microsoft.com/windowsserver2003/techinfo/overview/msmqfaq.mspx for more details.
b. MSMQ Complete Reference: http://www.microsoft.com/windowsserver2003/technologies/msmq/default.mspx

Debugging and its techniques in .Net

Posted by Techie Cocktail | 6:42 PM | | 0 comments »

Debugging is one of the most important aspects of developing quality code. It helps a developer to analyze the code at various points. Use of effective debugging techniques helps better understanding and fast analysis of the code thereby increasing the productivity.

Debugging often involves verification of the code, analysis of the code functionality when a bug is reported, or understanding of a pre-written code.

It is really very useful to understand the strong debugging techniques that .net language and IDE provides. Let us see some good debugging techniques available.

1. F9, F5, F10, F11 – Most of us are already familiar with these Hot Keys.
F9 – Used to set up breakpoint.
F5 – Starts the debugging.
F10 – Step Over.
F11 – Step into.
Shift + F11 – Step Out.

These options are available in the Debug menu of IDE.

2. Debug Windows: Following windows will be useful to look at for analyzing various output results. I am not going into details to explain these windows as this is out of scope of this article.

Output, locals, watch, call stack, Immediate.

3. Debugger and Debug Class available in system.diagnostics namespace. These are coding approaches of debugging in .net.

Debugger:
Has some important methods useful for debugging like Break() and Log().

Break() is similar to the breakpoint that we put using F9 Hot Key. But using this approach, we can make it conditional.


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int result = division(1, 2);
if (result == 0)
{
Debugger.Break();
}
}

static private int division(int num1, int num2)
{
return num1 / num2;
}
}
}

In the above example, if the result is non-zero, the debugger will not get activated.

Log() method is used to log the data to the attached debugger. The below example prints the output to the output window.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int num1 = 1;
int num2 = 2;
int result = division(num1, num2);
if (result == 0)
{
Debug.Listeners.Clear();
DefaultTraceListener _dtl = new DefaultTraceListener();
Debug.Listeners.Add(_dtl);
Debugger.Log(2, "Zero Result", string.Format("The result of {0}/{1} is zero", num1, num2));
}
}

static private int division(int num1, int num2)
{
return num1 / num2;
}
}
}

There are many other Listener classes available in .net. Best bet would be MSDN for reference.

Debug:
The Debug class has several important and useful methods to help efficient debugging. Let’s look at them.

Assert() – Pops up a message box if the assert condition fails.

static void Main(string[] args)
{
int num1 = 1;
int num2 = 2;

Debug.Assert(num1 > num2, "Num1 is less than Num2");

int result = division(num1, num2);
}

the user gets the message box as below with the message shown at the top followed by the stack trace.


Fail() – The fail method is similar to the Assert() method. Except that it does not evaluates the condition. It simply breaks at the Debug.Fail() line with the message & stack trace in the message box.

Write(), WriteIf() – Writes the output to the output window or any attached trace listener.

The only difference between Write() & WriteIf() is that WriteIf() is executed only if the specific condition is met.

Debug.Listeners.Clear();
DefaultTraceListener _dtl = new DefaultTraceListener();
_dtl.LogFileName = @"d:\logging.txt";
Debug.Listeners.Add(_dtl);
Debug.AutoFlush = true;
Debug.Write("Message from debug.write method");
Debug.WriteIf(num1 > num2, "Check the numbers");

Note, the issue with these methods is that they write the next output in the same line. To solve this problem we have Debug.WriteLine() & Debug.WriteLineIf() methods.

WriteLine(), WriteLineIf() - They do the same thing as Write() and WriteLineIf() except that they write the output to the attached listener in the new line.

Debug.Listeners.Clear();
DefaultTraceListener _dtl = new DefaultTraceListener();
_dtl.LogFileName = @"d:\logging.txt";
Debug.Listeners.Add(_dtl);
Debug.AutoFlush = true;
Debug.WriteLine("Message from debug.write method");
Debug.WriteLineIf(num1 > num2, "Check the numbers");

These are some of the useful methods you can perform good debugging. There are more useful methods available. I suggest MSDN as the best reference to research.

Also note, the above Debugger or Debug methods will work only if you run your program in the Debug mode. In release mode they act like disabled pieces. That’s the advantage of using these for debugging.

4. Debugging Attributes
Other than these powerful debugging methods, there are various debugging attributes available to ease the debugging output readability.

The attributes that are commonly used are DebuggerDiplay & DebuggerBrowsable.

I won’t get too much into details for this for the sake of brevity. Refer this like for its details MSDN

5. Trace Class
Trace is also a part of System.Diagnostics namespace. Trace class works in line with the Debug Class. Their methods are pretty much similar to that of debug class. They use TraceListeners instead of DebugListeners to print the trace output.

The only differences between Trace and Debug classes are:
Trace statements work both in Release and Debug mode whereas Debug statements works only in Debug mode.

Both trace and debug classes are used to understand the behavior of the application program. The main purpose of the trace is to understand the program flow execution whereas debug class purpose is to find out why a particular error occurs.

Happy Debugging!

Creating Windows Service - C#

Posted by Techie Cocktail | 1:36 PM | | 4 comments »

Creating a windows service is not a big deal. But as most people don’t often create windows service they tend to do some silly mistakes when they have to create one. Hence I thought of writing up a sample code demonstrating its basics.

Steps:
a. Create a new Windows Service Project. Go to File -> New -> Project and select 'Windows Service' Project template from Windows tab as shown in the figure.



b. The wizard creates for you Service1.cs by default.



c. Let’s see the default code view created by VS.



d. Now let’s add some functionality to this service. Most of the services have timers implemented in them so as to perform a particular task at regular intervals in the background. Lets add a timer and set to fire a method or an action at regular interval as set.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;

namespace MyService
{
public partial class MyFirstService : ServiceBase
{
private Timer _timer;

public MyFirstService()
{
InitializeComponent();

//instantiate the timer and set its interval to fire every one hour.
_timer = new Timer();
_timer.Interval = 3600000;

//perform the action immediately on service start.
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
}

void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
//Write a msg in a text file with the time at which the Elapsed event was raised.
WriteMsgToTextFile(string.Format("Hello: {0}", e.SignalTime.ToString()));
}

protected override void OnStart(string[] args)
{
//start the timer.
_timer.Start();
}

protected override void OnStop()
{
//stop the timer onStop
_timer.Stop();
}

private void WriteMsgToTextFile(string msg)
{
try
{
if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "msg.txt"))
{
using (StreamWriter sw = File.CreateText(AppDomain.CurrentDomain.BaseDirectory + "msg.txt"))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + msg);
sw.Close();
}
}
else using (StreamWriter sw = File.AppendText(AppDomain.CurrentDomain.BaseDirectory + "msg.txt"))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + msg);
sw.Close();
}
}
catch (Exception ex)
{
//Write Logs.
}
}
}
}


e. Now after the code is written successfully, it's time to install the service. For this you need to add the service installer to the project.

f. In the properties window as below, you would see an 'Add Installer' link at the bottom. Click on that to add the installer to your project.



g. This adds two objects 'ServiceProcessInstaller' & 'ServiceInstaller' as below.



h. Also you would have 'ProjectInstaller' files added to your Solution Explorer.



i. Installing the service: To install your windows service, go to the projects ‘bin’ directory. You will see the 'MyService' (in this case) application. Use the below command from your command line to install the service.

C:\Program Files\Microsoft Visual Studio 9.0\VC>
installutil E:\FirstService\MyService\MyService\bin\Debug\MyService.exe

This install the service successfully. You can see your service installed by going to Start -> Run -> 'Services.msc', you would see your service.



To uninstall your service, use the '/u' switch as below.
installutil /u E:\FirstService\MyService\MyService\bin\Debug\MyService.exe

Comments:
As seen in the SCM (Service Control Manager), the service appears as 'Manual'. This is because the startup type property of the ServiceInstaller was set to Manual.

Service Process Installer has 'Account' property which has values – 'LocalService', 'NetworkService', 'LocalSystem', 'User'. It indicates the account under which the service will run.

User - allows the service to impersonate a specific user whether or not that user is logged in. The account is mostly useful during development and not when installing the service in production. The problem with this account is that if the user changes their password, the services needs to be reconfigured with the new password to enable it to function.

Local System - system account with high privileges. This account is similar to Administrator account.
It provides full access to the local system's resources.

Local Service – provides a lower privilege level account. The account is ideal that requires limited or no access to the network resources.

Network Service - this account is built into windows. It provides less privilege to the local computer. The account is ideal for services that require substantial access to network resources.

Reference: MSDN