Amazon Ad

Saturday 20 October 2012

REST Services With Phonegap Android

Hi Guys,

Hope you are doing fine. Today I am going to share how to work with WCF(REST Services) made in asp.net and connecting it with phonegap android app.

Here goes the step wise description

Step 1 :Create a WCF Webservice in asp.net name it Plumber.

Create a WCF webservice in a new asp.net web application. By default the service name is Service1.svc. Two files are created one is the interface and second is the implementation file.

In the interface i.e IService1.svc add the following lines


[OperationContract]
        [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "SearchWorkBook")]
        List<PlumberWork> SearchWorkBook(string PlumberId, string HouseNo,string PostCode,string BoilerCode);

In Service1.svc add the following method


public List<PlumberWork> SearchWorkBook(string PlumberId, string HouseNo,string PostCode,string BoilerCode)
        {
            if (con.State == System.Data.ConnectionState.Closed)
                con.Open();

            List<PlumberWork> list = new List<PlumberWork>();
            string query = "[pSearchWorkBook]";
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("@PlumberId", PlumberId);
            cmd.Parameters.AddWithValue("@HouseNo", HouseNo);
            cmd.Parameters.AddWithValue("@PostCode", PostCode);
            cmd.Parameters.AddWithValue("@BoilerCode", BoilerCode);

            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adapt = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();
            adapt.Fill(ds);
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                PlumberWork obj = new PlumberWork();
                obj.SerialNo = ds.Tables[0].Rows[i]["SerialNo"].ToString();
                obj.PostCode = ds.Tables[0].Rows[i]["PostCode"].ToString();
                obj.Notes = ds.Tables[0].Rows[i]["Notes"].ToString();
                obj.EntryDate = ds.Tables[0].Rows[i]["EntryDate"].ToString();
                list.Add(obj);
            }
            return list;
        }
   
After the class ends add another class


 public class PlumberWork
    {
        public string SerialNo{get;set;}
        public string PostCode{get;set;}
        public string Notes{get;set;}
        public string EntryDate { get; set; }
    }




Step 2: Configure the web.config.


    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>

    <system.serviceModel>
        <services>
            <service name="Plumber.Service1" behaviorConfiguration="ATServiceBehavior">
                <endpoint address="" binding="webHttpBinding" contract="Plumber.IService1" behaviorConfiguration="web" bindingConfiguration="RestServiceBindingConfig">
                </endpoint>
            </service>
        </services>
        <bindings>
            <webHttpBinding>
                <binding crossDomainScriptAccessEnabled="true" name="RestServiceBindingConfig">
                    <security mode="None"></security>
                </binding>
            </webHttpBinding>
        </bindings>
        <behaviors>
            <serviceBehaviors>
                <behavior name="ATServiceBehavior">
                    <serviceMetadata httpGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="true" />
                </behavior>
            </serviceBehaviors>
            <endpointBehaviors>
                <behavior name="web">
                    <webHttp defaultOutgoingResponseFormat="Json" helpEnabled="true"/>
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>


Step 3: Create global.asax file for cross domain ajax configuration.

Add the following in your Application_BeginRequest


protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
             
                //For GET
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                //For POST
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");

                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }

       
        }


Step 4: Publish it on IIS.
Step 5: Create a phonegap application.
Step 6: Call WCF service using jquery ajax.


 function searchwork()
        {
            var servicepath = "http://IP_Address_Of_Computer_Hosting(IIS)/PlumberService/";
            var PlumberId="13";
            var HouseNo = "EA 3772";
            var PostCode = "L1A89A";
            var BoilerCode = "B9022A33A";

            alert('{"PlumberId":"' + PlumberId + '","HouseNo":"' + HouseNo + '","PostCode":"' + PostCode + '","BoilerCode":"'+BoilerCode+'"}');
            $.ajax({
                data: '{"PlumberId":"' + PlumberId + '","HouseNo":"' + HouseNo + '","PostCode":"' + PostCode + '","BoilerCode":"' + BoilerCode + '"}',
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                url: servicepath + "PlumberService.svc/SearchWorkBook",
                success: function (data) {
                    for (i = 0; i < data.SearchWorkBookResult.length; i++) {
                        document.write("<br>");
                        document.write(data.SearchWorkBookResult[i].SerialNo);
                        document.write(data.SearchWorkBookResult[i].make);
                        document.write(data.SearchWorkBookResult[i].model);
                        document.write(data.SearchWorkBookResult[i].installationdate);
                        document.write(data.SearchWorkBookResult[i].gcnumber);
                        document.write(data.SearchWorkBookResult[i].gascertificateexpirydate);
                        document.write(data.SearchWorkBookResult[i].HouseNo);
                        document.write(data.SearchWorkBookResult[i].PostCode);
                        document.write(data.SearchWorkBookResult[i].Notes);
                        document.write(data.SearchWorkBookResult[i].EntryDate);
                    }
                },
                error: function (a, e, d) { alert(e + ' ' + d); }
            });
        }


Hope you enjoyed, Please do give your comments.

Thanks
Ritesh Tandon

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...