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;
        }
























Friday, October 21, 2011

Step 4 : From SOAP to WCF-RESTful-DELETE


SOAP :



[WebMethod(Description = "Method to Delete User")]
public bool DeleteUser(string username)
{
   bool returnBool = false;
   SqlConnection dbConn = new SqlConnection(connStr);
   string sqlStr = "DELETE FROM users where username = '" + username +"';";
   SqlCommand dbCommand = new SqlCommand(sqlStr,dbConn);
try
{
   dbConn.Open();
   if (dbCommand.ExecuteNonQuery()!=0)
   {
      returnBool=true;
   }
}
catch
{
   returnBool=false;
}
   dbConn.Close();
   return returnBool;
}




WCF REST :


        [OperationContract]
        [WebInvoke(Method = "DELETE",
            ResponseFormat = WebMessageFormat.Xml,
            RequestFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "usrdel/{user}")]
        bool DeletePerson(string user);


        public bool DeletePerson(string user)
        {
            bool returnBool = false;
            SqlConnection dbConn = new SqlConnection(connStr);
            string sqlStr = "DELETE FROM users where username = '" + user + "';";
            SqlCommand dbCommand = new SqlCommand(sqlStr, dbConn);
            try
            {
                dbConn.Open();
                if (dbCommand.ExecuteNonQuery() != 0)
                {
                    returnBool = true;
                }
            }
            catch
            {
                returnBool = false;
            }
            dbConn.Close();
            return returnBool;
        }



Step 3 : From SOAP to WCF-RESTful-GET



Step 3 : From SOAP to WCF-RESTful-GET

Google Docs PDF :
https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0BzKVfKe--t_cZjM4YWU2NWMtZDQ3Yy00ZWZmLTgyYWYtZDQyM2EzN2EzYjVk&hl=en_GB


SOAP :
[WebMethod]
public List GetPersonList()
{
   SqlConnection dbConn = new SqlConnection(connStr);
   dbConn.Open();
   string sqlSelect = "select * from users ";
   SqlDataAdapter da = new SqlDataAdapter(sqlSelect, dbConn);
   DataTable dt = new DataTable();
   SqlCommand dbCommand = new SqlCommand(sqlSelect, dbConn);
   da.Fill(dt);
   dbConn.Close();
   List myList = new List();
   foreach (DataRow row in dt.Rows)
   {
      Person target = new Person();
      target.Name = row["Name"].ToString();
      target.UserName = row["UserName"].ToString();
      target.EMail = row["EMail"].ToString();
      target.Password = row["Password"].ToString();
      myList.Add(target);
   }
   return myList;
}



public class Person
{
private string _name = string.Empty;
private string _user_name = string.Empty;
private string _eMaiL = string.Empty;
private string _password = string.Empty;
public Person() {}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Password
{
get { return _password; }
set { _password = value; }
}
public string UserName
{
get { return _user_name; }
set { _user_name = value; }
}
public string EMail
{
get { return _eMaiL; }
set { _eMaiL = value; }
}
}


WCF REST : getAllPersons

[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "xml/getallpersons")]
PersonData[] getAllPersons();

[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[] getAllPersons()
{
SqlConnection dbConn = new SqlConnection(connStr);
dbConn.Open();
string sqlSelect = "select * from users ";
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, dbConn);
DataTable dt = new DataTable();
SqlCommand dbCommand = new SqlCommand(sqlSelect, dbConn);
da.Fill(dt);
dbConn.Close();
List<PersonData> list = new List<PersonData>();
foreach (DataRow row in dt.Rows)
{
// Person target = Activator.CreateInstance();
PersonData target = new PersonData();
target.Name = row["Name"].ToString();
target.User = row["UserName"].ToString();
target.Email = row["EMail"].ToString();
target.Password = row["Password"].ToString();
// DataColumnAttribute.Bind(row,target);
list.Add(target);
}
return list.ToArray();
}





http://192.168.61.3/RestServicePost/RestServiceImpl.svc/xml/getallpersons





VWD 2010 Express - full project : 
https://docs.google.com/leaf?id=0BzKVfKe--t_cMmUxYTlkY2UtZmIzOC00YjhjLWExN2MtNDk3MWFhNDQ4ZWY0&hl=en_GB






http://192.168.61.3/RestServicePost/RestServiceImpl.svc/json/getallpersons

More about JSON part of the RESTful WebService on :

Step 8 : WCF RESTful GET JSON List with FIDDLER



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


Step 1 : From SOAP to WCF REST without LINQ



From SOAP to WCF REST without LINQ : small and easy steps
with sample code  


For my goal I don't must have a license of the full Visual Studio ;
I'm OK with Visual Web Developer 2010 Express .

RESTful webservices are a lot easier to consume on Android than SOAP ;
So let's see the small steps from a simple SOAP webservice to a RESTful one :

The initial SOAP method is called ReturnEmail :
 - requested parameter is a username ;
 - returned value is the appropiate email address retrieved from an SQLS DB without LINQ ;

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

public class PersonPassport2 : WebService
{
const string connStr = "server=localhost;uid=sa;pwd=kash;database=minipassport";


[WebMethod(Description = "Method to obtain User Email Address")]
public string ReturnEmail(string username)
{
SqlConnection dbConn = new SqlConnection(connStr);
string sqlStr = "Select email from users where username = '" + username + "';";
dbConn.Open();
SqlCommand dbCommand = new SqlCommand(sqlStr,dbConn);
SqlDataReader dbReader = dbCommand.ExecuteReader();
dbReader.Read();
string _name = dbReader[0].ToString();
dbReader.Close();
dbConn.Close();
return _name;
}


}


The final WCF REST webservice method using WebInvoke - GET :

    [ServiceContract]
    public interface IRestServiceImpl
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "xml/{user}")]
        string ReturnEmail(string user);
    }


   public class RestServiceImpl : IRestServiceImpl
    {
     const string connStr = "server=localhost;uid=sa;pwd=kash;database=minipassport";
     public string ReturnEmail(string user)
        {
            SqlConnection dbConn = new SqlConnection(connStr);
            string sqlStr = "Select password from users where username = '" + user + "';";
            dbConn.Open();
            SqlCommand dbCommand = new SqlCommand(sqlStr, dbConn);
            SqlDataReader dbReader = dbCommand.ExecuteReader();
            dbReader.Read();
            string _name = dbReader[0].ToString();
            dbReader.Close();
            dbConn.Close();
            return _name;
        }
}

How to invoke the WCF REST webservice method :
http://localhost/RestServicePost/RestServiceImpl.svc/xml/user1

and the result is :



GET with FIDDLER (click to zoom) :




# 73 - Migrating from .asmx web services to WCF web services



http://www.dimecasts.net/Casts/CastDetails/73



12/26/2008
Level: Intermediate
Tags: WCF
Comments: (12)
Author:
Donn Felker

In this episode we will walk you though the process of converting your company from using .asmx services over to wcf services.


The focus of this episode is how you can setup your environment to support both types of services and use the same back end. This will allow you to slowly convert over any consumers from .asmx to wcf.
Click here to Watch this Episode


Download (12.76 MB) (8:02) (1440x900)
Download (9.15 MB) (8:02) (960x600)

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;
        }