Thursday, May 20, 2010

6 steps to implement DUAL security on WCF using User name + SSL


Introduction and Goal
Basics Transport and Message level security
Step 1:- Customize ‘WsHttp’ Bindings with security mode and credential type
Step 2:- Create your custom validator class
Step 3:- Define runtime behavior
Step 4:- Define SSL for your WCF service
Step 5 :- Consume WCF Service
Step 6: Run your WCF service

Introduction and Goal

In the article we will try to apply DUAL security using transport plus message on WCF services. So we will first try to understand the basic concepts of WCF security i.e. transport and message. Once we understand the concept we will move step by step in to how to implement SSL and user name security on WCF services.
Watch my 500 videos on various topics like design patterns,WCF, WWF , WPF, LINQ ,Silverlight,UML, Sharepoint ,Azure,VSTS and lot more @ click here , you can
also view my WCF videos Part :-1 and Part:- 2
Enjoy my free ebook which covers major .NET related topics like WCF,WPF,WWF,Ajax,Core .NET,SQL Server, Architecture and lot more Download from here



Basics Transport and Message level security

On a broader basis WCF supports two kinds of security, transport level and message level security. Transport means the medium on which WCF data travels while message means the actual data packets sent by WCF. Transport medium can be protocols like TCP, HTTP, MSMQ etc. These transport mediums by themself provide security features like HTTP can have SSL security
(HTTPS). WCF has the capability of leveraging underlying transport security features on WCF service calls.

Message level security is provided in the data itself using WS-Security. In other words it’s independent of the transport protocol. Some examples of message level security are messages encrypted using encryption algorithm, messages encrypted using X509 certificate etc, messages protected using username etc.

WCF gives you an option to either just use message level security in stand alone, transport level in stand alone or combination of both. If you are interested in how to do message level security and transport security in a standalone manner you can read more from here.



The best security is the combination of transport and message. In this article we will see step by step how to implement dual security using ‘SSL’ plus message security using ‘Username’ using ‘WsHttpBinding’.

Step 1:- Customize ‘WsHttp’ Bindings with security mode and credential type

The first step is to customize your ‘Wshttp’ binding with proper security mode and credential type. There are three options in security mode ‘Transport’, ‘Message’ and ‘TransportWithMessageCredential’.

As we are implementing dual security we need to use the last one i.e. ‘TransportWithMessageCredential’ where the transport security is provided by SSL and message security is provided using ‘UserName and password’.


The second thing we need to provide is the credential type. There are five different credential type none, windows, username, certificate and issued token. Credential type defines how the credentials will be passed over the transport layer. For the current instance we will select ‘UserName’.


So summing up we will provide security mode as ‘TransportWithMessageCredential’ and message security will be provided by ‘UserName’.

So create a WCF service using the WCF service template and in ‘web.config’ provide the security mode and credential type as shown in the below code snippet.
<bindings>

<wsHttpBinding>

<binding name="Binding1">
<!-- UsernameToken over Transport Security -->

<security mode="TransportWithMessageCredential" >
<message clientCredentialType="UserName"/>

</security>

</binding>

</wsHttpBinding>

</bindings>



Step 2:- Create your custom validator class

Once we have customized the ‘WsHttp’ binding with security mode and credential type it’s time to create the custom class which will do authentication of the user name provided.

In order to create your custom class you need inherit the ‘UserNamePasswordValidator’ class which belongs to ‘System.IdentityModels.Selector’.


Below goes the code snippet of ‘MyValidator’ class. We need to override the ‘Validate’ method with the authentication logic as shown below.
class MyValidator : UserNamePasswordValidator
{

public override void Validate(string userName, string password)
{

if ((userName == "shiv123") && (password == "pass123"))
{

}
else
{
throw new FaultException("Invalid credentials");
}
}
}
If the credentials are not proper we have raised the ‘FaultException’ error which can be caught by the WCF client to display error messages.

Step 3:- Define runtime behavior


So we are almost 50% through now. We have customized the ‘WsHttp’ binding and created our custom class ‘MyValidator’ which will do the necessary authentication. The next step is to define behavior.

‘Behaviors’ define customized run time logic over the binding agreement. Currently we need to execute ‘MyValidator’ class logic for the ‘UserName’ provided in the WCF service by WCF client.


To specify the behavior go to your ‘Web.config’ file and in the ‘servicecredentials’ tag specify the ‘userNameAuthentication’ tag which points to the custom class ‘MyValidator’.
<behaviors>
<serviceBehaviors>

<serviceCredentials>

<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyValidator, app_code"/>

</serviceCredentials>
</behavior>

Step 4:- Define SSL for your WCF service


We have already mentioned transport security will be provided by SSL while message security will be provided by ‘username’. We have already configured ‘UserName’ message security using ‘MyValidator’ class which is specified in the behavior section of ‘web.config’ file. The next step is to configure SSL i.e. transport security for our WCF service.

We will be using ‘makecert.exe’ which is a free tool given by Microsoft to enable HTTPS for testing purpose. MakeCert (Makecert.exe) is a command-line tool that creates an X.509 certificate that is signed by a system test root key or by another specified key. The certificate binds a certificate name to the public part of the key pair. The certificate is saved to a file, a system certificate
store, or both.

You can get the same from “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin” or you can also get it from windows SDK.

You can type the below thing through your dos prompt on “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin”. Please note “compaq-jzp37md0” is the server name so you need to replace with your PC name.

makecert -r -pe -n "CN= compaq-jzp37md0 " -b 01/01/2000 -e 01/01/2050 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr
localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12
If you run the same through your command prompt you should get a succeeded message as shown below.

Now it’s time to assign this certificate to your IIS website. So go to IIS properties, click on directory security tab and you should see server certificate tab.


So click on the server certificate tab and you will then be walked through an IIS certificate wizard. Click ‘Assign an existing certificate’ from the wizard.

You can see a list of certificates. The “compaq-jzp37md0” certificate is the one which we just created using ‘makecert.exe’.

Now try to test the site without ‘https’ and you will get an error as shown below….That means your certificate is working.

Do not forget to enable IIS anonymous access.

We also need to make couple of changes in the WCF service ‘Web.config’ ‘endpoint’ section as shown below. You can see how the address points to HTTPS and binding uses ‘mexHttpsBinding’.
<service name="Service" behaviorConfiguration="ServiceBehavior">

<endpoint address="https://localhost/Service.svc" binding="wsHttpBinding" contract="IService" bindingConfiguration="Binding1">

<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>

</service>

Step 5 :- Consume WCF Service

It’s time to consume WCF the service application. So click on add service reference and specify your service URL. You will be shown a warning box as shown in the below figure as the certificate is a test certificate. So just let it go.


The next step is to create WCF proxy client object and pass the credentials as shown in the below snippet.
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);
ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
obj.ClientCredentials.UserName.UserName = "shiv123";
obj.ClientCredentials.UserName.Password = "pass123";
Response.Write(obj.GetData(12));
‘makecert.exe’ creates test certificates. In other words it’s not signed by CA. So we need to suppress those errors in our ASP.NET client consumer. So we have created a function called as ‘IgnoreCertificateErrorHandler’ which return true even if there are errors. This function is attached as a callback to ‘ServicePointManager.ServerCertificateValidationCallback’ as shown in the above
code snippet.
public static bool IgnoreCertificateErrorHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}


Step 6: Run your WCF service

If everything goes appropriate you should be able to run the WCF service. Try changing the use rid and password to something else you should get the fault exception message provided in the ‘MyValidtor’ class.

Tuesday, April 27, 2010

6 important .NET concepts: - Stack, heap, Value types, reference types, boxing and Unboxing.

Introduction


This article will explain 6 important concepts Stack , heap , value types , reference types , boxing and unboxing. This article starts first explaining what happens internally when you declare a variable and then it moves ahead to explain 2 important concepts stack and heap. Article then talks about reference types and value types and clarifies some of the important fundamentals around them.

Finally the article concludes by demonstrating how performance is hampered due to boxing and unboxing with a sample code.

Watch my 500 videos on various topics like design patterns,WCF, WWF , WPF, LINQ ,Silverlight,UML, Sharepoint ,Azure,VSTS and lot more
click here
, you can also catch me on my trainings @ click here.



Image taken from http://michaelbungartz.wordpress.com/

What goes inside when you declare a variable?

When you declare a variable in a .Net application, it allocates some chunk of memory in to the RAM. This memory has 3 things first the name of the variable, second data type of the variable and finally the value of the variable.

That was a simple explanation of what happens in the memory, but depending on what kind of data type your variable is allocated on that type of memory. There are two types of memory allocation stack memory and heap memory. In the coming sections we will try to understand these two types of memory in more details.

Stack and Heap

In order to understand stack and heap, let’s understand what actually happens in the below code internally.
public void Method1()
{
// Line 1
int i=4;

// Line 2
int y=2;

//Line 3
class1 cls1 = new class1();
}


It’s a 3 line code so let’s understand line by line how things execute internally.
Line 1:- When this line is executed compiler allocates a small amount of memory in to memory type called as stack. Stack is responsible of keeping track of running memory needed in your application.

Line 2:- Now the execution moves to the next step. As the name says stack it stacks this memory allocation on the top of the first memory allocation. You can think about stack as series of compartment or boxes put on top of each other.
Memory allocation and de-allocation is done using LIFO (Last in first out) logic. In other words memory is allocated and de-allocated at only one end of the memory i.e. top of the stack.

Line 3:- In line 3 we have a created an object. When this line is executed it creates a pointer on the stack and the actual object is stored in a different type of memory location called as ‘Heap’. ‘Heap’ does not track
running memory it’s just pile of objects which can reached at any moment of time. Heap is used for dynamic memory allocation.

One more important point to note here is reference pointers are allocated on stack. The statement, Class1 cls1; does not allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it to null). The time it hits the new keyword it allocates on "HEAP".
Exiting the method (The fun):- Now finally the execution control starts exiting the method. When it passes the end control it clears all the memory variables which are assigned on stack. In other words all variables which are related to ‘int’ data type are de-allocated in ‘LIFO’ fashion from the stack.
The BIG catch – It did not de-allocate the heap memory. This memory will be later de-allocated by “GARBAGE COLLECTOR”.


Now many of our developer friends must be wondering why two types of memory, can’t we just allocate everything on just one memory type and we are done.
If you look closely primitive data types are not complex, they hold single
values like ‘int i = 0’. Object data types are complex, they reference other
objects or other primitive data types. In other words they hold reference to other multiple values and each one of them must be stored in memory. Object types need dynamic memory while primitive needs static type memory. If the requirement is of dynamic memory it’s allocated on a heap or else it goes on a stack.
Image taken from http://michaelbungartz.wordpress.com/


Value types and reference types

Now that we have understood the concept of ‘Stack’ and ‘Heap’ it’s time to understand the concept of value types and reference types.
Value types are types which hold both data and the memory on the same location. While a reference type has a pointer which points to the memory location.
Below is a simple integer data type with name ‘i’ whose value is assigned to an other integer data type with name ‘j’. Both these memory values are allocated on the stack.
When we assign the ‘int’ value to the other ‘int’ value it creates a complete different copy. In other word if you change either of them the other does not change. These kinds of data types are called as ‘Value types’.



When we create an object and when we assign one object to the other object, they both point to the same memory location as show in the below code snippet. So when we assign ‘obj’ to ‘obj1’ they both point to the same memory location.
In other words if we change one of them the other object is also affected this is termed as ‘Reference types’.


So which data types are ref type and value type?

In .NET depending on data types the variable is either assigned on the stack or on the heap. ‘String’ and ‘Objects’ are reference types and any other .NET primitive data types are assigned on the stack. Below figure explains the same in a more detail manner.


Boxing and Unboxing

WOW, you have given so much knowledge, so what’s the use of it in actual
programming. One of the biggest implications is to understand the performance hit which is incurred due to data moving from stack to heap and vice versa.
Consider the below code snippet. When we move a value type to reference type the data is moved from the stack to the heap. When we move reference type to a value type the data is moved from the heap to the stack.
This movement of data from the heap to stack and vice-versa creates a
performance hit.

When the data moves from value types to reference types its termed as ‘Boxing’ and the vice versa is termed as ‘UnBoxing’.



If you compile the above code and see the same in ILDASM you can see in the IL code how ‘boxing’ and ‘unboxing’ looks, below figure demonstrates the same.


Performance implication of Boxing and unboxing

In order to see how the performance is impacted we ran the below two
functions 10,000 times. One function has boxing and the other function is simple. We used a stop watch object to monitor the time taken.
The boxing function was executed in 3542 MS while without boxing the code was executed in 2477 MS. In other words try to avoid boxing and unboxing. In project you always need boxing and unboxing , use it when it’s absolutely necessary.
With the same article the sample code is attached which demonstrates this performance implication.



Currently I have not put a source code for unboxing but the same hold true for the same. You can write the same and experiment it by using stopwatch class.

Saturday, April 17, 2010

ASP.NET application and page life cycle
Introduction
In this article we will try to understand what are the different events which takes place right from the time the user sends a request, until the time request is rendered on the browser. So we will first try to understand the two broader steps of an ASP.NET request and then we will move in to different events emitted from ‘HttpHandler’, ‘HttpModule’ and ASP.NET page object. As we move in this event journey we will try to understand what kind of
logic should go in each every of these events.

This is a small E-book for all my .NET friends which covers topics like WCF, WPF, WWF, Ajax, Core .NET, SQL etc you can download the same from http://tinyurl.com/4nvp9t or else you can catch me on my daily free training @ http://tinyurl.com/y4mbsn6

The Two step process

From 30,000 feet level ASP.NET request processing is a 2 step process as shown below. User sends a request to the IIS:-
• ASP.NET creates an environment which can process the request. In other words it creates the application object, request, response and context objects to process the request.

• Once the environment is created the request is processed through series of events which is processed by using modules, handlers and page objects. To keep it short lets name this step as MHPM (Module, handler, page and Module event), we will come to details later.



In the coming sections we will understand both these main steps in more details.Creation of ASP.NET environment
Step 1:- The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance if the page is an ‘.ASPX page’ then it will be passed to ‘aspnet_isapi.dll’ for processing.
Step 2:- If this the first request to the website then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know application domain creates isolation between two web applications hosted on the same IIS. So in case there is issue in one app domain it does not affect the other app domain.
Step 3:- The newly created application domain creates hosting environment i.e. the ‘HttpRuntime’ object. Once the hosting environment is created necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.
Step 4:- Once all the core ASP.NET objects are created ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system then object of the ‘global.asax’ file will be created. Please note
‘global.asax’ file inherits from ‘HttpApplication’ class.
Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, ‘HttpApplication’ instances might be reused for multiple requests.Step 5:- The ‘HttpApplication’ object is then assigned to the core ASP.NET objects to process the page.
Step 6:- ‘HttpApplication’ then starts processing the request by http module events , handlers and page events. It fires the MHPM event for request processing.
Note: - For more details



http://msdn.microsoft.com/en-us/library/ms178473.aspx




Below image explains how the internal object model looks like for an ASP.NET request. At the top level is the ASP.NET runtime which has creates an ‘Appdomain’ which in turn has ‘HttpRuntime’ with ‘request’, ‘response’ and ‘context’ objects.



Process request using MHPM events fired


Once ‘HttpApplication’ is created it starts processing request it goes through 3 different sections ‘HttpModule’ , ‘Page’ and ‘HttpHandler’. As it moves through these sections it invokes different events which the developer can extend and add customize logic to the same.Before we move ahead lets understand what are ‘HttpModule’ and ‘HttpHandlers’. They help us to inject custom logic before and after the ASP.NET page is processed. The main differences between both of them are:-
• If you want to inject logic based in file extensions like ‘.ASPX’ , ‘.HTML’ then you use ‘HttpHandler’. In other words ‘HttpHandler’ is an extension based processor.



• If you want to inject logic in the events of ASP.NET pipleline then you use ‘HttpModule’. ASP.NET . In other word ‘HttpModule’ is an event based processor.




You can read more about the differences from http://tinyurl.com/yyfuc9r
Below is the logical flow of how the request is processed. There are 4 important steps MHPM as explained below :-
Step 1(M à HttpModule):- Client request processing starts. Before the ASP.NET engine goes and creates the ASP.NET ‘HttpModule’ emits events which can be used to inject customized logic. There are 6 important events which you can utilize before your page object is created ‘BeginRequest’,’AuthenticateRequest’,’AuthorizeRequest’,’ResolveRequestCache’,’AcquireRequestState’
and ‘PreRequestHandlerExecute’.
Step 2 (H à ‘HttpHandler’ ) :- Once the above 6 events are fired , ASP.NET engine will invoke ‘ProcessRequest’ event if you have implemented ‘HttpHandler’ in your project.
Step 3 (P – ASP.NET page):- Once the ‘HttpHandler’ logic executes the ASP.NET page object is created. While the ASP.NET page object is created many events are fired which can help us to write our custom logic inside those page events. There are 6 important events which provides us placeholder to write
logic inside ASP.NET pages ‘Init’ , ‘Load’ , ‘validate’ , ‘event’ , ‘render’ and ‘unload’. You can remember the word ‘SILVER’ to remember the events S – Start ( does not signify anything as such just forms the word ) , I – (Init) , L ( Load) , V ( Validate) , E ( Event) and R ( Render).
Step4 (M à HttpModule):- Once the page object is executed and unloaded from memory ‘HttpModule’ provides post page execution events which can be used to inject custom post-processing logic. There are 4 important post-processing events ‘PostRequestHandlerExecute’, ‘ReleaserequestState’, ‘UpdateRequestCache’ and ‘EndRequest’.
Below figure shows the same in a pictorial format.



In What event we should do what?
The million dollar question is in which events we should do what? . Below is the table which shows in which event what kind of logic or code can go.




A sample code for demonstration
With this article we have attached a sample code which shows how the events actually fire. In this code we have created a ‘HttpModule’ and ‘Httphandler’ in this project and we have displayed a simple response write in all events , below is how the output looks like.Below is the class for ‘HttpModule’ which tracks all event s and adds it to a
global collection.



public class clsHttpModule : IHttpModule

{

......

void OnUpdateRequestCache(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnUpdateRequestCache");

}

void OnReleaseRequestState(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnReleaseRequestState");

}

void OnPostRequestHandlerExecute(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnPostRequestHandlerExecute");

}

void OnPreRequestHandlerExecute(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnPreRequestHandlerExecute");

}

void OnAcquireRequestState(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnAcquireRequestState");

}

void OnResolveRequestCache(object sender, EventArgs a)

{

objArrayList.Add("httpModule:OnResolveRequestCache");

}

void OnAuthorization(object sender, EventArgs a)

{
objArrayList.Add("httpModule:OnAuthorization");

}

void OnAuthentication(object sender, EventArgs a)

{


objArrayList.Add("httpModule:AuthenticateRequest");
}

void OnBeginrequest(object sender, EventArgs a)

{


objArrayList.Add("httpModule:BeginRequest");

}

void OnEndRequest(object sender, EventArgs a)

{

objArrayList.Add("httpModule:EndRequest");

objArrayList.Add("<hr>");

foreach (string str in objArrayList)

{
httpApp.Context.Response.Write(str + "<br>") ;

}

}

} 

Below is the code snippet for ‘HttpHandler’ which tracks ‘ProcessRequest’ event.
public class clsHttpHandler : IHttpHandler

{

public void ProcessRequest(HttpContext context)

{

clsHttpModule.objArrayList.Add("HttpHandler:ProcessRequest");

context.Response.Redirect("Default.aspx");

}
}


We are also tracking all the events from the ASP.NET page.
public partial class _Default : System.Web.UI.Page 
{
protected void Page_init(object sender, EventArgs e)
{

clsHttpModule.objArrayList.Add("Page:Init");
}
protected void Page_Load(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:Load");
}
public override void Validate()
{
clsHttpModule.objArrayList.Add("Page:Validate");
}
protected void Button1_Click(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:Event");
}
protected override void Render(HtmlTextWriter output)
{
clsHttpModule.objArrayList.Add("Page:Render");
base.Render(output);
}
protected void Page_Unload(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:UnLoad");
}}
Below is how the display looks like with all events as per the sequence discussed in the previous section.

Zooming ASP.NET page events

In the above section we have seen the overall flow of events for an ASP.NET page request. One of the most important section is the ASP.NET page, we have not discussed the same in detail. So let’s take some luxury to describe the ASP.NET page events in more detail in this section. Any ASP.NET page has 2 parts one is the page which is displayed on the browser which has HTML tags , hidden values in form of viewstate and data on the HTML inputs. When the page is posted these HTML tags are created in to ASP.NET controls with viewstate and form data tied up together on the server. Once you get these full server controls on the behind code you can execute and write your own login on the same and render the page back to the browser.
Now between these HTML controls coming live on the server as ASP.NET controls, the ASP.NET page emits out lot of events which can be consumed to inject logic. Depending on what task / logic you want to performwe need to put these logics appropriately in those events.
Note: - Most of the developers directly use the ‘page_load’ method for everything, which is not a good thought. So it’s either populating the controls, setting view state, applying themes etc everything happens on the page load. So if we can put logic in proper events as per the nature of the logic that would really make your code clean.

References

I am not so smart to write this article by myself ;-) , lot of things I have plugged from the below articles. Intercepting filters:-http://msdn.microsoft.com/en-us/library/ms998536.aspx Explains how to implement Httphandlers and modules:- http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx Httphandlers and Httpmodules :-http://www.15seconds.com/Issue/020417.htm Implementing security using modules and handlers :-http://joel.net/articles/asp.net2_security.aspx Difference between Httpapplication and global.asax :-http://codebetter.com/blogs/karlseguin/archive/2006/06/12/146356.aspx

Wednesday, March 24, 2010

Detecting Refresh or Post back in ASP.NET

Detecting Refresh or Post back in ASP.NET

The problem


There are situations where we would like to detect if the post back is from a form interaction (i.e. submit or button clicks) or is it by hitting the browser F5 refresh button. Many of them will jump saying how about checking ‘Ispostback’ value. ‘IsPostback’ will always have the value which was set previously. So for instance if the page was posted back before refresh, then the value will be true and if the page is not posted back before refresh, then the value will be false.This article will first explain the fundamentals of how to solve the above problem and later this article will go in depth of how the source code looks like.Please feel free to download my free 500 question and answer eBook which covers .NET , ASP.NET , SQL Server, WCF , WPF , WWF , Silver light , Azure @ http://tinyurl.com/4nvp9t

Reference

The solution which this article proposes first came in an ASP.NET book written by Dino Esposito and it was taken further by Mr. SimoneB to make a small open source code which you can get from http://sourceforge.net/projects/busybox. A brief explanation is also provided at this link.
http://dotnetslackers.com/Community/blogs/simoneb/archive/2007/01/07/Using-an-HttpModule-to-detect-page-refresh.aspx

The article will go step by step to explain the ideas proposed by Mr. Dino Esposito in a simplified manner.

The fundamental





• Step 1 :- We have created a javascript which will generate unique fresh GUID in submit button click. This GUID will be stored in the HttpContext object.
• Step 2 ( User presses submit click ) :- If user presses submit button it will call the necessary javascript function to create the new fresh GUID again.
• Step 3 :- In ‘HttpHandler’ or ‘HttpModule’ the new GUID value is checked with the old GUID value. If the values are not equal then it means this was not called from a submit click and it’s a refresh event. Accordingly the HttpContext session value is set.
• Step 4 :- In the page load we can then check if this was a refresh or post back using the session variables.

3 important parts of the code

There are 3 important part of the code to be understood :-
• Javascript which generates the unique GUID.
• HtppHandler which checks if the old value is equal to the new value.
• ASP.NET page which finally checks if it’s a refresh or postback and handles logic accordingly.




Javascript code

So first lets start with the javascript code. The ‘genereateRandomSequence’ function generates unique GUID by using ‘math’ functions like ‘random’ and ‘floor’.The ‘onPostBack’function calls ‘generateRandomSequence’ function to generate GUID and attach the same to a hidden field with name ‘hdnGuid’. This hidden field is generated on fly in the ‘HttpHandler’ module which will be explained shortly. Below is the code snippet for the same.

function onPostBack()
{
var y=generateRandomSequence();
var hdnGuid=document.getElementById("hdnGuid");
hdnGuid.value=y;
}
function generateRandomSequence()
{
var g = "";
for(var i = 0; i < 32; i++)
g += Math.floor(Math.random() * 0xF).toString(0xF)
return g;
}


The above javascript function is referred in a JS files and called on the button submit click as shown in the below HTML code
snippet.

<title>Untitled Page</title>
<script type="text/javascript" language="javascript" src="Client-Side_Validn.js"></script>
</script>
</head>
<body>
<form id="form1" runat="server" onsubmit="onPostBack()">
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>


HttpModule code


The next important code is the ‘HttpModule’ code. As a first step let’s create a simple GUID class which help us store the GUID values as shown in the below figure.
public class GuidClass
{
private string guid;
public string Guid
{
get
{
return guid;
}
set
{
guid = value;
}
}
}


The next step is to create a simple ‘HttpModule’ class which overrides the ‘page_Init’ event and the ‘page_Load’
event. In the ‘page_Init’ event we have created a simple hidden field by name ‘hdnGuid’ which is attached to the page on the first hit itself.


void _page_Init(object sender, EventArgs e)
{
HiddenField hdnGuid = new HiddenField();
hdnGuid.ID = "hdnGuid";
if (!_page.IsPostBack)
hdnGuid.Value = Guid.NewGuid().ToString();
_page.Form.Controls.Add(hdnGuid);
}


In the ‘page_Load’ event we check if the hidden field value is same as the old value. In case the value is not same that means
it’s a ‘postback’ and if the value is same then its ‘refresh’. As per situation we set the ‘httpContent.Items[“Refresh”]’ value.

void _page_Load(object sender, EventArgs e)
{
HiddenField h1 = (HiddenField)(_page.Form.FindControl("hdnGuid"));
GuidClass currentGuid =new GuidClass();
currentGuid.Guid= h1.Value;
System.Web.HttpContext _httpContext = System.Web.HttpContext.Current;
if (temp.Contains<string>(currentGuid.Guid))
{
_httpContext.Items.Add("IsRefresh",true);
}
else
{
if(!(currentGuid.Guid.Equals(null)currentGuid.Guid.Equals("")))
temp.Enqueue(currentGuid.Guid);
_httpContext.Items.Add("IsRefresh",false);
}
}


We also need to ensure that the handler is registered in the ‘httpModules’ tag.
<httpModules>
<add name="Myhandler" type="Myhandler"/>
</httpModules>

ASP.NET page code

The final part is to detect in the ASP.NET page whether it’s a ‘refresh’ or ‘postback’. The below code demostrates how ‘HttpContext’ session can be referred to check the same and act accordingly.
if ((bool)HttpContext.Current.Items["IsRefresh"])
{
Response.Write("refreshed");
}
else
{
Response.Write("Postback");
}

Thursday, March 18, 2010

Introduction


This article will compare four important architecture presentation patterns i.e. MVP(SC),MVP(PV),PM,MVVM and MVC. Many developers are confused around what is the difference between these patterns and when should we use what. This article will first kick start with a background and explain different types of presentation patterns. We will then move ahead discussing about the state , logic and synchronization issues. Finally we will go in detail of each pattern and conclude how they differ from each other
Here’s my small gift for all my .NET friends , a complete 400 pages FAQ Ebook which covers various .NET technologies like Azure , WCF , WWF , Silverlight , WPF , SharePoint and lot more from here.

Special thanks


This whole article is abstract from http://martinfowler.com/eaaDev/uiArchs.html GUI architectures. Great work by Mr. Martin flower.
Josh Smith and team http://msdn.microsoft.com/en-us/magazine/dd419663.aspx , great work on MVVM.
Mr. Nikhil kothari's blog http://www.nikhilk.net/Silverlight-ViewModel-Pattern.aspx , awesome source for MVVM.

Background - Presentation patterns


One of the biggest problems associated with user interface is lot of cluttered code. This cluttered code is due to two primary reasons , first the UI has complicated logic to manipulate the user interface objects and second it also maintains state of the application. Presentation patterns revolve around how to remove the UI complication and make the UI more clean and manageable. Below are different variety and classifications of presentation patterns as shown in the below figure.



Presentation pattern are divided in to three important categories MVP ( Model view presenter ) , MVC ( Model view controller) and finally (PM) presenter model. MVP is further divided in to supervising controller and passive view. Presenter model is further divided by Microsoft team in two technology specific patterns MVVM for silverlight and MVVM for WPF.


3 big problems of UI :- State , Logic and Synchronization


There are 3 big problems associated with UI as listed below.
State :- State / data is one of the biggest concern in UI. State means the current data picture of your user interface. In web terminologies it can be session variable and in windows application it can be a simple UI level data. The more the UI maintains states ,the more complication is increased.
Logic :- User interface normally have UI logics like manipulating textboxes , combo boxes or any other UI elements.The more these kind of logic exists in the UI the more it becomes complex.
Synchronization :- User interfaces normally co-ordinate with domain / business components. UI also needs to synchronize data between UI elements ( textboxes , comboboxes etc) and business objects. If your UI is taking of synchronization again the UI complexity increases.




The Hero - Presentation design Pattern


Presentation design pattern helps to solve the above UI problems. The base logic of presentation design patterns is that we need to create a extra class which will consume complicated logic , data and synch issues which currently the UI does , thus making the UI dump , clean and simple. Depending on how much this class takes responsibilities defines further whether its a SC , PV , PM design pattern etc. In other words its the maturity of the presenter class which will define what kind of design pattern it is.



Some acronyms to simplify the article



AcronymFull form
VView or user Interface.
PPresenter class which has the UI logic.
LUI logic
SState of the UI
MBusiness components or domain objects.
SCSupervising controller .
PVPassive view.
PMPresenter model.
We will use the above acronym to simplify our explanation of presentation design pattern.

Supervising controller pattern ( SC )

Fundamentals about SC :-

  • State is stored in the view.

  • Presenter owns the complex presentation logic. Simple UI binding logic is taken care by using binding technologies like WPF binding and Silverlight binding. Anything complex is taken care presenter class.

  • Presenter is aware of the view.

  • View is not aware of the presenter.

  • View connects with model using technical bindings provided by WPF and Silverlight.


Passive view (PV)

Fundamentals about PV :-
  • State is stored in the view.

  • All logic of UI is stored in presenter.

  • View is completely isolated from the model. It also takes the extra task of synchronizing data between model and view.

  • Presenter is aware of the view.

  • View is not aware of the presenter.
You can read more about MVP (PV) from this link




Presentation Model (PM)

Fundamentals about SC :-

  • State is stored in the presenter.

  • Logic is stored in presenter.

  • Presenter represents a abstract view of the UI.

  • Presenter is not aware of the view.

  • View is aware of the presenter.

  • View is completely isolated from the model.



MVVM

Fundamentals about SC :-
  • Presenter model is the base.

  • State is stored in the presenter.

  • Logic is stored in presenter.

  • Presenter represents an abstract view of the UI.

  • Presenter is not aware of the view.

  • View is aware of the presenter.

  • View is completely isolated from the model.

  • Uses WPF and Silverlight bindings.



MVC

Fundamentals about MVC :-

  • Does not have a presenter , has a controller.

  • Request first comes to the controller.

  • Controller binds the model with the view.

  • Logic is stored in the controller.
You can read more about MVC from this link






Summarizing

Below is a summary comparison table for all presentation patterns from the aspect of state , logic and synchronization.


StateLogicSynchronization
Supervising controller




Presenter
XX

ViewX


ModelView connects to model for data using databindings like WPF bindings , Silverlight bindings etc.
Passive View




Presenter
XX

ViewX

Presenter model




PresenterXX

View

X
MVVM




PresenterXX

View

X

Databinding commands of WPF , Silverlight , ASP.NET is used.
MVCController
XX

ViewX

Below is a visual comparison of what we discussed above.

Sunday, March 14, 2010

4 steps to enable instrumentation in WCF

4 steps to enable instrumentation in WCF

Introduction and Goal

Many times we would like to monitor events of WCF application in production environment. We would like to monitor events like errors, security audits, performance etc. This can be achieved by extending the ASP.NET health monitoring system in WCF. The health monitoring system is also termed as instrumentation.
Here’s my small gift for all my .NET friends , a complete 400 pages FAQ Ebook which covers various .NET technologies like Azure , WCF , WWF , Silverlight , WPF , SharePoint and lot more http://tinyurl.com/4nvp9t

The event provider model

Instrumentation is provided using the event provider model. Events are notification which you receive from the WCF application which can be a security event like password change, UI click events, or exception events like application level errors. These events are captured by the provider and routed to some source like event viewer, SQL Server etc.



Both events and provider are specified in the ‘web.config’ file. The ‘eventmapping’ element is where you specify your provider and ‘rules’ elements helps you tie up the event with the provider.
<healthMonitoring>
<eventMappings>...</eventMappings>
<rules>...</rules>
</healthMonitoring>
What will we do in this article?
In this article we will create a simple audit function which will help us to track all calls made to the WCF service in to event viewer. So any calls by the
WCF client will be tracked and audited in to the event viewer. For every call we will be tracking details like number of threads, working sets, app domains, when
the message was created and when was it raised. Below is the snippet for the same which will be tracked in the event viewer.



***************start health monitoring event*******************
message created at:Event Created at :3/14/2010 11:32:37 AM
message raised at:Event Created at :3/14/2010 11:32:37 AM
Heap size 3480664
Number of threads 19
Number of Working sets 32165888
Number of domains 1
Request rejected 0******************End Health Monitoring event*********************

Step1: Create the main event class
The first step is to create a class which will help us to track the calls made to the WCF service. This class needs to be inherited from ‘WebAuditEvent’ class. This class helps us to track audit events, generate information about security related operation and provide both success and failure audit events.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Management;
namespace healthmonitering
{
public class CustomAudit:WebAuditEvent
{
}
}

In the same class lets add 3 private fields ,’ msgcreated’ , ‘ msgraised’ and ‘WebProcessStatistics’. By using ’ msgcreated’ and ‘ msgraised’ we can track at what time event is
created and raised. ‘WebProcessStatistics’ will provide information for assessing the health of a running process.
private string msgcreated = string.Empty;
private string msgraised = string.Empty;
private static WebProcessStatistics processStatistics;


Implement the necesarry public constructors that call the protected equivalents in the parent WebAuditEvent class.Base keyword is used to access the member of
base class within the derived class as shown in the below code snippet. Note we have created the ‘WebProcessStatistics’ object and set it to the private member
variable.


public CustomAudit(string message, object eventsource, int eventcode)
: base(message, eventsource, eventcode)
{
msgcreated = string.Format("Event Created at :{0}", EventTime.ToString());
processStatistics = new WebProcessStatistics();
}

In both the constructors we are checking at what time event is created. Now override the Raise method as shown in the below code snippet.
public override void Raise()
{
msgraised = string.Format("Event Created at :{0}", EventTime.ToString());
base.Raise();
}

Override the ‘FormatCustomEventDetails’ method with the message we want to log in the eventviewer. Note, we have used ‘WebProcessStatistics’ to get information like Heap size,Number of threads,Number of Working sets,Number of domains and Request rejected.

public override void FormatCustomEventDetails(WebEventFormatter formatter)
{
formatter.AppendLine("");
formatter.IndentationLevel += 1;
formatter.AppendLine("***************start health monitoring event*******************");
formatter.AppendLine(string.Format("message created at:{0}",msgcreated));
formatter.AppendLine(string.Format("message raised at:{0}", msgraised));
formatter.AppendLine(string.Format("Heap size {0}", processStatistics.ManagedHeapSize.ToString()));
formatter.AppendLine(string.Format("Number of threads {0}", processStatistics.ThreadCount.ToString()));
formatter.AppendLine(string.Format("Number of Working sets {0}", processStatistics.WorkingSet.ToString()));
formatter.AppendLine(string.Format("Number of domains {0}", processStatistics.AppDomainCount.ToString()));
formatter.AppendLine(string.Format("Request rejected {0}", processStatistics.RequestsRejected.ToString())); ;
formatter.AppendLine("******************End Health Monitoring event*********************");
formatter.IndentationLevel -= 1;
}

In the Raise method, we are checking at what time event raised and in ‘FormatCustomEventDetails’ we are appending the result in the audit event.
Step2:- Create the WCF service and change web.config

namespace WcfService3
{
[ServiceContract]
public interface IService1
{
[OperationContract]
string Audit();
}
}


In the ‘Audit’ function We are going to implement our health monitering functionality in health operation contract.
In the Service1.svc.cs class implement the ‘Audit’ function by creating the ‘CustomAudit’ object and calling the ‘Raise’ function as shown in the below code snippet.

public class Service1 : IService1
{
public string Audit()
{
Healthmonitering.CustomAudit webevent = new Healthmonitering.CustomAudit("Some on called", this, WebEventCodes.WebExtendedBase + 1);
webevent.Raise();
return "Event Audited";
}
}


In the constructor we are sending message, eventsource and event code as a parameter.
Now go to the ‘web.config’ and under ‘system.web’ element and add the ‘healthmonitoring’ tag.
Specify ‘CustomAudit’ class in the ‘eventMappinga’ element and mapping of the class with event viewer in the ‘rules’ element tag as shown in the below code snippet.

<healthMonitoring>
<eventMappings>

<add name="healthmonitering" type="Healthmonitering.CustomAudit "/>
</eventMappings>
<rules>
<add name="healthmonitering" eventName="healthmonitering" provider="EventLogProvider" minInterval="00:00:01"/>

</rules>
</healthMonitoring>



Step 3 :- Consume the WCF service in the ASPX client.


So let’s add a ASPX button, consume the client service and call the ‘Audit’ function in the button click event as shown in below code snippets.
<asp:Button ID="Button1" runat="server" Text="Invoke" onclick="Button1_Click" />

Now in the button click event write these lines

protected void Button1_Click(object sender, EventArgs e)
{
ServiceReference1.Service1Client proxy = new WebApplication1.ServiceReference1.Service1Client();
string result = proxy.Audit();
Response.Write(result);
}

Here we are creating the proxy,invoking the ‘audit’ method and displaying the result of the ‘audit’ method.

Step 4 :- See the audit data in Eventviewer

Run the web application which is consuming the WCF service and press the button to invoke the WCF audit function.
The ‘Audit’ function internally calls the ‘Raise’ event which logs the message in an event viewer. So go to Start->run->type eventvwr.It contains information like Heap size,Number of threads,Number of Working sets,Number of domains and Request rejected as shown in the below figure.

Saturday, February 20, 2010

4 steps to consume web services using Ajax (Includes Video tutorial)

Introduction and Goal

In this article we will try to understand the 4 important steps to consume web service directly in Ajax. In this sample we will create a simple customer combo box as shown in the figure below. This customer combo box will be filled by calling the web service methods directly of the customer web service.

Here’s my small gift for all my .NET friends , a complete 400 pages FAQ Ebook which covers various .NET technologies like Azure , WCF , WWF , Silverlight , WPF , SharePoint and lot more
http://www.questpond.com/SampleDotNetInterviewQuestionBook.zip

Video tutorial

This whole article is also demonstrated in video format which you can view from here http://www.youtube.com/watch?v=FvpXZdRTr4Q .
Introduction
Normally consumption of web services happens as shown in the below figure. The browser Ajax controls calls the ASP.NET code and the ASP.NET code consumes the web service. But there are scenarios where you would like to call the web services directly from the ajax javascript functions
rather than calling via the behind code. This article will demonstrate how we can achieve the same.



Step 1 Create your customer class

The first step is to create the customer class as shown below. So our customer class has 4 properties on customer id, first name, address and designation.
public class Customers
{
// private properties
private int _intCustomerID;
private string _strFirstName;
private string _strAddress;
private string _strDesignation;

// Public property and
public int CustomerID
{
get
{
return _intCustomerID;
}
set
{
_intCustomerID = value;
}
}

public string FirstName
{
get
{
return _strFirstName;
}
set
{
_strFirstName = value;
}
}

Step 2:- Create your web service

The next step is we need to create the web service which exposes the customer class to our UI. Below is a simple web service which has encapsulated customer collection. In the constructor we are loading some dummy data in to the list of customer as shown in the below code snippet.[System.Web.Script.Services.ScriptService]

public class Customer : System.Web.Services.WebService {

// Customer collection
List<Customers> listcust = new List<Customers>();
public Customer ()
{
//Load some dummy data in to customer collection.
listcust.Clear();
Customers cust = new Customers();
cust.CustomerID = 1;
cust.FirstName = "Taha";
cust.Address = "Live in India";
cust.Designation = "Software Developer";
listcust.Add(cust);
cust = new Customers();
cust.CustomerID = 2;
cust.FirstName = "Shyam";
cust.Address = "Live in Austrailia";
cust.Designation = "Web Designer";
listcust.Add(cust);
cust = new Customers();
cust.CustomerID = 3;
cust.FirstName = "Khadak";
cust.Address = "Live in London";
cust.Designation = "Architect";
listcust.Add(cust);
}
// This function exposes all customers to the end client’
[WebMethod]
public List<Customers> LoadCustomers()
{
return listcust;
}
// This function helps us to get customer object based in ID
[WebMethod]
public Customers LoadSingleCustomers(int _customerid)
{
return (Customers)listcust[_customerid-1];
}

We are also exposing two functions through the web service one which give out a list of customers and other which gives out individual customer data based in customer id.

Step 3:- Reference your web service using the asp:servicereference

Using the ‘asp:ServiceReference’ we will then point the path to the ASMX file as shown in the below code snippet. This will generate the JavaScript proxy which can be used to call the customer object.
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="Customer.asmx" />
</Services>
</asp:ScriptManager>

Step 4:- Call the webservice and the javascript code

Once you have defined the proxy you can now call the ‘Customer’ proxy directly to make method calls.function LoadAll()
{
Customer.LoadCustomers(LoadCustomerToSelectOption, ErrorHandler, TimeOutHandler);
}

When you call the JavaScript proxy object we need to provide three functions the first function (‘LoadCustomerToSelectOption’) will be called on the web service finishes and returns data. The data will be returned in the fill variable which will then be looped and added to the customer combo box.

function LoadCustomerToSelectOption(Fill)
{
var select = document.getElementById("cmbCustomers");
for (var i = 0; i < Fill.length; i++)
{
var value = new Option(Fill[i].FirstName, Fill[i].CustomerID);
select.options.add(value);
}
}

There are two more functions which are attached one which handles error and the other which handles time out. Below are the code
snippets for the same.
function ErrorHandler(result)
{
var msg = result.get_exceptionType() + "\r\n";
msg += result.get_message() + "\r\n";
msg += result.get_stackTrace();
alert(msg);
}
function TimeOutHandler(result)
{
alert("Timeout :" + result);
}