Click here to Skip to main content
14,422,431 members

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

Rate this:
4.27 (7 votes)
Please Sign up or sign in to vote.
4.27 (7 votes)
3 Jan 2020CPOL
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.

For those who want readymade code only, they will pass URL and filter parameters, then download the DLL and use as given.

Those who do not want to depend on DLL can use the code given below.

Creating Web Service

using WebApi.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace WebApi.Controllers
{
    public class HomeController : ApiController
    {

        [HttpPost ]
        public HttpResponseMessage GetData(App_DataFilters ObjDigFilters)
        {
            Exception _ex = null;
            OutputResult _result = new OutputResult();
            DataView dv = new DataView();

            try
            {
                Dal_Data objDal = new Dal_Data();
                dv = objDal.GetData(out _ex).AsDataView();              

                _result.Data = dv.ToTable();

                if (_ex != null)
                {
                    _result.IsSucceed = false;
                    _result.ExceptionDetails = _ex;
                }
                else { _result.IsSucceed = true; }

            }
            catch (Exception ex)
            {
                _result.IsSucceed = false;
                _result.ExceptionDetails = ex;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, _result);
            }

            return Request.CreateResponse(HttpStatusCode.OK, _result);
        }
}
}

 public class App_DataFilters
    {
        public string ProductName{ get; set; }
        public string Code { get; set; }
        public string Description { get; set; }
        public string CodesetName { get; set; }
         
    }

    public class OutputResult
    {
        public bool IsSucceed { get; set; } = false;
        public string Comment { get; set; } = string.Empty;
        public Exception ExceptionDetails { get; set; }
        public DataTable Data { get; set; }
    }

Using Web Service

public class MyClass
    {
        public async Task<OutputResult> GetData(App_DataFilters obj)
        {
            OutputResult _OutputResult = new OutputResult();
            JavaScriptSerializer _Serializer = new JavaScriptSerializer();
            try
            {               
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:41315/");
                var json = _Serializer.Serialize(obj);
                HttpContent content = 
                      new StringContent(json, Encoding.UTF8, "application/json");
                HttpResponseMessage response = 
                      await client.PostAsync("api/Home/GetData", content);

                var Data = response.Content.ReadAsAsync<OutputResult>();

                return Data.Result;
            }
            catch (Exception ex)
            {
                _OutputResult.IsSucceed = false;
                _OutputResult.ExceptionDetails = ex;                 
            }
            return _OutputResult;
        }
}
Those who want to use readymade code can go by the way described below. Download the DLL and only pass the required variables and get output.

Background

For this 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

Example: 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 every thing 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

ID Name City
1 Amol Buldana
2 Ram Nagpur
3 Krishna Amaravati

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 be 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.

ID Name City
1 Amol Buldana
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)

ID Name City
1 Amol Buldana
/// <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)

ID Name City
1 Amol Buldana
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 sometimes, it 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

Hope that so far, this article is very helpful to you, now I will tell you how we can make use of the above code for handling various types of JSON formatted data and use it. So that during development, you do not need to take reference from outside as all things will be available here.

Type 1

Handling Simple JSON Data

Example: If JSON result is simple as follows:

{
                "ID": "1",
                "Name": "Amol Khandagale",
                "City": "Buldana"
}

Then it can be handled and used as below:

//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

Example: 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 below:

//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

Example: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 below:

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:
    1. Status
    2. Message
    3. TotalCount
    4. Data

      The ‘Data’ entity again contains three entities, i.e.:

      1. ID
      2. Name
      3. City

Hence, we require two classes as below:

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

Example: 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 a little complex. Here in employee details, there are multiple employees and every employee having multiple skills, now we require to create three classes as below:

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 below:

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 to this nesting and hope you can now handle any JSON Data format.

If you are developing an application using ASP.NET, C# and Web services or Xamarin, this article will help you throughout the project. I think you are not required to take any reference from outside.

If you have any suggestions / changes, please leave a comment below.

History

  • 3rd January, 2020: Initial version

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

Comments and Discussions

 
QuestionMessage Closed Pin
9-Jan-20 0:41
MemberMember 147113959-Jan-20 0:41 
QuestionCould you better explain what is article about Pin
Alexey KK18-Apr-17 6:58
professionalAlexey KK18-Apr-17 6:58 
AnswerRe: Could you better explain what is article about Pin
Amol M. Khandagale29-Apr-17 1:38
MemberAmol M. Khandagale29-Apr-17 1:38 
GeneralRe: Could you better explain what is article about Pin
Alexey KK29-Apr-17 2:16
professionalAlexey KK29-Apr-17 2:16 
QuestionPasswords in Urls? Pin
pt140116-Apr-17 0:51
Memberpt140116-Apr-17 0: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.

Article
Posted 13 Apr 2017

Tagged as

Stats

24.9K views
21 bookmarked