Contents tagged with WebService

  • Dynamic URL of asp.net web service with web reference

    It’s been a while I am writing this. But never late.. So I am writing this. Before some time one of friend asked about the URL of web service when we add reference. So I am writing this. Some of you may find this very basic but still many of people does not know this that’s why I am writing this.

    In today’s world we have so many servers like development, preproduction and production etc. and for all the server location or URL of web service will be different.But with asp.net when you add a web reference to your web application it’s create a web reference settings in web.config where you can change this path. So it’s very easy to just change that path and you don’t have to add web reference again.

    Shout it

  • Interview questions about ASP.NET Web services.

    I have seen there are lots of myth’s about asp.net web services in fresher level asp.net developers. So I decided to write a blog post about asp.net web services interview questions. Because I think this is the best way to reach fresher asp.net developers. Followings are few questions about asp.net web services.

    1) What is asp.net web services?

    Ans: Web services are used to support http requests that formatted using xml,http and SOAP syntax. They interact with through standards xml messages through Soap. They are used to support interoperability. It has .asmx extension and .NET framework contains http handlers for web services to support http requested directly.

    2) What kind of data can be returned web services web methods?

    Ans: It supports all the primitive data types and custom data types that can be encoded and serialized by xml. You can find more information about that from the following link.

    http://msdn.microsoft.com/en-us/library/bb552900.aspx

    3) Is web services are only written in asp.net?

    Ans: No, It can be written by Java and PHP languages also.

    4) Explain web method attributes in web services

    Ans: Web method attributes are added to a public class method to indicate that this method is exposed as a part of XML web services. You can have multiple web methods in a class. But it should be having public attributes as it will be exposed as xml web service part. You can find more information about web method attributes from following link.

    http://msdn.microsoft.com/en-us/library/byxd99hx(v=vs.71).aspx

    5) What is SOA?

    Ans: SOA stands for “Services Oriented Architecture”. It is kind of service oriented architecture used to support different kind of computing platforms and applications. Web services in asp.net are one of the technologies that supports that kind of architecture.  You can call asp.net web services from any computing platforms and applications.

    6) What is SOAP,WDSL and UDDI?

    Ans: SOAP stands “Simple Object Access protocol”. Web services will be interact with SOAP messages written in XML. SOAP is sometimes referred as “data wrapper” or “data envelope”.Its contains different xml tag that creates a whole SOAP message.  WSDL stand for “Web services Description Language”.  It is an xml document which is written according to standard specified by W3c. It is a kind of manual or document that describes how we can use and consume web service. Web services development software processes the WSDL document and generates SOAP messages that are needed for specific web service. UDDI stand for “Universal Discovery, Description and Integration”. Its is used for web services registries. You can find addresses of web services from UDDI.

    Shout it

  • Working with more then one web.config files in asp.net application.

    Recently one of reader of my blog how we can work with more then one web.config files in asp.net application. So I decided to blog about that. Here is the my reply for that.

    You can work with more then one web.config file in asp.net. But you can not put more then one web.config in each folder. Let’s first understand the hierarchy of web.config and other configuration file settings. On the top of the every configuration files you will have machine.config file which will have all system wide configuration settings.You can find this file in your OS drive like C: /windows/Microsoft.NET/vFrameworkNumber/Config folder. Here framework number with what ever framework you are using 1.1/2.0 or 4.0. You can override those settings in web.config file at the your application root folder. Same way you can add more web.config file in subfolder and can override the setting of parent folder web.config file. So we will hierarchy like below.

    Hirerchay

    Now let’s Create Project for it. In that I have create two web.config and 2 pages. First I have putted the web.config in root folder and then I have putted web.config in subfolder. Same way I have created a sub folder and then I have putted the web.config in sub folder. I have also putted one asp.net page in root as well as subfolder to use respective web.config settings. Here are my folder structure like below.

    FolderStructure

    Below is code for root folder web.config

    <?xml version="1.0"?>
    <configuration>
        <system.web>
            <compilation debug="true" targetFramework="4.0" />
        </system.web>
      <appSettings>
        <add key="root" value="This is from root web.config"></add>
        <add key="MySetting" value="This my settings is from root web.config"></add>
      </appSettings>

    </configuration>

    and following is code for sub folder web.config.

    <?xml version="1.0"?>
    <configuration>
        <system.web>
        </system.web>
      <appSettings>
        <add key="sub" value="This is from sub web.config settings"></add>
        <add key="MySetting" value="This my settings is from sub folder web.config"></add>
      </appSettings>
    </configuration>

    After that I have written a code in root asp.net page to print settings from web.config folder like this following.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace MoreWebConfig
    {
        public partial class Root : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Root"));
                Response.Write("<BR>");
                Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("MySetting"));
    
            }
        }
    }

    Same way I have wrriten code in subfolder like following.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace MoreWebConfig.SubFolder
    {
        public partial class SubFolderPage : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Sub"));
                Response.Write("<BR>");
                Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("MySetting"));
    
            }
        }
    }

    Now let’s run the both pages in browser one by one and you can see root folder application page is fetching settings from root folder web.config while sub folder application page is fetching setting from subfolder web.config even if key ‘mysetting’ is same on both as expected. You can see out put in browser below.

    Root.aspx

    Root

    SubFolderPage.aspx

    SubFolder

    So it’s very easy to work with multiple web.config. The only limitation of this you can not access sub folder web.config settings from root folder page. Except all you can use anything. Hope you liked it. Stay tuned for more..Happy programming..

    Technorati Tags: ,
    Shout it

  • Converting a generic list into JSON string and then handling it in java script

    We all know that JSON (JavaScript Object Notation) is very useful in case of manipulating string on client side with java script and its performance is very good over browsers so let’s create a simple example where convert a Generic List then we will convert this list into JSON string and then we will call this web service from java script and will handle in java script.

    To do this we need a info class(Type) and for that class we are going to create generic list. Here is code for that I have created simple class with two properties UserId and UserName

    public class UserInfo
    {
    public int UserId { get; set; }
    public string UserName { get; set; }
    }

    Now Let’s create a web service and web method will create a class and then we will convert this with in JSON string with JavaScriptSerializer class. Here is web service class.

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

    namespace Experiment.WebService
    {
    /// <summary>
    /// Summary description for WsApplicationUser
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 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 WsApplicationUser : System.Web.Services.WebService
    {

    [WebMethod]
    public string GetUserList()
    {
    List<UserInfo> userList = new List<UserInfo>();
    for (int i = 1; i <= 5; i++)
    {
    UserInfo userInfo = new UserInfo();
    userInfo.UserId = i;
    userInfo.UserName = string.Format("{0}{1}", "J", i.ToString());
    userList.Add(userInfo);

    }
    System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    return jSearializer.Serialize(userList);
    }
    }
    }

    Note: Here you must have this attribute here in web service class ‘[System.Web.Script.Services.ScriptService]’ as this attribute will enable web service to call from client side.

    Now we have created a web service class let’s create a java script function ‘GetUserList’ which will call web service from JavaScript like following

    function GetUserList() {
    Experiment.WebService.WsApplicationUser.GetUserList(ReuqestCompleteCallback, RequestFailedCallback);

    }

    After as you can see we have inserted two call back function ReuqestCompleteCallback and RequestFailedCallback which handle errors and result from web service. ReuqestCompleteCallback will handle result of web service and if and error comes then RequestFailedCallback will print the error. Following is code for both function.

    function ReuqestCompleteCallback(result) {

    result = eval(result);
    var divResult = document.getElementById("divUserList");
    CreateUserListTable(result);

    }
    function RequestFailedCallback(error) {

    var stackTrace = error.get_stackTrace();
    var message = error.get_message();
    var statusCode = error.get_statusCode();
    var exceptionType = error.get_exceptionType();
    var timedout = error.get_timedOut();

    // Display the error.
    var divResult = document.getElementById("divUserList");
    divResult.innerHTML = "Stack Trace: " + stackTrace + "<br/>" +
    "Service Error: " + message + "<br/>" +
    "Status Code: " + statusCode + "<br/>" +
    "Exception Type: " + exceptionType + "<br/>" +
    "Timedout: " + timedout;
    }

    Here in above there is a function called you can see that we have use ‘eval’ function which parse string in enumerable form. Then we are calling a function call ‘CreateUserListTable’ which will create a table string and paste string in the a div. Here is code for that function.

    function CreateUserListTable(userList) {

    var tablestring = '<table ><tr><td>UsreID</td><td>UserName</td></tr>';

    for (var i = 0, len = userList.length; i < len; ++i)
    {
    tablestring=tablestring + "<tr>";
    tablestring=tablestring + "<td>" + userList[i].UserId + "</td>";
    tablestring=tablestring + "<td>" + userList[i].UserName + "</td>";
    tablestring=tablestring + "</tr>";
    }
    tablestring = tablestring + "</table>";
    var divResult = document.getElementById("divUserList");
    divResult.innerHTML = tablestring;
    }

    Now let’s create div which will have all html that is generated from this function. Here is code of my web page. We also need to add a script reference to enable web service from client side. Here is all HTML code we have.

    <form id="form1" runat="server">
    <asp:ScriptManager ID="myScirptManger" runat="Server">
    <Services>
    <asp:ServiceReference Path="~/WebService/WsApplicationUser.asmx" />
    </Services>
    </asp:ScriptManager>

    <div id="divUserList">
    </div>
    </form>

    Now as we have not defined where we are going to call ‘GetUserList’ function so let’s call this function on windows onload event of javascript like following.

     window.onload=GetUserList();

    That’s it. Now let’s run it on browser to see whether it’s work or not and here is the output in browser as expected.

    JSON string output in browser

    That’s it. This was very basic example but you can crate your own JavaScript enabled grid from this and you can see possibilities are unlimited here. Stay tuned for more.. Happy programming..

     

    Shout it

  • Request format is unrecognized for URL unexpectedly ending exception in web service.

    Recently I was getting error when I am calling web service using Java script. I searching on net and debugging I have found following things.

    Any web service support three kinds of protocol HttpGet,HttpPost and SOAP. In framework 1.0 it was enabled by default but after 1.0 framework it will not be enabled by default due to security issues and WS-Specifications. So we have to enabled them via putting configuration settings in web.config. Here is the code for that.

    <configuration>
    <system.web>
    <webservices>
    <protocols>
    <add name="HttpGet"></add>
    <add name="HttpPost"></add>
    </protocols>
    </webservices>
    </system.web>
    </configuration>

    Hope this will help you. Stay tuned for more. Till that Happy programming!!!.
    Shout it

  • Difference between Web Service and WCF Service

    While taking interviews of .NET developers I often ask this questions. But lots of people don’t know exact difference between this. So, I decided to write a separate blog about this.

    Here are the few differences.

    • Web services can be hosted in IIS as well as outside of the IIS. While WCF service can be hosted in IIS, Windows activation service,Self Hosting,WAS and on lots of proctols like Named Pipe,TCP etc.Here lots of people disagree how we can host the web service outside of the IIS but Here is the article for that.http://msdn.microsoft.com/en-us/library/aa529311.aspx.
    • In Web Services Web Service attribute will added  on the top of class. In WCF there will be a Service Contract attributes will be there. Same way Web Method attribute are added in top of method of Web service while in WCF Service Operation Contract will added on the top method.
    • In Web service System.XML.Serialization is supported while in the WCF Service System.RunTime.Serialization is supported.
    • WCF Services can be multithreaded via ServiceBehavior class while web service can not be.
    • WCF Services supports different type of bindings like BasicHttpBinding, WSHttpBinding, WSDualHttpBinding etc.while Web services only used soap or xml for this.
    • Web services are compiled into a class library assembly. A file called the service file is provided that has the extension .asmx and contains an @ WebService directive that identifies the class that contains the code for the service and the assembly in which it is located while in WCF.WCF services can readily be hosted within IIS 5.1 or 6.0, the Windows Process Activation Service (WAS) that is provided as part of IIS 7.0, and within any .NET application. To host a service in IIS 5.1 or 6.0, the service must use HTTP as the communications transport protocol.

    Hope this will help you. Happy programming!!!

    Technorati Tags: ,,
    Shout it

  • Calling an asp.net web service from jQuery

    As I have post it in earlier post that jQuery is one of most popular JavaScript library in the world amongst web developers Lets take a example calling ASP.NET web service with jQuery . You will see at the end of the example that how easy it is to call a web service from the jQuery.

    Let’s create a simple Hello World web service. Go to your project right click->Add –> New Item and select web service and add a web service like following. Adding  a webservice 

    Now modify the code of web service like following.

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 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 HelloWorld : System.Web.Services.WebService
    {
    [WebMethod]
    public string PrintMessage()
    {
    return "Hello World..This is from webservice";
    }
    }

    Here please make sure that [System.Web.Script.Services.ScriptService] is un commented because this attribute is responsible for allowing web service to be called by Client side scripts.

    Now to call this  web service from jquery we have to include jQuery Js like following. I am already having in my project so i don’t need to include in project just need to add script tag like following.

    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"> 
    </script>

    Now let’s add some JavaScript code to call web service methods like following.

     <script language="javascript" type="text/javascript">
    function CallWebServiceFromJquery() {

    $.ajax({
    type: "POST",
    url: "HelloWorld.asmx/PrintMessage",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnSuccess,
    error: OnError
    });

    }

    function OnSuccess(data, status)
    {
    alert(data.d);
    }

    function OnError(request, status, error)
    {
    alert(request.statusText);
    }
    </script>

    Here I have written three functions in JavaScript First one is CallWebserviceFromJquery which will call the web service. The another two functions are delegates of   web service if Success is there then onSuccess Method will be called and If Error is there then OnError method will be called.

    Inside the CallWebserviceFromJquery I have passed some parameter which will call web service with Ajax capabilities of $ jQuery object. Here are the description for each parameter.

    Type: This can be GET or POST for web service we have to take POST as by default web service does not work with GET to prevent Cross site requests.

    Url: Here will be url of the web service. You have insert fully qualified web service name here.

    Data:Here it will be Empty as we not calling web service with parameters if you are calling web service with parameter then you have to pass that here.

    contentType: here you have to specify what type of content is going to return by web service.

    datatype:Json it will be result type

    sucess:Here I have called the OnSuccess when the call is complete successfully. If you check the OnSuccess method you will see that I have set the returned result from the web service to the label. In the OnSuccess method body you see ‘data.d’. The ‘d’ here is the short form of data.

    Error: Same as I have done with OnSuccess. If any error occurred while retrieving the data then the OnError method is invoked.

    Now let’s add a asp.net button for on client click we will call the javascript function like following.

     

     <asp:Button ID="btnCallWebService" runat="server" 
    OnClientClick="CallWebServiceFromJquery()"
    Text="Call Webservice"/>

     

    Now Let’s run it and here is the output in browser.

    Ouput

    Hope this will help you!!!.. Happy programming..

    Shout it

  • How to add service reference dynamically from user control? Microsoft Ajax

    First, Create a web page default.aspx and put the html code as following..

    ---------------------------------------------------------------------------
    <asp:ScriptManager ID="MainScriptManager" runat="server">
    </asp:ScriptManager>
    --------------------------------------------------------------------------

    Now, Create a usercontrol my first user control

    Create a function called AddScriptReference as following...

    '--------------------------------------------------------------------------
    private void AddScriptReference()
    {
         ScriptManager scriptManger = ScriptManager.GetCurrent(this.Page);
         if (scriptManger != null)
         {
             ServiceReference serviceReference = new ServiceReference();
             serviceReference.Path="~/MyWebService.asmx";
             serviceReference.InlineScript = false; 
             scriptManger.Services.Add(serviceReference);   
         }
         else
         {
             throw new Exception("Script Manager Not Found");
         }
    }
    '--------------------------------------------------------------------------
    Then override controls init event as following...

    '--------------------------------------------------------------------------
    protected override void OnInit(EventArgs e)
    {
         AddScriptReference();
         base.OnInit(e);
    }
    '--------------------------------------------------------------------------