Monday, April 18, 2011

Consuming ReST Service

Today let us review how to consume the ReST service that was created in previous post.

Given below are 3 ways to consume the service


1) By using XMLDocument

XmlDocument oDoc = new XmlDocument();
oDoc.Load("http://localhost:49492/UserService.svc/users/World");
Console.WriteLine(oDoc.InnerXml);
Console.ReadLine();

2) Using Http Request


HttpWebRequest oRequest = (HttpWebRequest)WebRequest.Create("http://localhost:49492/UserService.svc/users/World");
HttpWebResponse webResponse = (HttpWebResponse)oRequest.GetResponse();
Stream receiveStream = webResponse.GetResponseStream();
StreamReader oReader = new StreamReader(receiveStream);
Console.WriteLine(oReader.ReadToEnd());
oReader.Close();
webResponse.Close();
Console.ReadLine();

3) Using Channel Factory


ChannelFactory factory = new ChannelFactory(new WebHttpBinding(), new EndpointAddress("http://localhost:49492/UserService.svc"));
factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
IUserService proxy = factory.CreateChannel();
Console.WriteLine(proxy.GetFullName("World"));

int i = proxy.PutUserAccount("world", "newval");
Console.WriteLine(i.ToString());
Console.ReadLine();

Monday, April 4, 2011

ReST Application using WCF

This article is about creating a simple ReST(Representational State Transfer) application using WCF. Using ReST model of communication, web services can be invoked without the WSDL.

Let us go through an example on how to develop a ReST application


1) Create a WCF application in VS 2008
(File -> New project-> Select "WCF Service Application" (Under Visual C#, Web))
Visual Studio will create service file (Service1.svc and IService1.cs)

2) Add reference to "System.ServiceModel.Web" ( This is required for "WebGet" Attribute that is used in interface method definition )

Let us reuse IService.cs for our example.

3) Create a new method definition in IService1 as given below

[WebGet(UriTemplate = "users/{username}")]
[OperationContract]
string GetFullName(string username);

4) Implement the interface method in Service1.svc as given below

public string GetFullName(string username)
{
return "Hello " + username;
}

5)In web.config make below 2 changes

 a) Remove the existing endpoint and add the new endpoint

<endpoint address="" behaviorconfiguration="webHttp" binding="webHttpBinding" contract="RestTestApp.IService1">
<identity>
<dns value="localhost">
</identity>
</endpoint>

 b) Include endpoint behavior for webHttp. This should be inside tag

<endpointbehaviors>
<behavior name="webHttp">
<webhttp>
</behavior>
</endpointbehaviors>


6)The development of ReST application is complete! Run the application.

Navigate to -
http://localhost:{Port if using Development server}/UserService.svc/users/test

This will return an xml

With ReST model , we are now able to access the service without passing the parameters in XML (SOAP). The service can be accessed and executed using a simple http webrequest.

We will look at how to consume this ReST application in later articles.

Till then, happy coding.

Friday, April 1, 2011

Callback Feature in ASP.NET

The callback feature in ASP.NET helps to display content in webpage in an asynchronous way.

Lets go straight to an example and get it working.


1)Create a web application in VS 2008

2)In Page Load of "Default.aspx.cs" , enter the following code


/*Client function to Receive Server Data*/
string strReceiveServerData = "function ReceiveServerData(arg,context){RecieveServerDate2(arg);}";

/*Get Callback Reference*/
string strReceiveCallReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", strReceiveServerData);

/*Client function to Call Server... the reference of "Receive server data" function is added here*/
string strCallTheServer = "function CallServer(arg,context){" + strReceiveCallReference + ";}";

/*Register the script*/
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", strCallTheServer, true);

3) Inherit interface “ICallbackEventHandler” in page

public partial class AsyncServerCall : System.Web.UI.Page,ICallbackEventHandler

4) Add method code for interface "ICallbackEventHandler" in "Default.aspx.cs"

#region ICallbackEventHandler Members

string strVar = "";
public string GetCallbackResult()
{
return strVar;
}

public void RaiseCallbackEvent(string eventArgument)
{
strVar = "Hello World," + eventArgument;
}

#endregion

5) Add below Javascript to aspx page. Make sure you add "script" tags.

<script>
function RecieveServerDate2(arg) {
alert(arg);
}
</script>

6) And the final step... call the javascript function to make server call in body onload

<body onload=" CallServer('Guys', '');" >

Run it! And you will get an alert “Hello World, Guys”. Wasn’t the callback easy in ASP.NET?

Thursday, March 31, 2011

Generics and LINQ

Generics is a feature that is very useful in ASP.NET. If generic collection is used to store data then quering data from the collection becomes really easy.
Given below is a simple example for creating a generic collection and quering from it using LINQ.

1) Create an object collection
a) Define the object "Employee"

public class Employee
{
public Employee(int iID, string strName, string strAddress, int iAge)
{
ID = iID;
Name = strName;
Address = strAddress;
Age = iAge;
}
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public int Age { get; set; }
}


b)Add objects to collection

public List GetEmployees()
{

List<Employee> lstEmps = new List<Employee>();

lstEmps.Add(new Employee(1, "Emp 1", "212 Street1", 34));
lstEmps.Add(new Employee(2, "Emp 2", "543 Street2", 31));
lstEmps.Add(new Employee(3, "Emp 3", "3332 Street2", 27));
lstEmps.Add(new Employee(4, "Emp 4", "1011 Street2", 40));
lstEmps.Add(new Employee(5, "Emp 5", "3214 Street4", 33));
lstEmps.Add(new Employee(6, "Emp 6", "5543 Street1", 35));

return lstEmps;
}



2) Query collection using LINQ

List<employee> EmpList =GetEmployees();

/**LINQ Examples**/

//Select employees with age > 30
List<employee> emps1 = (from x in EmpList where x.Age > 30 select x).ToList();

//Select employees with name starting with "Emp"
List<employee> emps2 = (from x in EmpList where x.Name.StartsWith("Emp") select x).ToList();

//Select employee with address "212 Street1"
List<employee> emps3 = (from x in EmpList where x.Address == "212 Street1" select x).ToList();

Delete Duplicate Rows from SQL Server Table

This example is about deleting duplicate rows in SQL server table. In this example duplicate records are deleted from the table based on rank.

/*Create temp table*/
create table #tmp(id int,name1 varchar(20),cre_date datetime)

GO
/*Insert rows with duplicate data in it*/
insert into #tmp values(1,'name1','2011-03-30 9:00 am')
insert into #tmp values(1,'name1','2011-03-30 9:20 am')
insert into #tmp values(2,'name2','2011-03-30 9:30 am')
insert into #tmp values(3,'name3','2011-03-30 9:40 am')
insert into #tmp values(3,'name3','2011-03-30 9:50 am')
insert into #tmp values(3,'name3','2011-03-30 9:55 am')

GO
/*Delete the rows that are duplicate*/
with t as (
Select id,name1,row_number() over (partition by id,name1 order by cre_date) rnk from #tmp )
delete from t where rnk>1