| 1 comments ]

In this article I will explain how to consume a WCF / ASMX service using jQuery. The scope of the article is limited to creating & consuming different kind of services using jQuery. I have segregated this article into 7 topics based on the service consumption.

  1. Calling ASMX Web service using jQuery
  2. Calling WCF service using jQuery and retrieving data in JSON Format
  3. Calling WCF service using jQuery and retrieving data in XML Format
  4. Calling WCF service using jQuery and retrieving data in JSON Format (pass multiple input parameters) & ( Get multiple objects as output using DataContract)
  5. Calling WCF service using jQuery[ Get Method] and retrieving data in JSON Format
  6. Calling REST based WCF service using jQuery
  7. Streaming an image through WCF and request it through HTTP GET verb..

If you have never heard about jQuery or WCF or JSON, please learn it before dwelling into this article. The scope is limited to service creation and consumption.

In the below example I have used jQuery version 1.3.2 , you can download the same from http://jQuery.com/. This article demonstrates how our jQuery based browser app will retrieve the Provinces for supplied country. All the services are hosted in the same web application. Please download the source code to experiment the sample by yourself.

For calling the service we need to use the .ajax method of jQuery which makes XMLHttpRequest
to the server. In the below code section I have explained the key value pair attributes to be passed by marking comments on the right side of the attribute.

<script type="text/javascript" language="javascript" src="script/jQuery-1.3.2.min.js" "></script>

     <script type="text/javascript">

        var varType;
        var varUrl;
        var varData;
        var varContentType;
        var varDataType;
        var varProcessData; 

        function CallService() 
        {
                $.ajax({
                    type                : varType, //GET or POST or PUT or DELETE verb
                    url                   : varUrl, // Location of the service
                    data                : varData, //Data sent to server
                    contentType    : varContentType, // content type sent to server
                    dataType         : varDataType, //Expected data format from server
                    processdata    : varProcessData, //True or False
                    success            : function(msg) {//On Successfull service call
                    ServiceSucceeded(msg);                    
                    },
                    error: ServiceFailed// When Service call fails
                });
        }
    </script>
I have made the above method generic to use it for all different type of services which we are going to discuss.

Business Logic:

Business logic for below demonstrated service is quite simple, we store Country and Province details in a Name Value collection ,When a request supplies the country name it returns the provinces associated with it.

public class CountryProvinceBL
{
    NameValueCollection nvProvince = null;
    public CountryProvinceBL()
    {
        nvProvince = new NameValueCollection();
        nvProvince.Add("usa", "Massachusetts");
        nvProvince.Add("usa", "California");
        nvProvince.Add("india", "Tamil Nadu");
        nvProvince.Add("india", "Karnataka");
    }
    
    public string[] GetProvince(string Country)
    {  return nvProvince.GetValues(Country).ToArray();}

}


1. Calling ASMX Web service using jQuery


Step 1:

Create a web service and add the below code

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// Below line allows the web service to be called through HTTP protocol. 
[System.Web.Script.Services.ScriptService]
public class CountryProvinceWebService : System.Web.Services.WebService
{

    [WebMethod]
   //Business Logic returns the provinces for the supplied country
    public string[] GetProvince(string Country) 
    {  return new CountryProvinceBL().GetProvince(Country); }    
}

Step 2:

Invoke the below method on button click

unction CountryProvinceWebService() {
            varType              = "POST";         
            varUrl                 = "service/CountryProvinceWebService.asmx/GetProvince"; 
            //Pass country from drop down ddlCountry'
            varData               = '{"Country": "' + $('#ddlCountry').val() + '"}';
            varContentType  = "application/json; charset=utf-8";
            varDataType       = "json";varProcessData = true; CallService();
        }



Step 3:

On Success "ServiceSucceeded" will be called and it will populate the provinces dropdown with the values sent by the server.


function ServiceSucceeded(result) {
            var ProvinceDDL = document.getElementById("ddlProvince");
            for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
            var resultObject = result.d; // Constructed object name will be object.d //Button 
            for (i = 0; i < resultObject.length; i++) {
                    var opt = document.createElement("option"); opt.text = resultObject[i];
                    ProvinceDDL.options.add(opt)
                }
        }

2. Calling WCF service using jQuery and retrieving data in JSON Format


Step 1:

Define the Contracts in the interface ICountryProvinceWCFService

[ServiceContract]
public interface ICountryProvinceWCFService
{
    [OperationContract]
    [WebInvoke(Method = "POST",BodyStyle=WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]    
    string[] GetProvince(string Country);
}

Implement the contract in class CountryProvinceWCFService 

public class CountryProvinceWCFService : ICountryProvinceWCFService
{   
  // Call Business Logic to get provinces
    public string[] GetProvince(string Country)
    {return new CountryProvinceBL().GetProvince(Country); }
}

Step 2:

Define the configuration in web.config

a) enables the user to view the metadata through web browser and generate WSDL file

b) setting includeExceptionDetailInFaults = "true" allows the WCF service throw original error , it will be useful while debugging the application.

c) Adding to endpoint behaviour & webHttpBinding to binding enables the web programming model for WCF and allows the service to be accessible through web protocols.

d) Define contract and name of the service

Step 3:

Invoke the WCF service on the button click event


function CountryProvinceWCFJSON() {
            varType              = "POST";
            varUrl                 = "service/CountryProvinceWCFService.svc/GetProvince";
            varData              = '{"Country": "' + $('#ddlCountry').val() + '"}';
            varContentType = "application/json; charset=utf-8";
            varDataType      = "json"; varProcessData = true; CallService();
        }


On successful service invocation "ServiceSucceeded" will be called and the province value will get added to province drop down.


function ServiceSucceeded(result) {/
       var ProvinceDDL = document.getElementById("ddlProvince");
       for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
               // Constructed object name will be object.[ServiceName]Result // Button 2 & 3
              var resultObject = result.GetProvinceResult;
           for (i = 0; i < resultObject.length; i++) {
               var opt = document.createElement("option"); opt.text = resultObject[i];
               ProvinceDDL.options.add(opt)
           }       
   }

3. Calling WCF service using jQuery and retrieving data in XML Format

Step 1:


In operation contract set ResponseFormat to XML.

[OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped,ResponseFormat = WebMessageFormat.Xml)]
    string[] GetProvinceXML(string Country);

Then implement the service 

    public string[] GetProvinceXML(string Country)
    {  return new CountryProvinceBL().GetProvince(Country); }

Use the web.config, defined in Figure 1 .

Step 2:

Invoke the WCF service on the button click event, Make sure you set the expected data type as XML

function CountryProvinceWCFXML() {
            varType              = "POST";
            varUrl                 = "service/CountryProvinceWCFService.svc/GetProvinceXML";
            varData              = '{"Country": "' + $('#ddlCountry').val() + '"}';
            varContentType = "application/json; charset=utf-8"; 
            varDataType      = "xml";  varProcessData = true; CallService();
        }

Step 3:

On successful service invocation "ServiceSucceeded" will be called and the province value will get added to province drop down.

function ServiceSucceeded(result) {
              var ProvinceDDL = document.getElementById("ddlProvince");
              for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
            //Below jQuery code will loop through the XML result set
              $(result).find("GetProvinceXMLResult").children().each(function() {
                  var opt = document.createElement("option"); opt.text = $(this).text();
                  ProvinceDDL.options.add(opt)
              });          
          }

4. Calling WCF service using jQuery and retrieving data in JSON Format (pass multiple input parameters) & ( Get multiple objects as output using DataContract)

In this example Country and Browser type will be passed as input parameter to the WCF service in JSON format, Upon receiving the values the service will send back provinces for the passed country and some comments for the browser information.

Step 1:

Define Data contract and service contact for the service

[DataContract]
public class CustomData
{
    [DataMember]
    public String BrowserInfo;
    [DataMember]
    public String[] ProvinceInfo;
}

  [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    CustomData GetProvinceAndBrowser(string Country, string Browser);


And implement the contract in your service call

    public CustomData GetProvinceAndBrowser(string Country, string Browser)
    {
        CustomData customData = new CustomData();
        customData.ProvinceInfo = new CountryProvinceBL().GetProvince(Country);
        if (Browser == "ie")
            customData.BrowserInfo = " Did you learn to program IE 8.0";
        else if (Browser == "firefox")
            customData.BrowserInfo = " Mozilla rocks, try Firebug & Fiddler addon's";
        else
            customData.BrowserInfo = " I did not test in this browser";
        return customData;
    }


Step 2:

Invoke the WCF service on the button click event, Make sure you set the expected data type as XML

function CountryProvinceWCFJSONMulti() {
            var browser = "";
            if (jQuery.browser.mozilla == true) browser="firefox"
            else if(jQuery.browser.msie == true) browser = "ie"
            varType                = "POST";
            varUrl                   = "service/CountryProvinceWCFService.svc/GetProvinceAndBrowser";
            //We are passing multiple paramers to the service in json format {"Country" : "india", "Browser":"ie"}
            varData                = '{"Country": "' + $('#ddlCountry').val() + '","Browser": "' + browser + '"}';
            varContentType   = "application/json; charset=utf-8";
            varDataType        = "json";varProcessData = true; CallService();
    }

Step 3:

On successful service invocation "ServiceSucceeded" will be called and the province value will get added to province drop down.

 function ServiceSucceeded(result) {
                    var ProvinceDDL = document.getElementById("ddlProvince");
                    for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }                   
                   //WCF Service with multiple output paramaetrs //First object 
                    var resultObject = result.GetProvinceAndBrowserResult.ProvinceInfo;
                    for (i = 0; i < resultObject.length; i++) {
                        var opt = document.createElement("option"); opt.text = resultObject[i];
                        ProvinceDDL.options.add(opt)
                    }
                    //Second object sent in JSON format
                    $("#divMulti").html(result.GetProvinceAndBrowserResult.BrowserInfo);          
                }

5. Calling WCF service using jQuery[ Get Method] and retrieving data in JSON Format

This time we will use GET Verb instead of POST to retrieve the data through WCF & jQuery

Step 1:

We can use the WebGet attribute instead of WebInvoke to perform the operation,
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Json)]
string[] GetProvinceGET(string Country);

Implement the contract

public string[] GetProvinceGET(string Country)
{return new CountryProvinceBL().GetProvince(Country);}

And use the web.config defined in figure 1

Step 2:

Set the verb to GET instead of POST and pass the data as a query string. Invoke the WCF Service using below method

function CountryProvinceWCFJSONGet() {
            varType                 = "GET";
            varUrl                    = "service/CountryProvinceWCFService.svc/GetProvinceGET?Country=" +$('#ddlCountry').val();
            varContentType    = "application/json; charset=utf-8";
            varDataType = "json";varProcessData = false; CallService();
        }

On successful service invocation "ServiceSucceeded" will be called and the province value will get added to province drop down.

function ServiceSucceeded(result) {
           var ProvinceDDL = document.getElementById("ddlProvince");
           for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }          
           for (i = 0; i < result.length; i++) {
               var opt = document.createElement("option"); opt.text = result[i];
               ProvinceDDL.options.add(opt)
           }
       }

6. Calling REST based WCF service using jQuery

Step 1:


Define the URI for REST service in the operation contract and set the BodyStyle to Bare.


[OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProvinceREST/{Country}", BodyStyle=WebMessageBodyStyle.Bare)]
    string[] GetProvinceREST(string Country);

Implement the contract:

    public string[] GetProvinceREST(string Country)
    { return new CountryProvinceBL().GetProvince(Country);  }

Use the web.config defined in Figure 1

Step 2:

While using REST services use GET verb for retrieving data and POST , PUT , DELETE for modifying, adding and deleting information

function CountryProvinceWCFREST() {
            varType               = "GET";
            varUrl                  = "service/CountryProvinceWCFService.svc/GetProvinceREST/" + $('#ddlCountry').val();            
            varContentType  = "application/json; charset=utf-8";
            varDataType       = "json"; varProcessData = false; CallService();
        }

On successful service invocation "ServiceSucceeded" will be called and the province value will get added to province drop down.

function ServiceSucceeded(result) {
           var ProvinceDDL = document.getElementById("ddlProvince");
           for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }          
           for (i = 0; i < result.length; i++) {
               var opt = document.createElement("option"); opt.text = result[i];
               ProvinceDDL.options.add(opt)
           }
       }

Step 1:

Define the contract and set the return type to Stream since we are going to send it in Image/jpeg Format
[OperationContract]
[WebInvoke(Method = "GET")]
Stream GetPicture();

Implement the contract

public Stream GetPicture()
{
string fileName = Path.Combine(HostingEnvironment.ApplicationPhysicalPath,"vista.jpg");
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
// Set the content type as image/ jpeg
System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
return (Stream)fileStream;
}

And use the web.config which we defined earlier in this article

Step 2:

On Button click event set the src attribute of image element [image1] to the WCF service

function ShowImage() {// Call the WCF service
$("#image1").attr('src','service/CountryProvinceWCFService.svc/GetPicture');

}

| 0 comments ]


A tag cloud is a way to display a weighted list such that the weight of each item is reflected by the size of the item's text. Tag clouds provide a quick way for one to eyeball a list and ascertain what items are more prevalent. Oftentimes, each item in a tag cloud is rendered as a link that, when clicked, allows the user to drill into the selected category.

Ideally, a tag cloud could be associated with some data, a few properties set, and, voila, the tag cloud appears! In fact, we'll examine how to accomplish exactly this in a future article by creating a custom, compiled ASP.NET 2.0 server control. For now, though, let's just implement the tag cloud directly from an ASP.NET page (although this could be moved to a User Control for greater reuse opportunities).
First things first - we need the data that returns the list with each item weighted. In the demo downloadable at the end of this article, I have used a SqlDataSource control to query the Northwind database, returning the CategoryID, CategoryName, and number of products belonging to each category:

SELECT Categories.CategoryID, Categories.CategoryName, 
       COUNT(Products.ProductID) AS NumberOfProducts 

FROM Categories 
    INNER JOIN Products ON 
        Categories.CategoryID = Products.CategoryID 

GROUP BY Categories.CategoryID, Categories.CategoryName
ORDER BY Categories.CategoryName


This query uses the GROUP BY clause to return the count of products associated with each category. See Using the GROUP BY Clause for more information on this SQL clause.

The tag cloud is outputted in the Web page via a Literal Web control named CloudMarkup. In code we're going to loop through the database results, compute the font size scale, and then emit an HTML hyperlink as markup into the Text property of the Literal control. To start, we need to get the data from the SqlDataSource control. This is accomplished by calling its Select() method, which returns a DataView object:


'First, read data from SqlDataSource
Dim cloudData As DataView = CType(CategoriesProductsBreakdownDataSource.Select(DataSourceSelectArguments.Empty), DataView)

Next, a series of constants are defined in an attempt to generalize this code at least a little bit. For example, there are constants that define the names of the database columns that return the weight, the text field to display, along with the field to use (and a format string) when constructing the URL for each hyperlink. You'll also find the set of font sizes and the markup to inject between each link.


Const SpacerMarkup As String = " " 'The markup injected between each item in the cloud
Dim FontScale() As String = {"xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large"}

'All database column names are centralized here. To customize this, simply modify the column names here
Const WeightColumnName As String = "NumberOfProducts"
Const TextColumnName As String = "CategoryName"
Const NavigateUrlColumnName As String = "CategoryID"
Const NavigateUrlFormatString As String = "~/ViewProductsByCategory.aspx?CategoryID={0}"
Next, we need to determine the minimum and maximum weight values in the list. This information is then used to compute the linear scale by which we'll map an item's weight to a font size. The scaleUnitLength holds the "length" of each notch on the scale.

Dim minWeight As Decimal = Decimal.MaxValue, maxWeight As Decimal = Decimal.MinValue

For Each row As DataRowView In cloudData
    Dim numProductsObj As Object = row(WeightColumnName)
    If Not Convert.IsDBNull(numProductsObj) Then
       Dim numProductsDec As Decimal = Convert.ToDecimal(numProductsObj)

       If numProductsDec < minWeight Then minWeight = numProductsDec
       If numProductsDec > maxWeight Then maxWeight = numProductsDec
    End If
Next

Dim scaleUnitLength As Decimal = (maxWeight - minWeight + 1) / Convert.ToDecimal(FontScale.Length)

After computing the scale, the data is enumerated one more time, this time with a hyperlink element emitted for each record. To find the place on the scale, the current item's weight is subtracted from the minimum and divided by scaleUnitLength. This index is used to select the appropriate font size from FontScale. Also note that the specified values for NavigateUrlColumnName and NavigateUrlFormatString are used to configure the href portion of the hyperlink.

For Each row As DataRowView In cloudData
    Dim numProductsObj As Object = row("NumberOfProducts")
    If Not Convert.IsDBNull(numProductsObj) Then
       Dim numProductsDec As Decimal = Convert.ToDecimal(numProductsObj)

       Dim scaleValue As Integer = Math.Truncate((numProductsDec - minWeight) / scaleUnitLength)
       CloudMarkup.Text &= String.Format("<a href=""{0}"" style=""font-size:{1};"">{2}</a>{3}", _
                                    Page.ResolveUrl(String.Format(NavigateUrlFormatString, row(NavigateUrlColumnName).ToString())), _
                                    FontScale(scaleValue), row(TextColumnName).ToString(), SpacerMarkup)
    End If
Next

That's all there is to it! The resulting output is a chunk of HTML that, when rendered in the user's browser, lists each category as a hyperlink pointing to ViewProductsByCategory.aspx?CategoryID=categoryID. Each link's text size is based on its weight using a linear scale. The following screenshot below shows a tag cloud of the Northwind database's categories table along with the raw data used to populate the cloud.