Click here to Skip to main content
13,589,969 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

13.9K views
16 bookmarked
Posted 13 Apr 2017
Licenced CPOL

Calling Web Services Programmatically Using C#.NET or Xamarin App Development

, 15 Apr 2017
Rate this:
Please Sign up or sign in to vote.
How to call and consume Web Services programmatically using C#.NET

Introduction

This article is very useful for those of you who are going to develop a project using ASP.NET C# Web services/ Web API Services. This article is also useful for those who are developing a project using Xamarin: Mobile App Development & App Creation

This post simplifies things for you. You just need to prepare your Service URL, Posting data (If Post service).

Then at last, here you will get json string as output, just create class as per your json formatted string and use the data as per your requirement.

Mobile application developers can use all these methods only they do not want datatable they can take list only, and perform their operations.

Background

For the purpose, you will be required to download ImportJson.dll, RestSharp.dll and Newtonsoft dll. Add reference of ImportJson DLL in your project.

How to add?

  1. Download ImportJson DLL
  2. Right click on references
  3. Click on browse button and go to path where DLL gets downloaded

Download ImportJson from:

Using the Code

Calling Simple GET Method

E.g. The GET service for getting access Token

URL: http://test.mydomin.com/ipos/oauth/api/?grantType=password&username=userName&password=Password@321

Use function for Json output as shown below:

/// <summary>
/// Simple Get method
/// </summary>
/// <returns> Json formatted data </returns>
   
public string GetJsonData1()
{
    IOperations _Obj = ClsOperations.GetOperations();
    string url = "http://test.mydomin.com/ipos/oauth/api/
     ?grantType=password&username=userName&password=Password@321";
     string jsonResult = _Obj.GetJsonResult(url);
    return jsonResult;
}

The above function will return json formatted string as given below:

{
       "success": true,
       "count": 1,
       "totalCount": 1,
       "access_token": "70f1f689-457e-49da-8858-87f478240051",
       "errors": null
}

How To Use: Suppose I want to assign access token to Label Text, Then create class as below:

public class ClsAccessToken
{
    public bool success { get; set; }
    public int count { get; set; }
    public int totalCount { get; set; }
    public string access_token { get; set; }
    public object errors { get; set; }
}
 
string _res = GetJsonData1();
ClsAccessToken obj = (JsonConvert.DeserializeObject<ClsAccessToken>(_res));

Now you will get each and everything from class object. The following code will assign access token value to label.

Label1.Text=obj.access_token;

Calling Simple GET Method with Multivalued / List / Enumerator / Tabular JSON Data

IDNameCity
1AmolBuldana
2RamNagpur
3KrishnaAmaravati

Now suppose your json data has multiple or tabular formatted data as below:

[{
                "ID": "1",
                "Name": "Amol",
                "City": "Buldana"
}, {
                "ID": "2",
                "Name": "Ram",
                "City": "Nagpur"
}, {
                "ID": "3",
                "Name": "Krishna",
                "City": "Amaravati"
}]

You want in List or show on Gridview, so the procedure will as below:

Create Class and get details:

public class ClsEmployee
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}
protected void GetData()
{     
    string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
    IOperations obj = ClsOperations.GetOperations();
    IEnumerator enumerator = obj.GetJsonEnumerableResult(url);
    List<ClsEmployee> lst = new List<ClsEmployee>();
    while (enumerator.MoveNext())
    {
        lst.Add(Newtonsoft.Json.JsonConvert.DeserializeObject
           <ClsEmployee>(enumerator.Current.ToString()));
    }
// Mobile developers use the lst as list of List<ClsEmployee>
DataTable dt = CommonServiceCall.ToDataTable(lst);
// For list to datatable take reference from internet
// E.g. http://stackoverflow.com/questions/18100783/how-to-convert-a-list-into-data-table
//Dot net developers can perform operations on datatable
}

Calling Web Service with Data POST/ POST Method

If you want to show the details of a particular employee only, e.g., from the above example, we will show information of the first employee only, let's say ID=1.

IDNameCity
1AmolBuldana
protected void GetDataByParameter()
{
    string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
    IOperations obj = ClsOperations.GetOperations();
    Dictionary<string, object> objDec = new Dictionary<string, object>();
    objDec.Add("@ID", "1");
    IEnumerator enumerator = obj.GetJsonEnumerableResult(url,objDec );
    List<ClsEmployee> lst = new List<ClsEmployee>();
    while (enumerator.MoveNext())
    {
        lst.Add(Newtonsoft.Json.JsonConvert.DeserializeObject
        <ClsEmployee>(enumerator.Current.ToString()));
    }
 
    DataTable dt = CommonServiceCall.ToDataTable(lst);
}

Calling Web Service with Data POST/ POST Method (Posted Data in JSON Format)

IDNameCity
1AmolBuldana
/// <summary>
/// Post Method with Input/ data to post in JSON format
/// </summary>
/// <returns> Json formatted data </returns>
 
protected void GetDataByjsonParameter()
{
      string url = 
      "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
      IOperations obj = ClsOperations.GetOperations();
      string InputJson = "{ \"ID\": \"1\" }";
      IEnumerator enumerator = obj.GetJsonEnumerableResult(url, null ,InputJson );
      List<ClsEmployee> lst = new List<ClsEmployee>();
      while (enumerator.MoveNext())
      {
          lst.Add(Newtonsoft.Json.JsonConvert.DeserializeObject
          <ClsEmployee>(enumerator.Current.ToString()));
      }
      DataTable dt = CommonServiceCall.ToDataTable(lst);
}

Calling Web Service for Xamarin App / Mobile Developer with Data POST/ POST Method (Posted Data in JSON Format)

IDNameCity
1AmolBuldana
protected List<ClsEmployee> GetDataByjsonParameterXamrine()
{
    string url = 
    "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
    IOperations obj = ClsOperations.GetOperations();
    JSONObject JSONObj = new JSONObject();
    JSONObj.put("ID", "1");
    string InputJson = JSONObj.ToString();
    IEnumerator enumerator = obj.GetJsonEnumerableResult(url, null, InputJson);
    List<ClsEmployee> lst = new List<ClsEmployee>();
    while (enumerator.MoveNext())
    {
        lst.Add(Newtonsoft.Json.JsonConvert.DeserializeObject
        <ClsEmployee>(enumerator.Current.ToString()));
    }
            
    return lst;
}

Forcefully Making Method as GET or POST

Here you can see that until now, you need not worry about GET or POST method, as by default if single URL returning data means service is of type GET, and if having parameters along with URL, then POST. But some of the times this may happen that service having single URL still is of type POST. In such case, we can use function as below:

public string GetJsonDataByForcefullyPOST()
{
   IOperations _Obj = ClsOperations.GetOperations();
   string url = "http://test.mydomin.com/ipos/oauth/api/
   ?grantType=password&username=userName&password=Password@321";
   string jsonResult = _Obj.GetJsonResult (url,null,null,ServiceType.POST );        
   return jsonResult;
}

Conversion from JSON string to Class object / List / DataTable

Dear friends,

Hope that uptil, this article is very helpful to you, now I will tell you how we can make use of above code for handling various type of JSON formatted data and using it, So that while development you does not need to take reference from outside all things will be available here.

Type 1:

Handling simple JSON Data

  E.g. If JSON result is simple as follows:

{

                "ID": "1",

                "Name": "Amol Khandagale",

                "City": "Buldana"

}

Then it can be handled and used as bellow:

 

 //Handling simple JSON

        protected void HandleSimpleJSON()

        {

            string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";

            IOperations obj = ClsOperations.GetOperations();

            ClsEmployee objEmp = new ClsEmployee();

String _res=obj.GetJsonResult(url);

            objEmp = Newtonsoft.Json.JsonConvert.DeserializeObject<ClsEmployee>(_res);

            string EmpID = objEmp.ID; // Gives result as 1

            string EmpName = objEmp.Name; //  Gives result as Amol

            string EmpCity = objEmp.City; //  Gives result as Buldana

        }

 

Type 2:

Handling simple JSON Data containing multiple values

E.g. If JSON format follows:

[{

                "ID": "1",

                "Name": "Amol",

                "City": "Buldana"

}, {

                "ID": "2",

                "Name": "Ram",

                "City": "Nagpur"

}, {

                "ID": "3",

                "Name": "Krishna",

                "City": "Amaravati"

}]

Then it can be handled and used as bellow:

 

//Handling simple JSON object having multiple values

protected void GetAllEmployeeDetails()

        { 

            string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";

            IOperations obj = ClsOperations.GetOperations();

            IEnumerator enumerator = obj.GetJsonEnumerableResult(url);

            List<ClsEmployee> lst = new List<ClsEmployee>();

            while (enumerator.MoveNext())

            {

                lst.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<ClsEmployee>(enumerator.Current.ToString()));

            }


 /* Here we get List of Employees, you can convert it to DataTable , IEnumerable, LINQ object and can perform various operations on it. */


        }

 

Type 3:

Handling little complex JSON Data

E.g. If JSON format follows:

{

                "Status": "Success",

                "Message": "Success",

                "TotalCount": "3",

                "Data": [{

                                "ID": "1",

                                "Name": "Amol",

                                "City": "Buldana"

                }, {

                                "ID": "2",

                                "Name": "Ram",

                                "City": "Nagpur"

                }, {

                                "ID": "3",

                                "Name": "Krishna",

                                "City": "Amaravati"

                }]

}

Then it can be handled and used as bellow:

                Now here the JSON object is quite complex, you can say it is a nested object. You just required to find out how many nested objects are there and have to create classes accordingly. In this example we have two objects 1) object containing four entities i) Status ii) Message iii)

 TotalCount iv) Data   

  The ‘Data’ entity contains again three entities i.e. i)ID ii)Name iii)City

 

Hence we required two classes as bellow:

public class ClsEmployee

{

    public string ID { get; set; }

    public string Name { get; set; }

    public string City { get; set; }

}

public class ClsEmployeeDetails

{

    public string Status { get; set; }

    public string Message { get; set; }

    public string TotalCount { get; set; }

    public List< ClsEmployee > Data { get; set; }

}

//Handling little JSON object having multiple values

protected DataTable GetEmployeeDetails()

        {

                        string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";

            IOperations obj = ClsOperations.GetOperations();          

ClsEmployee objEmp = new ClsEmployee();

String _res=obj.GetJsonResult(url);

            ClsEmployeeDetails  objEmpData = JsonConvert.DeserializeObject< ClsEmployeeDetails >(_res);

            List< ClsEmployee> lst1 = new List< ClsEmployee >();

            if (objEmpData.data != null)

            {

                    foreach (ClsEmployee i in objEmpData.data)

                    {

                        lst1.Add(i);

                    }

            }

        }

Type 4:

Handling complex JSON Data

E.g. If JSON format follows:

 

{

                "Status": "Success",

                "Message": "Success",

                "TotalCount": "3",

                "Data": [{

                                "ID": "1",

                                "Name": "Amol",

                                "City": "Buldana",

                                "Skills": [{

                                                "Subject": "ASP.NET"

                                }, {

                                                "Subject": "C#"

                                }]

                }, {

                                "ID": "2",

                                "Name": "Ram",

                                "City": "Nagpur",

                                "Skills": [{

                                                "Subject": "C#"

                                }]

                }, {

                                "ID": "3",

                                "Name": "Krishna",

                                "City": "Amaravati",

                                "Skills": [{

                                                "Subject": "ASP.NET"

                                }, {

                                                "Subject": "C#"

                                }, {

                                                "Subject": "SQL Server"

                                }]

                }]

}

Now here again nesting increased, hence structure becomes few complex, Here in employee details there are multiple employees and every employees having multiple skills, now we require to create three classes as bellow:

public class ClsSkills

{

    public string Subject { get; set; }

}

public class ClsEmployee

{

    public string ID { get; set; }

    public string Name { get; set; }

    public string City { get; set; }

    public List<ClsSkills> Skills { get; set; }

}

public class ClsEmployeeDetails

{

    public string Status { get; set; }

    public string Message { get; set; }

    public string TotalCount { get; set; }

    public List<ClsEmployee> Data { get; set; }

}

 

Then it can be handled and used as bellow:

 

protected void   GetEmployeeDetails()

        {

            string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";

            IOperations obj = ClsOperations.GetOperations();

            ClsEmployee objEmp = new ClsEmployee();

String _res=obj.GetJsonResult(url);

           

            ClsEmployeeDetails objData = JsonConvert.DeserializeObject<ClsEmployeeDetails>(GetJsonString());

            List<ClsEmployee> lst = new List<ClsEmployee>();

            List<ClsSkills> lst1 = new List<ClsSkills>();

            if (objData.Data != null)

            {

                foreach (ClsEmployee e in objData.Data)

                {

                    lst.Add(e);

                    foreach (ClsSkills i in e.Skills )

                    {

                        lst1.Add(i);

                    } 

                }

            }


            /* Now we can make use of these lists lst, lst1, objData and can perform your required operations */


        }

In this way, just refer this nesting and hope that you can handle now any JSON Data format.

 

If you are developing application using ASP.Net, C# and  Web services or Xamarine application development, This article will help you throughout the project. I think you does not required to take any reference form outside.

 

Points of Interest

For any suggestions / changes, please contact akhandagale65@gmail.com

History

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionCould you better explain what is article about Pin
Alexey KK18-Apr-17 5:58
professionalAlexey KK18-Apr-17 5:58 
AnswerRe: Could you better explain what is article about Pin
Amol M. Khandagale29-Apr-17 0:38
memberAmol M. Khandagale29-Apr-17 0:38 
GeneralRe: Could you better explain what is article about Pin
Alexey KK29-Apr-17 1:16
professionalAlexey KK29-Apr-17 1:16 
QuestionPasswords in Urls? Pin
pt140115-Apr-17 23:51
memberpt140115-Apr-17 23:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02-2016 | 2.8.180618.1 | Last Updated 15 Apr 2017
Article Copyright 2017 by Amol M. Khandagale
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid