I am Raghuveer

In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

Showing posts with label WebServices. Show all posts
Showing posts with label WebServices. Show all posts

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.

Features Web Service WCF
Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
Model [WebMethod] attribute represents the method exposed to client [OperationContract] attribute represents the method exposed to client
Operation One-way, Request- Response are the different operations supported in web service One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML System.Xml.serialization name space is used for serialization System.Runtime.Serialization namespace is used for serialization
Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions

Calling ASP.NET Web Services using JQuery AJAX

AJAX has changed the way we developed web sites in the past by giving them responsiveness similar to Desktop applications. In Plain English, AJAX means that instead of waiting for the whole web page to load you can load and display only what you need to. Technically speaking, it’s a technique to communicate with servers through JavaScript asynchronously and handle external data. In this tutorial, I will show you how you can call ASP.NET web service using JQuery, which is the most popular and widely used JavaScript library.

To start communicating with ASP.NET web service through JQuery we first need to implement our web service. Create an ASP.NET web site project in Visual Studio and add an ASP.NET Web Service by right clicking the project name and choosing Add New Item option as shown in the figure below.

Add New Item Dialog

Once the Add New Item dialog box appears, select Web Service (.asmx) item from the list and give web service a suitable name such asDateWebService.asmx. Visual Studio will create a web service (.asmx) and related code behind files in the project. You need to add a method GetDateTime in web service code behind file but keep in mind that we will call this web service from JavaScript so you need to remove comments from the attribute System.Web.Script.Services.ScriptService of your class. The complete code of the web service class is shown below.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class DateWebService : System.Web.Services.WebService {
public DateWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string GetDateTime() {
return DateTime.Now.ToString();
}

}


The web service code is pretty straight forward as there is only one method GetDateTime defined returning the current Date and Time using DateTime.Now property. Before calling the service method using JQuery you need to keep in mind few restrictions on calling service methods from JavaScript. To preventing some security vulnerabilities, ASP.NET service validation layer checks for following two things when service methods are called from JavaScript.

  1. Only POST method can be used to call a web service method. You cannot use HTTP GET.
  2. The HTTP content-type header should be set to the value "application/json".
For those of you who are not familiar with JSON may be wondering what is json and where it came from. So don’t worry I have some basic introduction for you in this tutorial as we will use it in few minutes using JQuery AJAX. In modern AJAX based web applications, when web services are called from client applications, they normally return XML formatted response, which can be parsed and use in JavaScript, but it complicates things for developers. They need a simple data structure which can be used more easily than XML. This is where JavaScript Object Notation (JSON) comes to help us with the following major features.
  1. Lightweight data-interchange format.
  2. Easy for humans to read and write.
  3. Easy for machines to parse and generate.
  4. JSON can be parsed trivially using the JavaScript eval() procedure or using some useful methods in JQuery API.
  5. JSON supports almost all modern languages such as ActionScript, C, C#, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby and many more.

Any .NET object you return from web service methods can be serialized in JSON format. To get some familiarity with JSON format, let’s say you have following custom Product object initialized with some properties.

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };


If you will serialize the object in JSON format it will produce the following output:

{
"Name": "Apple",
"Expiry": new Date(1230422400000),
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}


You can see from the above output that JSON data structure is very easy to read and understand. If you are a .NET developer and want to learn more about serialization and de-serialization of .NET objects into JSON, I will recommend you to use free JSON.NET library available atjson.codeplex.com.
Let’s come back to our tutorial, we have implemented web service so it’s time to create a web page and call that service using JQuery. Create an ASP.NET web form (.aspx) in your project and add the following button and span tag in web form.

<form id="form1" runat="server">
<input id="Button1" type="button" value="Get Date and Time" />
<br />
<br />
<span id="output" />
</form>


Next add the JQuery library reference and the following JQuery script in the head section of the page.

<script src="Scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Button1").click(function() {
$.ajax({
type: "POST",
url: "/ASPNET_WebServices_JQuery/DateWebService.asmx/GetDateTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)
{
$("#output").text(msg.d);
}
});

});
});
</script>

The important lines in the above code are when the $.ajax() method is called inside the Button1 click event handler. $.ajax() method performs an asynchronous HTTP AJAX request and can be customized with many parameters. Some of the parameters I used in the above code are explained below:
type: The type of request you want to make "POST" or "GET". The default value of this parameter is "GET"
url: A string containing the URL to which the request is sent. In the code above, I put the website project name followed by the service file name with extension and then the web method name.
data: This parameter contains the data to be sent to the server. For the GET requests it will be appended to the url although you can change this behavior using processData parameter (not used in the above example). I am using empty braces in the above example as I am not passing any parameters to service methods.
contentType: When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded". Data will always be transmitted to the server using UTF-8 charset. In the above code, I am explicitly using application/json as the contentType.
dataType: The type of data that you're expecting back from the server. If none is specified, JQuery will intelligently try to get the results, based on the MIME type of the response. The available types are xml, html, script, json, jsonp and text.
success: JQuery $.ajax() method also supports many callback functions, which are invoked at the appropriate during the request process. One of them is a success which is called if the request succeeds.
In this tutorial, I have explained all the options used in this example code above but there are more parameters and options available, and If you are interested to read more about JQuery $.ajax() method please visit the JQuery API documentation available athttp://api.jquery.com/jQuery.ajax.
Build and test your page in the browser, and you will see the server time displayed on the page when you will click the button. If you are using FireFox you can even see the JSON formatted response came from the server in my favorite FireFox plug-in Firebug.

JQuery AJAX ASPNET Web Service

In this tutorial, I tried to give you the basic introduction of calling ASP.NET web service using JQuery AJAX along with some explanation of JSON format. In my future tutorials, I will show you more complex interaction between client and server using JQuery AJAX so please keep visiting my website to learn more about the tips and tricks of latest technologies.

Download Source Code

Using JQuery, AJAX, JSON and ASP.NET Web Services

Due to the latest paradigm shift in web development, more and more websites are loading and displaying all types of dynamic contents on the web pages. Web 2.0 based websites such as Gmail. Facebook and Twitter have not only changed the user’s expectations but also forced developers to learn more dynamic and exciting ways to build web applications. Client side web technologies like AJAX, XHTML, DOM, JavaScript and JQuery are now mandatory ingredients of every web developer resume. In my previous tutorial, I have shown you how you can call ASP.NET web services using JQuery AJAX capabilities. In this tutorial, I will show you how you can pass parameters to web services and how you can use JSON data returned from web services to display dynamic contents on web page.

Due to the latest paradigm shift in web development, more and more websites are loading and displaying all types of dynamic contents on the web pages. Web 2.0 based websites such as Gmail. Facebook and Twitter have not only changed the user’s expectations but also forced developers to learn more dynamic and exciting ways to build web applications. Client side web technologies like AJAX, XHTML, DOM, JavaScript and JQuery are now mandatory ingredients of every web developer resume. In my previous tutorial, I have shown you how you can call ASP.NET web services using JQuery AJAX capabilities. In this tutorial, I will show you how you can pass parameters to web services and how you can use JSON data returned from web services to display dynamic contents on web page.

Create a new ASP.NET website in the visual studio and add following Employee.cs class in App_Code folder of your project. I will be using this class from the web service to return the list of Employee class objects to the clients.

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
}


Next, add an ASP.NET web service EmployeeWebService.asmx in the project by using Add New Item dialog box. The complete web service code is shown below:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class EmployeeWebService : System.Web.Services.WebService {
List<Employee> list = new List<Employee>();
public EmployeeWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
list.Add(new Employee { Id = 1, Name = "Peter", Salary = 22000 });
list.Add(new Employee { Id = 2, Name = "Mark", Salary = 24000 });
list.Add(new Employee { Id = 3, Name = "James", Salary = 28000 });
list.Add(new Employee { Id = 4, Name = "Simon", Salary = 29000 });
list.Add(new Employee { Id = 5, Name = "David", Salary = 19000 });

}
[WebMethod]
public List<Employee> GetAllEmployees() {
return list;
}

[WebMethod]
public Employee GetEmployeeDetails(string employeeId)
{
int empId = Int32.Parse(employeeId);
Employee emp = list.Single( e => e.Id == empId);
return emp;
}

}

In start, the web service declares a list of Employee objects which I will be using to store employee objects for this tutorial.

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


I have added five employee objects to the list in the constructor of the web service. I am using this approach only for simplifying this tutorial as in a real world application these records are normally stored in the database.

list.Add(new Employee { Id = 1, Name = "Peter", Salary = 22000 });
list.Add(new Employee { Id = 2, Name = "Mark", Salary = 24000 });
list.Add(new Employee { Id = 3, Name = "James", Salary = 28000 });
list.Add(new Employee { Id = 4, Name = "Simon", Salary = 29000 });
list.Add(new Employee { Id = 5, Name = "David", Salary = 19000 });

A web method GetAllEmployees returns the list of employees to the clients.

[WebMethod]
public List GetAllEmployees()
{
return list;
}


Another simple web method GetEmployeeDetails will filter and return a single Employee object based on employee id.

[WebMethod]
public Employee GetEmployeeDetails(string employeeId)
{
int empId = Int32.Parse(employeeId);
Employee emp = list.Single( e => e.Id == empId);
return emp;
}


Next add the following code in your web page in HTML source. It has a DropDownList to display all employees and an HTML table to display single employee details.

<form id="form1" runat="server">
Select Employee:
<asp:DropDownList ID="DropDownList1" runat="server" Width="150">
<asp:ListItem Text="Select" Value="-1" />
</asp:DropDownList>

<br />
<br />
<table style="border: solid 1px black; width: 300px; display: none; background-color: #f3f3f3"
cellpadding="4" cellspacing="0" id="outputTable">
<tr>
<td>Employee ID:</td>
<td><span id="spnEmployeeId" /></td>
</tr>
<tr>
<td>Employee Name:</td>
<td><span id="spnEmployeeName" /></td>
</tr>
<tr>
<td>Salary:</td>
<td><span id="spnSalary" /></td>
</tr>
</table>
</form>

Before staring JQuery AJAX code make sure you have JQuery file available in the scripts folder of your website, and you have added file reference in the page <head> element.
<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
Next add a JavaScript code block and typical JQuery ready function to get things started when the document is ready and DOM tree is loaded by the browser. The first statement is a call to another JavaScript function GetAllEmployees which is declared just after ready function. This function will call GetAllEmployees web service method, and then it will populate the DropDownList control from the JSON data returned from the web service method. Next the DropDownList change event function handler is defined, which first gets the selected employee id from theDropDownList using JQuery val method and then pass that employee id to another JavaScript function GetEmlployeeDetails which will retrieve details of that particular employee by calling web service GetEmployeeDetails method and then will display details in HTML table.

<script type="text/javascript">
$(document).ready(function () {
// Load Employees
GetAllEmployees();
var DropDownList1 = $("#DropDownList1");
DropDownList1.change(function (e) {
var employeeId = DropDownList1.val();
if (employeeId != -1) {
// Get Employee Details
GetEmployeeDetails(employeeId);
} else {
$("#outputTable").hide();
}
});
});
function GetAllEmployees() {
// JQuery AJAX Code Here
}
function GetEmployeeDetails(employeeId) {
// JQuery AJAX Code Here
}

</script>


As you can see in the above code, I didn’t define the GetAllEmployees and GetEmployeeDetails functions so that you can focus on ready function implementation and can understand more easily what is going on in JQuery ready function. To complete this tutorial, I need to show you the code required inside the above two functions to call web services methods and to update controls and user interface elements. Following is the implementation of GetAllEmployees function:

function GetAllEmployees()
{
var DropDownList1 = $("#DropDownList1");
$.ajax({
type: "POST",
url: "EmployeeWebService.asmx/GetAllEmployees",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var Employees = response.d;
$.each(Employees, function (index, employee) {
DropDownList1.append('<option value="' + employee.Id + '">' + employee.Name + '</option>');
});

},
failure: function (msg) {
alert(msg);
}
});
}


In the above code snippet, JQuery ajax() method is used to send AJAX request to ASP.NET web service method GetAllEmployees. From the parameters, you can easily guess the service method url, request type (POST) and data type (JSON). If you are not familiar with the ajax()method parameters, I will recommend you to read my tutorial Calling ASP.NET Web Services using JQuery AJAX for more detailed understanding of the ajax() method and JSON.
Inside the success function handler of ajax() method, I have used JQuery each() method to loop through all the employees I received in JSON response (response.d) and I appended the HTML elements inside DropDownList to display all employees. If you will build and test your page in the browser you will see DropDownList populate with employee names as shown in the following figure. You can also see the JSON response inFireBug just below to the DropDownList.

JQuery AJAX JSON Response

The following is the code required for the GetEmployeeDetails function. The code is almost similar to the GetAllEmployees function as it is also using JQuery ajax() method to call web service method but there are two differences. First, I am passing employee id as a parameter in JSON format using the data option of JQuery ajax() method. Second, inside success method I am not using any loop to iterate employees as there is only one employee to receive from the web service method. Note the Employee class properties Id, Name and Salary are used to display values inside span elements declared in HTML table above.

function GetEmployeeDetails(employeeId)
{
$.ajax({
type: "POST",
url: "EmployeeWebService.asmx/GetEmployeeDetails",
data: "{'employeeId':'" + employeeId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
var Employee = response.d;
$("#spnEmployeeId").html(Employee.Id);
$("#spnEmployeeName").html(Employee.Name);
$("#spnSalary").html(Employee.Salary);
$("#outputTable").show();

},
failure: function (msg)
{
alert(msg);
}
});
}

That’s all we need to call web service methods using JQuery AJAX and to display single or multiple records coming from web service method in JSON format. Build and run your web page, and you will see output similar to following figure:

JQuery AJAX JSON Response

 

Download Source Code Download Source Code Live Demo Live Demo

Calling Web Services in Client Script using ASP.NET AJAX

Web Services play an important role in data transport and communication between the client the server. Web services reside on the server and wait to be called by any client and most of the time these clients are written in server side technologies such as ASP.NET, PHP or JSP etc. ASP.NET AJAX provides web developers ability to call web services from the client side language such as JavaScript asynchronously to improve the user experience and to avoid full page refresh and postback. In this tutorial, I will show you how you can call an ASP.NET web service with the help of ASP.NET AJAX.

For the purpose of this tutorial I have created a web service with the name ProductsService.asmx. If you are new to web services and don’t know how to add web service right click on your website name in Solution Explorer and click Add New Item option and select the Web Service icon from the available file templates as shown in figure below. A new file with the name ProductsService.asmx will be added in your website and the code behind file for the web service will be added in App_Code folder.

Add ASP.NET Web Service

Notice the ProductsService class is derived from the System.Web.Services.WebService class available in .NET Framework class library. Also check the following directive in your code and make sure it is not commented because this directive is required to call web service using ASP.NET AJAX.[System.Web.Script.Services.ScriptService]
The implementation of web service is fairly straight forward. It has only one method GetProducts which is decorated with [WebMethod] attribute that is required to expose web service methods to consumers and calling applications. The method takes category id as a parameter and return some products based on the category. I am returning hard coded products names and not connecting database in this tutorial but you can easily write code to return products from the database.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]
public class ProductsService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetProducts(int categoryId)
{
List<string> list = new List<string>();
if (categoryId == 1)
{
list.Add("Nokia N95");
list.Add("Nokia N70");
list.Add("Nokia 6630");
}
else
{
list.Add("Dell Laptop");
list.Add("HP Laptop");
list.Add("Sony Laptop");
}
return list;
}
}


To consume web service by using client script you need to add an instance of the ASP.NET AJAX ScriptManager control in your page. This control supports a Services collection which can be used to add the reference of web services you want to call from client side JavaScript. The ASP.NET AJAX asynchronous communication layer automatically generates JavaScript proxy classes for each Web service reference you add usingScriptManager control.
Once your page is requested, the proxy class is downloaded to the browser at the page load time and provides a client object that represents the exposed methods of a Web service. To call a method of the Web service, you can call corresponding method of generated proxy class. The proxy class in turn communicates with the Web service asynchronously by using XmlHttpObject of the browser.
For this tutorial, I have added the reference of ProductsService.asmx by using <asp:ScriptReference> element inside Services collection under the <asp:ScriptManager> element. The remaining form has a DropDownList, an HTML button and a Label control. Notice that the onclick event of the Button1 control is calling a JavaScript function Button1_onclick() which needs to be defined in the JavaScript in your page.

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/ProductsService.asmx" />
</Services>
</asp:ScriptManager>

Select Category:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">Mobiles</asp:ListItem>
<asp:ListItem Value="2">Laptops</asp:ListItem>
</asp:DropDownList>
<input id="Button1" type="button" value="Get Products"
onclick="Button1_onclick()" />
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</form>


As I mentioned earlier that calling a Web service method from client script is asynchronous means the communication will take place behind the scene and user will remain interactive with the page. If your web service returns some data you must provide a callback function you want to execute on successful call to web service. You can also provide another callback function to handle errors in case the Web service call failed due to any communication or server error or Web service return no data.
I have added the following JavaScript code in my page to call Web service. Notice how I have called the GetProducts method of the Web service using the ProductsService proxy class generated automatically for me when I have added the Web service reference using ScriptManagercontrol. Also notice the callback functions onSuccess and onFailed have been passed as a second and third parameter in the proxy class GetProducts method to receive the results or error messages returned by the Web service and to update the page accordingly.

<head runat="server">
<title>Consuming Web Services From AJAX</title>
<script type="text/javascript">
function Button1_onclick()
{
var categoryId = $get("DropDownList1").value;
ProductsService.GetProducts(categoryId, onSuccess, onFailed);
}
function onSuccess(result)
{
var Label1 = $get("Label1");
Label1.innerHTML = "";
for(i=0 ; i<result.length ; i++)
{
Label1.innerHTML += result[i] + "<br />";
}
}
function onFailed(error)
{
var Label1 = $get("Label1");
Label1.innerHTML = "Service Error: " + error.get_message();
}
</script>
</head>


Build your project and test your page in the browser and you will see output similar to the following when you will click the button after selecting a category from the DropDownList.

ASP.NET AJAX Web Service

Posting data to URL in C#.NET

The following procedure describes the steps used to send data to a server. This procedure is commonly used to post data to a Web page.
requestResponse
public static string sendToServer(string Request)
        {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(“URL”);
               
//HttpWebRequest class is used to Make a request to a Uniform Resource Identifier (URI). 
                request.ContentType = "application/x-www-form-urlencoded";
               // Set the ContentType property of the WebRequest.
                request.Method = "POST";
                byte[] byteArray = Encoding.UTF8.GetBytes(Request);
               // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length; 
               //Get the stream that holds request data by calling the GetRequestStream method.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
                WebResponse response = request.GetResponse();
               // Get the stream containing content returned by the server.

                //Send the request to the server by calling GetResponse.
                dataStream = response.GetResponseStream();
              
// Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
              
// Read the content.
                string Response = reader.ReadToEnd();
                //return the response
                return Response;
        }



..Source MSDN