Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts

Friday, November 4, 2011

ToDo : Android WCF adapter class

How to manipulate a  RESTful WCF Web Service in Android


after 9 steps of simple WCF samples 
Step 9 : Android Client reading JSON WCF REST
Step 8 : WCF RESTful GET JSON List with FIDDLER
it's time to incorporate them all in a single class called WCFadapter ... 

On the model of DBAdapter in the article Creating and Using Databases in Android
it's interesting to crate a similar class named WCFadapter ... 


It's also useful these samples : 

Building an Android Application in 6 Steps

Friday, October 28, 2011

Step 7 : POST data from JSON Android Client to WCF REST WebService

POST JSON data from an Android Client to a WCF RESTful WebService

The full Android.java source code is on Google Code :
http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/src/net/learn2develop/AndroidViews/

The full Eclipse Indigo 3.7 - Android  project zipped on Google Docs :
https://docs.google.com/leaf?id=0BzKVfKe--t_cMDU5OTU5MDQtNDQzOC00YjE3LTlhODgtYjE1ZDhmZWFmZjc1&hl=en_GB


All files of the WCF RESTful Web Service are also on Google Code :
http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/RestService

The full Visual Web Developer project -  VWD  Express 2010 also on Google Docs :
https://docs.google.com/leaf?id=0BzKVfKe--t_cODIwZWE2M2QtZTUwMy00Yjg1LTljMjUtYTA3MGI4YmM5OGZm&hl=en_GB

First we tried to post XML formatted data to a WCF Web Service with FIDDLER ( step 5 ) :
http://pantestmb.blogspot.com/2011/10/pass-multiple-body-parameters-wcf-rest.html

Then tried to post JSON data to a WCF Web Service with FIDDLER ( step 6 ) :
http://pantestmb.blogspot.com/2011/10/wcf-rest-fiddler-json-request-body.html

Now , knowing that the WCF Web Service responds OK with both XML and JSON ,
we can take our simple sample project to the ANDROID Client Test :


http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/src/net/learn2develop/AndroidViews/SavePerson.java

package net.learn2develop.AndroidViews;


import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
// import org.json.JSONObject;
import org.json.JSONStringer;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class SavePerson extends Activity {

private final static String SERVICE_URI = "http://192.168.61.3/RestServicePost/RestServiceImpl.svc";

@Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       setContentView(R.layout.main);
       // String plate = new String("test");
       // POST request to
            HttpPost request = new HttpPost(SERVICE_URI + "/json/adduser");
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-type", "application/json");
         
            String not = new String(" ");
            try {
            // Build JSON string
            JSONStringer vehicle = new JSONStringer()
                .object()
                    .key("rData")
                        .object()
                            .key("details").value("bar|bob|b@h.us|why")
                        .endObject()
                    .endObject();
         
            StringEntity entity = new StringEntity(vehicle.toString());
         
            Toast.makeText(this, vehicle.toString() + "\n", Toast.LENGTH_LONG).show() ;
         
            request.setEntity(entity);
         
            // Send request to WCF service
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(request);
            // Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode());
            Toast.makeText(this, response.getStatusLine().getStatusCode() + "\n", Toast.LENGTH_LONG).show() ;
         
            }catch (Exception e) {
            not = "NOT ";
            }
         
            Toast.makeText(this, not + " OK ! " + "\n", Toast.LENGTH_LONG).show() ;
         
         

}  
}


http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/RestService/IRestServiceImpl.cs


      [OperationContract]
        [WebInvoke(Method = "POST",
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "json/adduser")]
        PersonData AddJsonUser(RequestData rData);

In our simple example we create a JSONStringer object with "rData" key and "details" sub-key ;
      "rData" is the variable of the function "AddJsonUser" ;
"details" is the single property of the object "RequestData" :
 http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/RestService/RequestData.cs


    [DataContract(Namespace = "")]
    public class RequestData
    {
        [DataMember]
        public string details { get; set; }
    }





The string  "bar|bob|b@h.us|why" of the JSONStringer is hard-coded to simplify things ;
After being parsed - it ends up in the SQLS table "Users" : 





http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/RestService/RestServiceImpl.svc.cs
AddUser is the function triggered by the POST WCF Webservice
http://192.168.61.3/RestServicePost/RestServiceImpl.svc/json/adduser
with a JSON request body -  JSONStringer vehicle : 


        public PersonData AddUser(RequestData rData)
        {
            bool returnBool = false;

            var data = rData.details.Split('|');
            var response = new PersonData
            {
                Name = data[0],
                User = data[1],
                Email = data[2],
                Password = data[3]
            };

            SqlConnection dbConn = new SqlConnection(connStr);
            string sqlStr = "INSERT INTO users(username,name,email,password)
                          values('" + data[0] + "', '" + data[1] + "', '" + data[2] + "', '" + data[3] + "');";
            SqlCommand dbCommand = new SqlCommand(sqlStr, dbConn);
            try
            {
                dbConn.Open();
                if (dbCommand.ExecuteNonQuery() != 0)
                {
                    returnBool = true;
                }
                dbConn.Close();
            }
            catch
            {
                returnBool = false;
            }
            return response;
        }

        public PersonData AddJsonUser(RequestData rData)
        {
            return AddUser(rData);
        }



~ ~ ~


the SQL Server Database has only one table - Users :

CREATE TABLE [dbo].[Users](
[UserName] [varchar](100) NOT NULL,
[Name] [varchar](100) NOT NULL,
[EMail] [varchar](100) NOT NULL,
[Password] [varchar](100) NOT NULL,


Wednesday, October 26, 2011

Step 6 : WCF REST & FIDDLER JSON - request body


WCF REST * FIDDLER JSON - request body , headers and content type : 



  [DataContract(Namespace = "")]
    public class PersonData
    {
        [DataMember]
        public string Name { get; set; }


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


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


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




    [OperationContract]
        [WebInvoke(Method = "POST",
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "jsontestpersondatapost")]
        PersonData JsonTestPersonDataPost(PersonData pd);





       public PersonData TestPersonDataPost(PersonData pd)
        {
            var response = new PersonData
            {
                Name = pd.Name,
                User = pd.User,
                Email = pd.Email,
                Password = pd.Password
            };
            
            return response;
            // return pd;
        }


        public PersonData JsonTestPersonDataPost(PersonData pd)
        { 
            return TestPersonDataPost(pd);
        }









POST http://192.168.61.3/RestServicePost/RestServiceImpl.svc/jsontestpersondatapost HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json
Host: 192.168.61.3
Content-Length: 86


{ "pd" : { "Email":"bo@se.us" , "Name":"amab" , "Password":"egti" , "User":"brac" } } 










HTTP/1.1 200 OK
Content-Length: 99
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.0
X-Powered-By: ASP.NET
Date: Wed, 26 Oct 2011 18:31:54 GMT


{"JsonTestPersonDataPostResult":{"Email":"bo@se.us","Name":"amab","Password":"egti","User":"brac"}}










Tuesday, October 25, 2011

Step 5 : Pass multiple body parameters in wcf rest



How pass multiple body parameters in wcf rest

using webinvoke method(Post or PUT)








Even If you have blank namespace  [DataContract(Namespace = "")] you have to put 
xmlns="" in the request body ... ( see the pictures below )
Whithout xmlns="" in the request body , problems can appear 






  [OperationContract]
        [WebInvoke(Method = "POST",
            ResponseFormat = WebMessageFormat.Xml,
            RequestFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "testpersondatapost")]
        PersonData TestPersonDataPost(PersonData pd);


  [DataContract(Namespace = "")]
    public class PersonData
    {
        [DataMember]
        public string Name { get; set; }

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

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

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


       public PersonData TestPersonDataPost(PersonData pd)
        {
            var response = new PersonData
            {
                Name = pd.Name,
                User = pd.User,
                Email = pd.Email,
                Password = pd.Password
            };
            
            return response;
            // return pd;
        }
























Wednesday, October 19, 2011

Step 2 : From SOAP to WCF-RESTful-POST

From SOAP to WCF-RESTful-POST

Simple step 2 :

http://pantestmb.blogspot.com/2011/02/personpassport4asmx.html

SOAP

[WebMethod(Description = "Method to Add User")]
public bool AddUser(string username, string password, string name, string email)
{
bool returnBool = false;
SqlConnection dbConn = new SqlConnection(connStr);
string sqlStr = "INSERT INTO users(username,password,name,email)
values('" + username + "', '" + password + "', '" + name + "', '" + email + "');";
SqlCommand dbCommand = new SqlCommand(sqlStr,dbConn);
try
{
dbConn.Open();
if (dbCommand.ExecuteNonQuery()!=0)
{
returnBool=true;
}
returnBool=true;
}
catch
{
returnBool=false;
}
dbConn.Close();
return returnBool;
}





WCF REST POST :





    [DataContract(Namespace = "")]
    public class RequestData
    {
        [DataMember]
        public string details { get; set; }
    }


    [DataContract]
    public class PersonData
    {
        [DataMember]
        public string Name { get; set; }


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


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


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







        public PersonData AddUser(RequestData rData)
        {
            bool returnBool = false;


            var data = rData.details.Split('|');
            var response = new PersonData
            {
                Name = data[0],
                User = data[1],
                Email = data[2],
                Password = data[3]
            };


            SqlConnection dbConn = new SqlConnection(connStr);
            string sqlStr = "INSERT INTO users(username,name,email,password)
                                values('" + data[0] + "', '" + data[1] + "', '" + data[2] + "', '" + data[3] + "');";

            SqlCommand dbCommand = new SqlCommand(sqlStr, dbConn);
            try
            {
                dbConn.Open();
                if (dbCommand.ExecuteNonQuery() != 0)
                {
                    returnBool = true;
                }
                returnBool = true;
            }
            catch
            {
                returnBool = false;
            }
            dbConn.Close();
            return response;
        }



the result on fiddler





the result on SQL Server DataBase



Full Code on Google.Docs :
https://docs.google.com/document/d/1H0d2gq22-SsTElxI_mBEdAiagEOQL4HPXLInDHLDorg/edit?hl=en_GB

~ a 7z file ~ Visual Web Developer Express 2010 ~ full project :
https://docs.google.com/leaf?id=0BzKVfKe--t_cYTc4MWZkZjMtM2VmYi00OWIyLWJkMDgtN2FmOWE0ZGM4YTY5&hl=en_GB

Dumped Database can be downloaded at :
https://docs.google.com/leaf?id=0BzKVfKe--t_cYjAzOTk5YmEtNjk1ZS00ZTcxLWIzMDgtYTMwMTVlMTQwZDVi&hl=en_GB


Tuesday, October 18, 2011

Create a POST to a REST WCF Service with Fiddler



How to POST to REST WCF web services with Fiddler

CREATE RESTful WCF Service API Using POST: Step By Step Guide

After making a set of REST web services with WCF I tested them by making requests with a browser. 
This is fine for GET requests however you will need some HTTP building tool such as Fiddler to test a POST, PUT or DELETE REST web service.

To begin with I have a WCF REST web service that intends for a RequestData object to be POSTed:

        [WebInvoke(Method = "POST",
            ResponseFormat = WebMessageFormat.Xml,
            RequestFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "auth")]
       ResponseData Auth(RequestData rData);


The definition of RequestData is very simple:



  public class RequestData
    {
        [DataMember]
        public string details { get; set; }
    }


The definition of ResponseData is quite simple:



public class ResponseData
    {
        [DataMember]
        public string Name { get; set; }


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


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


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


The function that gets RequestData and returns ResponseData : 


    public ResponseData Auth(RequestData rData)
        {
            var data = rData.details.Split('|');            
           var response = new ResponseData
                               {
                                   Name = data[0],
                                   Age = data[1],
                                   Exp = data[2],
                                   Technology = data[3]
                               };

            return response;
        }


Note this namespace is very important as it will need to be specified in the XML sent in the request. 
Personally I set my DataContract with no namespace to save having to write it out in the XML every time.

Now open up Fiddler and lets get testing:

Create a POST to your REST service in Fiddler
Go to the Request Builder tab in Fiddler.
Set the verb to POST
Set the URL to the one of your service
Type "Content-Type: application/xml" into the Request Headers. 
If you did give your DataContract a namespace other than blank as I did you will need to specify it in the XML of your Request Body. 
Add your XML to the Request Body like : 





The response : 




Comsuming WCF Services With Android

Create a Simple WCF service against Pubs Database using EF, LINQ



PersonPassport4.asmx - Simple webservice : INSERT UPDATE DELETE



RESTful ASP.NET WCF with SQLite without LINQ: 

  [ServiceContract]

    public interface IService1
    {

    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "Notes/{ID}")]
        [OperationContract]
        Note GetNote(string ID);

   [DataContract]
    public class Note
    {
         [DataMember]
        public int ID { get; set; }
        [DataMember]
        public string Category { get; set; }
        [DataMember]
        public string Subject { get; set; }
        [DataMember]
        public string NoteText { get; set; }
    }

      public Note GetNote(string ID)
        {
            string Sql = "SELECT * FROM NOTE WHERE ID=@ID";
            SQLiteCommand cmd = new SQLiteCommand(Sql, conn);
             cmd.Parameters.AddWithValue("@ID", int.Parse(ID));
            SQLiteDataAdapter da = new SQLiteDataAdapter(Sql, conn);
            da.SelectCommand = cmd;
            DataTable dt = new DataTable();
             da.Fill(dt);
            Note note=null;
            if (dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                note = new Note();
                note.ID = Convert.ToInt32(row["ID"]);
                note.Category = (string)row["Category"];
                note.Subject = (string)row["Subject"];
                note.NoteText = (string)row["NoteText"];
            }
    
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
             return note;
        }