Wednesday 11 December 2013

Pass json string data to Rest service (POST Method) using c#

Save Rescords with Rest Service POST Method in WCF Application using VS2008

Step 1 : Create a new WCF Service Application Project

Step 2 : Delete default service files like Service.svc & IService.cs

Step 3 : Then Add new WCF Service file. I added in the file name as RestServiceImpl.svc. Automatically                  IRestServiceImpl.cs file will be added.



Step 4 :  Open RestServiceImpl.cs file and also IRestServiceImpl.cs. In both files add the following codes                   respectively.

In RestServiceImpl.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace SampleRest
{
    // NOTE: If you change the class name "RestServiceImpl" here, you must also update the reference to "RestServiceImpl" in Web.config.
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class RestServiceImpl : IRestServiceImpl
    {
        string conStr = ConfigurationManager.ConnectionStrings["connRest"].ConnectionString;

        public string EchoWithGet(string s)
        {
            return "You said " + s;
        }

        public string EchoWithPost(string s)
        {
            return "You said " + s;
        }

        public string GetJSonString(jSonStr jsonData)
        {
            if (!string.IsNullOrEmpty(jsonData.jsonStr))
                return SaveJsontoDB(jsonData.jsonStr);
            else
                return "{\"success\":false}";
        }

        public string GetJSonData(jsonDataCollection jsonData)
        {            
            var res =JsonConvert.SerializeObject(jsonData);
            return SaveJsontoDB(res);
        }

        private string SaveJsontoDB(string oJson)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"jsonResult\":[{");

            using (SqlConnection con = new SqlConnection(conStr))
            {
                con.Open();
                var jSonData = serializer.Deserialize<jsonDataCollection>(oJson);
                foreach (var data in jSonData.jsonData)
                {
                    string query = "iPad_InsertLogDetails";
                    using (SqlCommand cmd = new SqlCommand(query, con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@iUserId", data.user_Id);
                        cmd.Parameters.AddWithValue("@iAppId", data.app_id);

                        if (!string.IsNullOrEmpty(data.session_key) && data.session_key.Trim() != "")
                            cmd.Parameters.AddWithValue("@vSessionKey", data.session_key);

                        cmd.Parameters.AddWithValue("@vVersionName", data.app_version);

                        if (!string.IsNullOrEmpty(data.IPAddress) && data.IPAddress.Trim() != "")
                            cmd.Parameters.AddWithValue("@vIPAddress", data.IPAddress);

                        cmd.Parameters.AddWithValue("@iLogTypeID", data.log_typeId);
                        cmd.Parameters.AddWithValue("@iLogDesc", data.log_description);
                        cmd.Parameters.AddWithValue("@bIsOnline", data.app_isOnline);

                        try
                        {
                            cmd.ExecuteNonQuery();                            
                            sb.Append("{\"success\": true},");
                        }
                        catch (Exception ex)
                        {                            
                           // sb.Append("{\"log_Id\":" + Convert.ToString(data.log_Id) + ",\"success\":false,\"Error\":\"" + ex.Message.ToString() + "\"},");
                            sb.Append("{\"log_Id\":" + Convert.ToString(data.log_Id) + ",\"success\":false},");
                        }
                        cmd.Dispose();
                    }
                }
            }

            //sb.ToString().TrimEnd(',');
            sb.Remove(sb.Length - 1, 1);
            sb.Append("}]}");
            return JsonConvert.SerializeObject(sb.ToString());            
        }

        public class jsonDataResult
        {           
            public IEnumerable<Dictionary<string,object>> jsonResult { get; set; }
        }       
    }

}

And In IRestServiceImpl.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace SampleRest
{
    // NOTE: If you change the interface name "IRestServiceImpl" here, you must also update the reference to "IRestServiceImpl" in Web.config.
    //[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceContract]
    public interface IRestServiceImpl
    {     
        [OperationContract]           
        [WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Xml,BodyStyle = WebMessageBodyStyle.Wrapped,UriTemplate = "/EchoWithGet/{s}")]
        string EchoWithGet(string s);

        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/EchoWithPost/{s}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, 
            BodyStyle = WebMessageBodyStyle.Wrapped)]
        string EchoWithPost(string s);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/GetJSonData", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, 
            BodyStyle = WebMessageBodyStyle.Bare)]
        string GetJSonData(jsonDataCollection jsonData);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/GetJSonString", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, 
            BodyStyle = WebMessageBodyStyle.Bare)]
        string GetJSonString(jSonStr jsonStr);
    }

    [DataContract]
    public class jsonDataCollection
    {
        [DataMember]
        public IEnumerable<jSonData> jsonData { get; set; }
    }

    [DataContract]
    public class jSonData
    {
        [DataMember]
        public int log_Id { get; set; }

        [DataMember]
        public int user_Id { get; set; }

        [DataMember]
        public int app_id { get; set; }

        [DataMember]
        public string session_key { get; set; }

        [DataMember]
        public string app_version { get; set; }

        [DataMember]
        public string IPAddress { get; set; } 

        [DataMember]
        public int log_typeId { get; set; }

        [DataMember]
        public string log_description { get; set; }

        [DataMember]
        public bool app_isOnline { get; set; }

        [DataMember]
        public string app_dateTimeZone { get; set; }        
    }

    [DataContract]
    public class jSonStr
    {
        [DataMember]
        public string jsonStr { get; set; }
    }

}

Step 5 : After create this code add Newtonsoft.Json file in your bin folder and add reference to your project.

           Go to this link http://json.codeplex.com/ then choose downloads tab. Here you found file download link.

Step 6 : Working with rest service you have to change your web.config file.

   If you add any WCF Service file automatically service behavior created under Service Model. You slightly alter the code work with Rest service. 

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service behaviorConfiguration="SampleRest.RestServiceImplBehavior" name="SampleRest.RestServiceImpl">
        <endpoint address="http://localhost/RestServiceImpl.svc" binding="webHttpBinding" contract="SampleRest.IRestServiceImpl" behaviorConfiguration="Web">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors> 
      <serviceBehaviors>
        <behavior name="SampleRest.RestServiceImplBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="Web">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

In default endpoint binding should be in webHttpBinding. We need to alter this like webHttpBinding and then add endpointBehaviors tag under behavior. 

Step 7 : Now add new Web Application project.

Step 8 : In deault page add the following code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SampleRestWeb._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" Height="150" Width="300" TextMode="MultiLine"></asp:TextBox>
    </div>
    </form>
</body>
</html>

and in Default.aspx.cs page add the below code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
//using HttpUtils;
using System.Web.UI.MobileControls;
using RestSharp;
using System.Web.Script.Services;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SampleRestWeb.ServiceReference1;
using System.Data.SqlClient;

namespace SampleRestWeb
{
    public partial class _Default : System.Web.UI.Page
    {
        jSonStr ojsonStr = new jSonStr();
        jsonDataCollection ojSonDataCol = new jsonDataCollection();

        protected void Page_Load(object sender, EventArgs e)
        {
            string jsonString = "{\"jsonData\":[{"
                        + "\"log_Id\" : 0,"
                        + "\"user_Id\" : 1249,"
                        + "\"session_key\" : \"dvnoewcdw\","
                        + "\"app_id\" : 1,"
                        + "\"app_version\" :\"1.2.7\","
                        + "\"app_isOnline\" : true,"
                        + "\"app_dateTimeZone\" : \"1997-07-16T19:20:30+01:00\","
                        + "\"log_typeId\" : 1,"
                        + "\"log_description\" : \"valid\"}"
                    + ",{"
                        + "\"log_Id\" : 1,"
                        + "\"user_Id\" : 1249,"
                        + "\"session_key\" : \"dvnoewcdw\","
                        + "\"app_id\" : 1,"
                        + "\"app_version\" : \"1.2.7\","
                        + "\"app_isOnline\" : true,"
                        + "\"app_dateTimeZone\" : \"1997-07-16T19:20:30+01:00\","
                        + "\"log_typeId\" : 2,"
                        + "\"log_description\" : \"syncing permissions successful\"}]}";
            
            const string url = "http://localhost:1307/RestServiceImpl.svc/";

            JavaScriptSerializer serializer = new JavaScriptSerializer(); 
            try
            {
                var client = new RestClient();
                // This, of course, needs to be altered to match the
                // IP Address/Port of the server to which you are connecting
                client.BaseUrl = url;
                var request = new RestRequest();
                //request.AddHeader("Content-Length", int.MaxValue.ToString());
                request.Method = Method.POST;
                request.RequestFormat = DataFormat.Json;               
                
                //Pass collection Data  Method 1
                ojSonDataCol = serializer.Deserialize<jsonDataCollection>(jsonString);
                request.AddBody(ojSonDataCol);
                request.Resource = "/GetJSonData";                 
                               
                //request.Resource = "/EchoWithGet/test"; 

                //Pass String Data Method 2
               // If you enable Method 2 comment Method 1 codes
                //ojsonStr.jsonStr = jsonString;
                //request.AddBody(ojsonStr);
                //request.Resource = "/GetJSonString";           
                
                // The server's Rest method will probably return something 
                var response = client.Execute(request) as RestResponse;
                
                if (response != null && ((response.StatusCode == HttpStatusCode.OK) &&
                 (response.ResponseStatus == ResponseStatus.Completed))) // It's probably not necessary to test both
                {                    
                    var obj = response.Content;
                    var res = JsonConvert.DeserializeObject(obj);
                    Response.Write(response.Content);                    
                }
                else if (response != null)
                {
                    Response.Write(string.Format
                    ("Status code is {0} ({1}); response status is {2}",response.StatusCode, response.StatusDescription, response.ResponseStatus));
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
}

Step 9 : Download restsharp dll file under add it in your web project bin folder, then add reference into your project and also add Newtonsoft.json reference into your web project.

 Download the restsharp dll in https://github.com/restsharp/RestSharp/downloads (Please download latest version)

Step 10:  Now Add WCF Service reference into your web project. The project flow will be look like as








6 comments:

  1. I want to download the code how can i? please guide ....

    ReplyDelete
  2. how to download this code please guide.....

    ReplyDelete
  3. I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in Windows foundation communication, kindly contact us http://www.maxmunus.com/contact
    MaxMunus Offer World Class Virtual Instructor led training on Windows foundation communication. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
    For Demo Contact us:
    Name : Arunkumar U
    Email : arun@maxmunus.com
    Skype id: training_maxmunus
    Contact No.-+91-9738507310
    Company Website –http://www.maxmunus.com



    ReplyDelete
  4. It isn't difficult to do something about the four panel drug test with the ideal comprehension and internet help.If you are curious to know more about marijuana cleansing drinks, here you can get more information about it.

    ReplyDelete
  5. There are two main ways to develop your body's system to get stronger and healthier. Your first option is to simply eat healthier foods, which are often more nutritious and natural. For more information on testosterone booster supplements visit this site right here.

    ReplyDelete
  6. Some of the different products they offer may contain the same ingredients or the same ingredient together with a combination of other herbal ingredients. Check out this site to know more about best synthetic urine brand review.

    ReplyDelete