Showing posts with label Web Services. Show all posts
Showing posts with label Web Services. Show all posts

Friday, April 12, 2013

How to return JSON string from ASP.NET WebMethod

Recently i worked with making some ajax calls to the server. There we need to get the response from the server as a JSON string. I have used two ways of returning a JSON string from a ASP.NET WebMethod.

Method 1 - Uses the JavaScriptSerializer

[WebMethod]
public string GetLankanList()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Lankans> lankanList = new List<Lankans>();
string[] names = { "chamara", "janaka", "asanka" };

for (int i = 0; i < names.Length; i++)
{
Lankans srilankans = new Lankans();
srilankans.Name = names[i];
lankanList.Add(srilankans);
}
string jsonString = serializer.Serialize(lankanList);
return jsonString;
}

Method 2 - Uses ScriptMethod with the WebMethod

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public string getData() 
{ 
 try 
 { 
 string name="chamara";
return name; 
 } 
 catch (Exception ex) { 
 throw ex; 
 } 
 }

Sunday, March 24, 2013

Using the jQuery $.ajax() Method in a Web Forms Application

The WCF service that converts temperature values between Celsius and Fahrenheit is shown below.

namespace AjaxWebForm
{
[DataContract]
public class TemperatureData
{

[DataMember]
public decimal Value { get; set; }
[DataMember]
public string Unit { get; set; }

}

[ServiceContract]

public interface IService
{
[OperationContract]

[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
TemperatureData Convert(TemperatureData t);
}

public class Service : IService
{
public TemperatureData Convert(TemperatureData t)
{
if (t.Unit == "C")
{
t.Value = (t.Value * 1.8m) + 32;
t.Unit = "F";
}

else
{
t.Value = (t.Value - 32) / 1.8m;
t.Unit = "C";
}

return t;
}
}
}

The TemperatureData class represents the data contract of the WCF service and contains two data member properties: Value and Unit. The IService interface represents a service contract for the service and defines a single method Convert(). The Convert() method accepts a TemperatureData object and returns a TemperatureData object after converting the temperature value to the other scale.

Notice that Convert() is decorated with an [WebInvoke] attribute. Due to this attribute, Convert() becomes callable from the client-side jQuery code. The RequestFormat and ResponseFormat properties of the [WebInvoke] attribute specify JSON as the communication format during request and response, espectively. The Method property specifies that Convert() can be invoked by HTTP POST requests. The Service class implements Convert(). The Convert() method checks the Unit of the incoming TemperatureData object and, depending on the Unit, converts the Value to the other scale.

The Service class’s Convert() method can be called using jQuery’s $.ajax() function as shown below
Using $.ajax() to Call the WCF Service Convert() Method

$(document).ready(function () {
$("#Button1").click(function () {
url = "Service.svc/Convert";
data = '{"Value":"' + $("#Text1").val() + '","Unit":"' + $("#Select1").val() + '"}';
$.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
})
});
});

The Convert button’s click event handler contains the jQuery code for invoking the Convert() method. The $.ajax() function has many configurable settings. The url setting allows you to specify the remote resource URL. For a WCF service, the URL takes the form <path_to_svc_file>/<method_name>.

The type option lets you specify the HTTP request type to be used while making the request. The Convert() method is configured with the [WebInvoke] attribute to use a POST method, and hence type is POST. The data setting indicates the data to be sent to the server (if any) while making the call. Notice how data is captured in JSON format. A JSON object takes the form of key-value pairs: a key and its value are separated by a colon (:), and multiple key-value pairs are delimited by a comma (,).

The dataType setting governs the data type of the response (XML, JSON, and so on). Recollect that the [WebMethod] attribute specified ResponseFormat as JSON, so dataType here must be set to JSON to correctly process the data coming from the server.

If Convert() returns successfully, the function specified by the success option (OnSuccess) is called. If there is any error while calling the WCF service, a function specified by the error option (OnError) is called. The OnSuccess() function is where you process the data returned from the WCF service. OnSuccess() receives the return value of Convert() (the TemperatureData object) as a parameter. You can access its Value and Unit properties and display an alert box to the user.

In the OnError() function, you typically flag the error to the user or take some corrective action. OnError() receives an error object; you can display its status and statusText properties to the user. Figure shows a sample run of the Web Forms application.



Tuesday, March 5, 2013

How to bind data to a Jquery Mobile ListView

Below example uses an ASP.NET web service to bind data to a Jquery mobile ListView Control.

ASP.NET WebService: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;

namespace SimpleWebService
{

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string GetLankanList()
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<Lankans> lankanList = new List<Lankans>();
            string[] names = { "chamara", "janaka", "asanka" };

            for (int i = 0; i < names.Length; i++)
            {
                Lankans srilankans = new Lankans();
                srilankans.Name = names[i];

                lankanList.Add(srilankans);
            }

            string jsonString = serializer.Serialize(lankanList);
            return jsonString;
        }

        public class Lankans
        {
            public string Name { get; set; }
        }
    }
}

HTML MarkUp:

 <!DOCTYPE html> 
<html> 
    <head> 
    <title>Page Title</title> 
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.js"></script>
</head> 
<body> 
<div data-role="page" id="lankalistpage">
    <div data-role="header">
        <h1>Page Title</h1>
    </div><!-- /header -->

    <div data-role="content">   
        <div id="LankanLists"></div>        
    </div><!-- /content -->

    <div data-role="footer">
        <h4>Page Footer</h4>
    </div><!-- /footer -->
</div><!-- /page -->
<script src="lankanscript.js"></script>
</body>
</html>

Jquery Script:

$('#lankalistpage').live('pageshow',function(event){
    var serviceURL = 'service1.asmx/GetLankanList';

    $.ajax({            
            type: "POST",
            url: serviceURL,
            data: param="",
            contentType:"application/json; charset=utf-8",
            dataType: "json",
            success: successFunc,
            error: errorFunc
    });

    function successFunc(data, status){
        // parse it as object
        var lankanListArray = JSON.parse(data.d);

        // creating html string
        var listString = '<ul data-role="listview" id="customerList">';

        // running a loop
        $.each(lankanListArray, function(index,value){
         listString += '<li><a href="#" >'+this.Name+'</a></li>';
        });
        listString +='</ul>';



        //appending to the div
        $('#LankanLists').html(listString);

        // refreshing the list to apply styles
        $('#LankanLists ul').listview();
    }

    function errorFunc(){
        alert('error');
    }
});


Thursday, December 20, 2012

Elements of a Web Service

Interface definition
WSDL - Web Service description language.
- WSDL defines the interface of s particular web service.
- ie: Methods, return values, parameters, datatypes etc
Also describe the bindings of a web service.
- URL to find the web service at.
- Supported protocols to use for communication.
- Supported message formats.

Communication protocol
Almost universally HTTP, but doesn't have to be.

Message formats
SOAP 1.1, SOAP 1.2 or even CGI POST

Web Server (for hosting the web service)
.NET needs Microsoft's internet information server (IIS), although Mono is extending this to other web servers.

Tuesday, December 11, 2012

Get Client IP,Country and Code using WebService

To get the Client IP related information we can use a free webservice available here.
Add the webservice reference to your project and add the below method.


private void GetUserIP()
{
string UIP= Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Request.ServerVariables["REMOTE_ADDR"];
net.webservicex.www.GeoIPService myProxy = new net.webservicex.www.GeoIPService();
List<net.webservicex.www.GeoIP> resultList = new List<net.webservicex.www.GeoIP>();
resultList.Add(myProxy.GetGeoIP(UIP));
Response.Write("User IP: " + UIP + "<br/>");
Response.Write("Country Name: "+resultList[0].CountryName+"<br/>");
Response.Write("Country Code: " + resultList[0].CountryCode);
}

Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Request.ServerVariables["REMOTE_ADDR"];

This will get the ip address of the client.

net.webservicex.www.GeoIPService myProxy = new net.webservicex.www.GeoIPService()
Create an object from the webservice reference.

List<net.webservicex.www.GeoIP> resultList = new List<net.webservicex.www.GeoIP>()
Get an IEnumerable type of result.

myProxy.GetGeoIP(UIP)
Pass the user IP address.

Below Code will Print the User IP Country name and Code.

Response.Write("User IP: " + UIP + "<br/>");
Response.Write("Country Name: "+resultList[0].CountryName+"<br/>");
Response.Write("Country Code: " + resultList[0].CountryCode);


Output:
User IP: 61.245.168.13
Country Name: Sri Lanka
Country Code: LKA

Wednesday, December 5, 2012

Download files from a remote server folder using a Web-service

This Post is related to my article on Code project.

Introduction
This is a very basic article which describes how to develop a simple application to download files from a folder in a remote server.

Background
I'm using VS 2010 and a Web service to develop the application.
Using the code

First create a new website in VS 2010 and add a web-service. Then add the following Web methods to your web-service.


[WebMethod()]
public void DownloadToBrowser(string fileName)
 {
FileInfo file = new FileInfo(@"D:\DOCS\"+fileName);
Context.Response.Clear();
Context.Response.ClearHeaders();
 Context.Response.ClearContent();
Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); Context.Response.AddHeader("Content-Length", file.Length.ToString());
Context.Response.ContentType = "text/plain"; Context.Response.Flush(); Context.Response.TransmitFile(file.FullName); Context.Response.End();
}

[WebMethod()]
public string[] GetFiles()
{
string[] Files = Directory.GetFiles(@"D:\DOCS\"); return Files;
 }

D:\DOCS\ is the folder where the files reside in the remote server. Now add the Web-Service reference to your website and design your web form markup as follows:

<form id="form1" runat="server">
    <div>
       <asp:Button ID="btnsearch" runat="server" Text="Search"
            onclick="btnsearch_Click" />
        <asp:TextBox ID="txtSearch" runat="server"
            Height="23px" Width="201px"></asp:TextBox>
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server"
                       AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Existing Files">
                <ItemTemplate>
                 <asp:LinkButton ID="lbtnDownload"
                    Text='<%# Eval("FileName")%>' runat="server"
                    OnCommand ="lbtnDownload_Click"
                    CommandArgument='<%# Eval("FileName")%>'></asp:LinkButton>
                 </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
</form>

Now you will see the interface with a Search button and a TextBox. You need to type the name of the file that you need to download in the TextBox and hit Search. Related documents will be added to the GridView. Add the following code to the search button click:

protected void btnsearch_Click(object sender, EventArgs e)
{
   FileSearchWebService FSW = new FileSearchWebService();
   string[] filePaths = FSW.GetFiles().AsEnumerable().Where(r=>r.Contains(txtSearch.Text)).ToArray();

   DataTable DT = new DataTable();
   DataColumn auto = new DataColumn("FileName", typeof(System.String));
   DT.Columns.Add(auto);
   foreach (string item in filePaths)
   {
       DT.Rows.Add(Path.GetFileName(item.ToString()));
   }
    GridView1.DataSource = DT;
    GridView1.DataBind();
}

Now you need to call the web-service with the link button Click event to download the file. Then Run the application and see how it works

protected void lbtnDownload_Click(object sender, CommandEventArgs e)
{
    FileSearchWebService FSW = new FileSearchWebService();
    FSW.DownloadToBrowser(e.CommandArgument.ToString());
}

Sunday, December 2, 2012

Object reference not set to an instance of an object: When using Session in WebMethod

The exception "Object reference not set to an instance of an object" could occur when you are trying to use a session variable within a WebMethod in a ASP.NET WebService.

An example would be as below


[WebMethod]
    public string HelloWorldGetName() {

        Session["name"] = "xx";
        string a = Session["name"].ToString();
        return a;

    }

This method will throw the above exception. To avoid the error you need to enable session state inside WebMethod


[WebMethod(EnableSession=true)]
    public string HelloWorldGetName() {

        Session["name"] = "xx";
        string a = Session["name"].ToString();
        return a;

    }

If you do not want to use Sessions inside the WebMethod then leave it as default. Default setting is EnableSession=false.

If you Enable Session state WebMethod would be bit more time consuming when it comes to the method execution.