Wednesday, March 12, 2014

JSON with AJAX Example

using System;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Data.SqlClient;
using System.Runtime.Serialization.Json;
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = 
  AspNetCompatibilityRequirementsMode.Allowed)]
public class ProductService
{ 
 [OperationContract]    
 public string GetProductDetailsByProductID(int productID)
 {
   Product prod = new Product();        
   string connectionString = 
     "server=localhost;uid=sa;pwd=thiru;database=AdventureWorks;";
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
     string sql = "Select Name, ProductNumber from Production.Product " +
       " Where ProductID = " + productID.ToString();
     connection.Open();
     SqlCommand command = new SqlCommand(sql, connection); 
     SqlDataReader reader = command.ExecuteReader();
     while (reader.Read())
     {
       prod.Name = reader["Name"].ToString();
       prod.ProductNumber = reader["ProductNumber"].ToString();
       prod.ProductID = productID;
     }
    }
    MemoryStream stream = new MemoryStream();
    DataContractJsonSerializer serializer = new 
      DataContractJsonSerializer(typeof(Product));
    serializer.WriteObject(stream, prod);
    stream.Position = 0;
    StreamReader streamReader = new StreamReader(stream);
    return streamReader.ReadToEnd();        
  } 
}
[DataContract]
public class Product
{
    [DataMember]
    public int ProductID;
    [DataMember]
    public string Name;
    [DataMember]
    public string ProductNumber;
} 






================
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Invoking the Product Service through the AJAX based Client</title>
 <script type="text/javascript">    
   function pageLoad() {
   }
   function OnGetProductDetailsByProductID() {                 
     ProductService.GetProductDetailsByProductID($get("txtProductID").value, 
       OnGetProductDetailsByProductIDComplete, OnError);         
   } 
   function OnGetProductDetailsByProductIDComplete(result){ 
     var prod = eval("(" + result + ")");                
     $get("spnProductID").innerText = prod.ProductID;
     $get("spnProductName").innerText = prod.Name;
     $get("spnProductNumber").innerText = prod.ProductNumber;                
   } 
   function OnError(errorMessage) {
     alert(errorMessage.get_message()); 
   } 
  </script>
</head>
<body>
 <form id="form1" runat="server">
  <div>
   Enter Product ID: 
   <input type="text" id="txtProductID" name="txtProductID" />        
   <input type="button" value="Get Product Details" id="btnInvokeWebService" 
     onclick="OnGetProductDetailsByProductID()" />
   <asp:ScriptManager ID="ScriptManager1" runat="server">
     <Services>
       <asp:ServiceReference Path="~/ProductService.svc" />
     </Services>
   </asp:ScriptManager>
   <br /><br />        
   Product ID : <span id="spnProductID"></span> <br /><br />
   Name :<span id="spnProductName"></span> <br /><br />
   Product Number :<span id="spnProductNumber"></span> <br /><br />
  </div>
 </form>
</body>
</html> 
Before looking at the code required to implement the client, let us understand the steps involved in utilizing the ASP.NET AJAX extensions for invoking the WCF Web service.
  1. The client declares a <asp:ScriptManager> element to specify the location of the Web service. Inside this element, you declare the path of the Web service using the Path attribute of the <asp:ServiceReference> element. This enables the client side code to dynamically create the proxy for the Web service.
  2. You invoke a client-side method that will use declared proxy to invoke the Web service.
  3. The proxy invokes the Web service passing in the required arguments to the service, as well as the callback method to invoke after the Web service execution is completed. In addition, you also pass in a separate callback method that will be invoked in case an exception is generated during the server side processing.
  4. The service receives the request, processes the request by invoking the appropriate methods on the server side. Then it returns the results back to the proxy on the client side.
  5. The proxy receives the server response and invokes a callback method located on the client-side. If there is an error during the server side processing, the callback manager invokes a separate callback method.
  6. The client processes the results returned from the service call.







No comments:

Post a Comment