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);
}

Wednesday, February 10, 2010

7 simple steps to run your first Azure Queue program

7 simple steps to run your first Azure Queue program


Introduction


Azure queues help to communicate data between web role and worker role. Web roles are nothing but web application which can be accessed by the end browser. Worker roles are back ground processes which run in the azure system and they do not take direct request from the web.
So if we want to pass data to worker roles we need to use Queues. Queues are temporary storage which acts like a bridge between web role and worker role. So you can post data to web role , web role posts data to queues and worker role picks the data from queues to do further processing.
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 .


What will we do in this article?

In this article we will create a simple application which will allow us to enter customer feedbacks. These customer feedback messages will go through a quality check whether the messages have any kind spam keywords. Currently we will only check for “XXX”.



In other words the above web role will submit the feedback message to queues, worker role will pick up the message, does a quality check and if the quality check passes it will add it to the Azure table. In case you are new to how to create an Azure table please read here http://computerauthor.blogspot.com/2010/01/9-simple-steps-to-run-your-first-azure.html

Step 1:- Ensure you have things at place

In case you are a complete fresher to Azure, please ensure you have all the pre-requisite at place. You can read the below article to get the basic prerequisite http://computerauthor.blogspot.com/2010/01/9-simple-steps-to-run-your-first-azure.html

Step 2:- Create a web role and worker project


The next step is to select the cloud service template, add the web role project and create your solution.


Step 3:- Configure service definition and configuration files.

The next step is to define table storage and queue storage location in the service definition and configuration. Just to revise service definition files help your define the configuration name while service configuration actually set the value.
Below is how the service definition file looks like , we need to the account name , shared key , queue storage and table storage end point. We need to define both these definition both for worker role as well as web role.
We are not sure if there is a way to avoid this redudancy. We googled and found that we indeed to define different definition even if the names are same , below is one of the links which talks about the same http://bstineman.spaces.live.com/Blog/cns!61AEA8168D26EA6B!291.entry


<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="QueueStorage" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">
<WebRole name="WebRole1" enableNativeCodeExecution="false">
<InputEndpoints>
<!-- Must use port 80 for http and port 443 for https when running in the cloud -->
<InputEndpoint name="HttpIn" protocol="http" port="80" />
</InputEndpoints>
<ConfigurationSettings>
<Setting name="AccountName" />
<Setting name="AccountSharedKey" />
<Setting name="QueueStorageEndpoint" />
<Setting name="TableStorageEndpoint" />
</ConfigurationSettings>
</WebRole>
<WorkerRole name="WorkerRole1" enableNativeCodeExecution="false">
<ConfigurationSettings>
<Setting name="AccountName" />
<Setting name="AccountSharedKey" />
<Setting name="QueueStorageEndpoint" />
<Setting name="TableStorageEndpoint" />
</ConfigurationSettings>
</WorkerRole>
</ServiceDefinition>


Once you have defined the definitions its time to define the configuration values for this definitions.Below is the service
configuration file which has the values for all the 4 definitions defined in the definition file. You can see that the end point for both storage and queues are defined using a URL , in other words these storages are exposed through REST services.
Currently all the 4 configurations point to the local development storage , these values will change when you want to host online on the actual azure platform.

<?xml version="1.0"?>
<ServiceConfiguration serviceName="QueueStorage" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration">
<Role name="WebRole1">
<Instances count="1" />
<ConfigurationSettings>
<Setting name="AccountName" value="devstoreaccount1" />
<Setting name="AccountSharedKey"
value="Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" />
<Setting name="QueueStorageEndpoint" value="http://127.0.0.1:10001" />
<Setting name="TableStorageEndpoint" value="http://127.0.0.1:10002" />
</ConfigurationSettings>
</Role>
<Role name="WorkerRole1">
<Instances count="1" />
<ConfigurationSettings>
<Setting name="AccountName" value="devstoreaccount1" />
<Setting name="AccountSharedKey"
value="Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" />
<Setting name="QueueStorageEndpoint" value="http://127.0.0.1:10001" />
<Setting name="TableStorageEndpoint" value="http://127.0.0.1:10002" />
</ConfigurationSettings>
</Role>
</ServiceConfiguration>



Step 4:- Add CustomerInfo entity class


The next step is to create our entity class which has customer name and message. So below is a simple entity class called as ‘CustomerInfo’ which inherits from ‘TableStorageEntity’. This class has 2 properties ‘CustomerName’ and ‘Message’.
public class CustomerInfo :
Microsoft.Samples.ServiceHosting.StorageClient.TableStorageEntity
{
public CustomerInfo()
{
this.PartitionKey = "CustomerInfos";
this.RowKey = DateTime.Now.Ticks.ToString();
}
public string CustomerName { get; set; }
public string Message { get; set; }
}



Step 5:- Add CustomerInfoDataContext class


We need to create one more class i.e. the data context class. This class is responsible for adding the above defined customer entity class. So the first thing is inherit from the ‘TableStorageDataServiceContext’ class as shown in the below code snippet.
public class CustomerInfoDataContext : TableStorageDataServiceContext
{}

In the same class we creat a initializetable method which will create the table structure define by the ‘CustomerInfo’ class.
Below is the code snippet explanation with comments.


public void InitializeTable()
{
// Get access to the account of table storage end point
StorageAccountInfo accountInfo =StorageAccountInfo.GetAccountInfoFromConfiguration("TableStorageEndpoint",true);

// Create the table using the ‘TableStorage’ class. TableStorage.CreateTablesFromModel(typeof(CustomerInfoDataContext), accountInfo);
}

We also need to expose ‘IQueryable’ interface which exposes ‘CustomerInfo’ class which can be used by Azure system to create
azure table structure.

public IQueryable<CustomerInfo> CustomerInfos
{
get
{
return this.CreateQuery<CustomerInfo>("CustomerInfos");
}
}

We are also exposing a ‘AddCustomer’ method which takes the ‘CustomerInfo’ object , this object is then added to the Azure
table using the ‘AddObject’ method of the ‘TableStorageDataServiceContext’ and finally for committing the same to the table we call the ‘SaveChanges’ method.


public void AddCustomer(CustomerInfo _objCustomer)
{
this.AddObject("CustomerInfos", _objCustomer);
this.SaveChanges();
}


Once we add the customer entity in to the table we would like to display the same , so we have exposed a ‘GetCustomerInfo’
function which is type casted to list and this can be binded to the grid view.

public List<CustomerInfo> GetCustomerInfo()
{

return this.CustomerInfos.ToList();
}



Step 6:- Create web role to add customer messages

The next step is to create a web role project with a ASPX UI page as shown below. You can see that the UI has a gridview source which can be used to display messages and 2 text boxes for customer name
and feedback.


The submit messages button adds messages to the queue while the get old feedback messages displays the messages from the tables.
In order to add the customer and messages to the queue the first step is to get hold of the ‘StorageAccountInfo’ object using the configuration of the queues.

StorageAccountInfo accountQueueInfo = StorageAccountInfo.GetDefaultQueueStorageAccountFromConfiguration();


Use this account queue information to create the storage.
QueueStorage qs = QueueStorage.Create(accountQueueInfo);


Get the customer queue using the Queuestorage class.
MessageQueue queue = qs.GetQueue("customer");


Create the customer queue if it does not exist using the ‘DoesQueueExist’ method.
if (!queue.DoesQueueExist())
queue.CreateQueue();


Create the message object by concatentating both the text boxes and put the same in the queue.
Message msg = new Message(TextBox1.Text+"#"+TextBox3.Text);
queue.PutMessage(msg);
We also have a second button on the web role screen to display the data added in the customer table. So below is the code which will help you display data from the azure table.Get hold of the ‘CustomerInfoDataContext’ class.
CustomerInfoDataContext
objCustomerDataContext = new CustomerInfoDataContext();

Use the ‘GetCustomerInfo’ function which was discussed in the previous steps to get a list of ‘CustomerInfo’ object.
List<CustomerInfo> _objCustomer = objCustomerDataContext.GetCustomerInfo();


Finnally bind the customer objects with the gridview.
if (_objCustomer.Count > 0)

{
GridView1.DataSource = _objCustomer;
GridView1.DataBind();
}



Step 7:- Create worker role to read the messages
In step 7 we have seen how the web role inserts data in to the queue. Now the queue is read by the worker role , the message is parsed and searched for ‘xxx’ , if its not found it will add the same to tables. So the first step is get hold of the queue object as shown in the below code snippet.
StorageAccountInfo accountQueueInfo = StorageAccountInfo.GetDefaultQueueStorageAccountFromConfiguration();
QueueStorage qs = QueueStorage.Create(accountQueueInfo);
MessageQueue queue = qs.GetQueue("customer");


In the worker there will be a infinite loop which will keep running and polling for messages using the queue objects which we just obtained from the above step.
while (true)
{
Message msg = queue.GetMessage();
if (msg != null)
{
// Parse XXX data here
}

}
In the while loop we get the message and checkfor ‘XXX” as shown in the below code snippet. If we do not find a ‘XXX’ we add
it to the table as entity using the data context object as shown in the below code snippet.

string message = msg.ContentAsString();
string name = message.Substring(0, message.IndexOf("#"));
string msgUser = message.Substring(message.IndexOf("#") + 1, message.Length - message.IndexOf("#") - 1);
if (!msgUser.Contains("xxx"))
{
CustomerInfo _obj = new CustomerInfo();
CustomerInfoDataContext objCustomerDataContext = new CustomerInfoDataContext();
_obj.CustomerName = name; _obj.Message = msgUser;
objCustomerDataContext.InitializeTable();
objCustomerDataContext.AddCustomer(_obj);
}

queue.DeleteMessage(msg);
Now we are all set to run the program. Just toensure that all the tables are created , right click on the visual studio project and select ‘Create test storage tables’ as shown below.
Enjoy your hard work. If you now add ‘XXX’ in the feedback message its not added to the table and rejected by the worker role. If you add a normal message its displayed on the grid view source of the webrole project.

Source code

You can get the source code of the above sample from here.

Monday, February 1, 2010

Simple 5 steps to expose WCF services using REST style

Introduction
Video of this article
Step 1:- Create your WCF service project.
Step 2:- Make changes to the web.config files
Step 3:- Decorate your methods with ‘WebInvoke’ attribute.
Step 4:- Run your program.

Introduction


WCF Rest Services are nothing but simple WCF Services with added functionality
of consuming WCF service in a Restful manner. For instance if you had a order
web service that you built in WCF, instead of consuming them through heavy SOAP
implementation and ASMX, you can use the WCF Rest functionality to consume the
service by using simple HTTP verbs like post and get.
So rather than passing complicated SOAP message to the below link to get a order detail http://localhost/order.svc

We can now use REST style to get order as shown in the below URL
http://localhost/order.svc/GetOrder/100234

In this article we demonstrate the 4 important steps to enable your WCF service as a REST service.

Video of this article

In case you are lazy like me you can download the video of this article in MP4 format from http://tinyurl.com/y8j4jjb .

Step 1:- Create your WCF service project.

The first step is to create your WCF service. So click on new website and select WCF service template.



Step 2:- Make changes to the web.config files

The next step is to make changes in the Web.config files to ensure that its uses the HTTP verbs like post and get. So open the web.config file of your WCF project and change the binding to ‘webHttpBinding’ as shown in the below code snippet.
<endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="WebBehavior1">

We also need to insert the ‘endpointBehaviors’ tag with ‘webHttp’ tag in the behavior tag as shown in the below code snippet.
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior1">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>



Step 3:- Decorate your methods with ‘WebInvoke’ attribute.

The next step is to decorate the function / method with ‘WebInvoke’ attribute as shown below. So decorate your function which you want to expose through REST using the ‘WebInvoke’ and specify the HTTP method which this function will accept, currently its ‘GET’.

We have also specified what kind of URI template will be used with the function. Currently we have specified the format as ‘Getdata/{value}’. In other words we can pass data as ‘GetData/1’, GetData/2’ etc.

using System.ServiceModel.Web;
[OperationContract]
[WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "GetData/{value}")]
string GetData(string value);

Step 4:- Run your program.

Now run your program with URL as ‘http://localhost/WcfService3/Service.svc/GetData/12’ as shown in the below figure and it will display the data in the XML format as shown in the below figure.

My article links on WIKI