Wednesday, 4 April 2018

024 Web Sevice -Creating Web Service

Web service is a communication platform between application. It consists of one or more method that can be exposed to a web for communication purpose.The most common for communication protocol is SOAP. SOAP stand for simple object access protocol.
  •  SOAP XML based protocol for accessing web service
  •  SOAP communicate over HTTP
  •  SOAP is W3C  recommended.

Web service file extension is .asmx . The method you want to use as a web method , need a special tag  [WebMethod] , before the method definition. 




To add a new web service to Asp.Net project, you need to add .asmx file in your application. New .asmx file content and inbuilt web service  called "HelloWorld".

 
 WebService Class
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
///
/// Summary description for WebService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
           public WebService ()
          {
                    //Uncomment the following line if using designed components
                   //InitializeComponent();
          }
         [WebMethod]
         public string HelloWorld()
        {
                  return "Hello World";
         }
}


When you browse that the .asmx file , you will see HelloWorld as a link, clicking this link HelloWorld web service will be called and the output of the HelloWorld will be shown.



WebService in Browser
 






Output

<string xmlns="http://tempuri.org/">Hello World</string>


 
We are creating a new web service, this web service content to method GetFullName and GetCountryName. GetFullName accept two parameter first name and last time, output as a concatenated full name. The second method GetCountryName name , return a string array  of some sample country name. GetCountryName method does not accept any parameter.







WebService Class

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data;
///
/// Summary description for WebService
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
            public WebService()
           {
           }

            [WebMethod]
            public string GetFullName(string firstName, string lastName)
            {
                      return firstName + " " + lastName;
            }

            [WebMethod]
            public string[] GetCountryName()
            {

             DataTable dt = new DataTable();

            dt.Columns.Add("CountryName");

           for (int i = 1; i < 20; i++)
            {

                 dt.Rows.Add("Country " + i.ToString());

           }

           List<string> data = new List<string>();
           for (int i = 1; i < dt.Rows.Count; i++)
           {

              data.Add(dt.Rows[i]["CountryName"].ToString());

          }

          return data.ToArray();

     }
}


WebService in Browser




GetCountryName Output
<ArrayOfString xmlns="http://tempuri.org/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <string>Country 2</string> <string>Country 3</string> <string>Country 4</string> <string>Country 5</string> <string>Country 6</string> <string>Country 7</string> <string>Country 8</string> <string>Country 9</string> <string>Country 10</string> <string>Country 11</string> <string>Country 12</string> <string>Country 13</string> <string>Country 14</string> <string>Country 15</string> <string>Country 16</string> <string>Country 17</string> <string>Country 18</string> <string>Country 19</string> </ArrayOfString>



GetFullName browser view








GetFullName Outut


<string xmlns="http://tempuri.org/">John Samuel</string>


Web service not only returning single value, a lot of type can be returned from webservice.

  1.     JSON
  2.     XML
  3.     Array
  4.     ByteArray
In the below example you will see, how JSON is return from Web service. How is serialized string return through web service. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

///



/// Summary description for WebService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

public WebService () {

//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
          public string GetStudentData()
          {
               Student[] obj = new Student[] {
              new Student()
              {
                   Name="John",
                   Roll=10
              },
              new Student()
             {
                   Name="Samuel",
                   Roll=15
               }
            };
        return new JavaScriptSerializer().Serialize(obj);
     }
}

public class Student
{
        public string Name { get; set; }
        public int Roll { get; set; }
}

In this example, a class "student" is created, to serialize data , the following namespace is  added. 

System.Web.Services;
System.Web.Script.Services;
System.Web.Script.Serialization;

Collection of "student" type object created and return which serialization process.
Output
<string xmlns="http://tempuri.org/">[{"Name":"John","Roll":10},{"Name":"Samuel","Roll":15}]</string>


In this example you will see how file can be transfer through  web service, if file is transferred through byte array.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data;
using System.IO;
///
/// Summary description for WebService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
          public WebService()
          {
           }

           [WebMethod()]
           public byte[] GetDownload()
            {
                   string path = @"C:\ab\cd\mytext.txt";
                   FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read);
                   byte[] fb = new byte[fs.Length];
                   fs.Read(fb, 0,Convert.ToInt16(fs.Length));
                   fs.Close();
                   return fb;
       }
}
In this example, a text file is read as filestream, this file stream is converted to a byte array and return .
Output (base64Binary formt)
 
<base64Binary xmlns="http://tempuri.org/">SUYgTk9UIEVYSVNUUyAoU0VMRUNUUoKQ0KCQk
=</base64Binary>

No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...