Last Lap Around ASMX and Stuffs before moving to WCF:-Part I

Posted: November 27, 2006 in Uncategorized
 
Now that .NET FX 3.0 released focus has been shifted to the WCF,WF,WPF and WCS and I can see lot of interest between developers,architects and all microsoft techies starts exploring the tid bits of .NET Fx 3.0 and me too was no exception.However this post is not about the .NET FX 3.0 but in this post i ll try to cover the journey of the ASMX to WCF via the route of SOA,WS* and from the view point of developers as well as architects.I ll try to make this post helpful for one who is planing to move into WCF as well as for the one who is trying to understand WebSvc in FX 2.0 as well as i ll try to cover what all is happening around WebSvc from the FX 1.1 and my focus will be oriented more around Microsoft and .NET side.
 
Intially i feel that this post is bit late but later on i found that there are quite a few people i talked and discuused with were unaware of  the websvc journey and thus this post.
 
So, to start with what all issues and topics  you have seen working with webservices .I ve found and worked on quite a few issues and even you might ve seen ,worked on issues revolving around like the following broad categories:-
 
  • Datatypes support in WebServices[Often this ends with dataset vs objects]
  • WebServiceVersioning and Interface support
  • Control Over Serilization mechanism
  • Interopability
  • WSE
  • Contract First or Code First
  • Compression Support and handling Large Data
  • SOAP vs REST
  • Dynamic Webservice
  • Transaction and Asynchronous WebServices
  • Different Host and Protocol Support
  • Remoting vs WebSerices 
  • Messaging Patterns
  • Usage of webservice in data access and
  • Finally WS* stack and SOA
 
 There might be few more what i am missing here and i didn’t have considered quite a few internal issue like handling exception ,security details etc.; Its not that work has not been done on these and many framework and patterns have been eveoled from both microsoft as well as third parties.For many of these issue a lot of work has been done many articles have been written and frameworks have been developed.Few examples might be WSE,MTOM,Asmx 2.0 supports, WSCF(contract first),WSSF(software factory),WSSP(Websvc sec pattern from p&p)..
 
In this post i cann’t cover all but i ll try to provide few resources ,few writes up before moving to the routes of WCF from WebServices.
 
So to starts with let me go thru what you found new in Asmx 2.0 stacks with VS2005 :-
 
Again summarizing the facts and figure the primtive improvements were:-

  • Properties instead of fields
  • AsynchronousEvent Support
  • Run asmx without IIS
  • Server Interface with WSDL (/si) with WSDL.exe
  • Basic profile Conformance
  • Soap 1.2 Protocol support
  • Interface Support
  • IXMLSerilizable
  • Pre-Generating Serialization Assemblies with Sgen.exe support
  • Proxy Type Sharing
  • Web Service versioning & interface
  • SchemaImporter Extension

 
Now that i have listed few new features in WebServices in VS 2005 then in time around VS2003 let go into  the little details of these:-
 Properties instead of fields:-
 
 In version 1.1 of framework if you built a websvc which exposes a class which has fields and properties both was serialized as  fields .thus if you are planning to data binding against the websvc call thru the proxy it ll not succeed. In 2.0 both fields and properties serialized as properties.
 
To see this yourself return an instance of a class which contains a properties and field from a webmethod.Now inspect the proxy.cs in client application web reference section.
 
 AsynchronousEvent Support:-
 There is now event based async call support built-in with the websvc 2.0 framework. Earlier in 1.1 you need to call a beginXXX and later implement the asynchronous pattern by hooking a event based mechanism and callback. Why all these were necessary? Normally the web svc call during async execution are executed in a different thread then the thread from which you have called and you need some sort of callback as well as you need to update the UI back with the result. Now since the thread execution has been changed from the UI thread you can’t directly access or update the UI and thus you need another delegate to delegate the result back to main thread. See the Asynchronous pattern in msdn as well as David hill articles on the asynchronous pattern. Further you can use the BackgrounWorker in framework 2.0 .Also checks Juval lowy’s post here and code magazine and Mike Woodering tin plurasight on threading and finally checkout the AsyncTask and AsyncPages in asp.net 2.0 for asynchrony in asp.net 2.0.

http://blogs.msdn.com/dphill/articles/43260.aspx

http://msdn2.microsoft.com/en-US/library/hkasytyf.aspx

http://msdn2.microsoft.com/en-US/library/8wy069k1.aspx

http://msdn2.microsoft.com/en-US/library/wewwczdw.aspx

 Also checkout How To: Submit and Poll for Long-Running Tasks from p&p and fritz onion post on the wait state pattern in msdn.

  The good news in 2.0 is that the eventbased async model is thus you already built-in thus you can directly leverage the same. Below is a demo for the same. Finally pay a closer notice to the proxy.cs methods to know how this is carrying fwd.

  Add a few seconds delay to web method .Now add a winform app and put 2 buttons for Sync and Async Call. Check that during the sync call you can’t resize the form it hangs where as during async call you can do the resize.

Webmetod :-

[WebMethod]

    public string ReverseString(string strToreverse)     {

        //Force a Delay So that You can test AsyncCall

         System.Threading.Thread.Sleep(2000); 

        char[] arr = strToreverse.ToCharArray();

        Array.Reverse(arr);

        string str = new string(arr);

        return str;

    }

private void CmdSync_Click(object sender, EventArgs e)

        {    Proxy.Service svc = new Service();

            svc.UseDefaultCredentials = true;

            textBox1.Text = svc.ReverseString(textBox1.Text);

        }

        private void CmdASync_Click(object sender, EventArgs e)

        {     Proxy.Service svc = new Service();

            svc.UseDefaultCredentials = true;

            svc.ReverseStringCompleted+=new ReverseStringCompletedEventHandler(svc_ReverseStringCompleted);

            svc.ReverseStringAsync(textBox1.Text);

         }

private void svc_ReverseStringCompleted(object seneder,ReverseStringCompletedEventArgs e)

        {            textBox1.Text = e.Result;

        }

 

 

 

 

 

 

 

 

 

 

 

 

Run asmx without IIS:-

 With the introduction of http.sys you can now host the asp.net as well as the asmx easily using the Http listener and httpworkerrequest.Note that here I am not pointing to the Casini hosting rather or better I am pointing to the hosting scenario for httppipeline,webserver and hosting asmx.

Note that doing so you are losing the inbuilt IIS capabilities like ISAPI and process and thread pool management.[IIS 6 is architected to configured around http.sys].If you have gone thru the WSE hands-on labs you might have seen feature of hosting using the httplistener .Basically you are defining the port on which to listen ,a host to process the message and the http.sys interface using the system.net namespace.

See for below article by Aaron for further details:- 

http://msdn.microsoft.com/msdnmag/issues/04/12/ServiceStation/ 

Further you can use TCP instead of Http as well which is analogous to WCF  and the WSE 3.0 samples shows you how to achieve this .Here you need to mere define an Uri and just add that Uri to the Soap receiver and you are thru. 

               Uri uri = new Uri("soap.tcp://localhost:9090/myservice");
               SoapReceivers.Add(uri, typeof(myservice)); 
However note that you cannot supply an HTTP address to SoapReceivers.Add like you can with ServiceHost in WCF.
SoapReceivers doesn’t provide direct integration with HTTP.sys, which is what would be required in this case.
So to host your ASMX services over HTTP, you must revert to an <httpHandler> mapping or write the HTTP.sys
integration code yourself    . 
Basic profile Conformance & Soap 1.2 Protocol support:-
 
If you want to build a WS-I basic profile conformant WebSvc you can use the WebServiceBinding attribute on the websvc class ad set the ConformanceClaims to WsiProfiles.BasicProfile1_1.The EmitConformanceClaim=true ll emit the conformance claim in WSDL. By default, new Web services created by Visual Studio are BP-conformant with WebServiceBinding.EmitConformanceClaims set to true.  
 
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1, EmitConformanceClaims=true)]
[WebService(Namespace="Microsoft.Samples.XmlMessaging.WebServices")]
public class My_asmx
{
}
Soap 1.2 protocol:-
Asmx 2.0 now supports the soap 1.2 protocols.You can however configure the same in web.config as follows.
<system.web>
                        <webServices>
                                    <protocols>
                                                <!– <remove name="HttpSoap"/> –>
                                                <!– <remove name="HttpSoap1.2"/> –>
                                    </protocols>
                        </webServices>
    </system.web>
 
If u check ur wsdl u can found 2 implementation by defauld correcponds to 1.2 and earlier one.

 Ref:  http://www.ws-i.org/deliverables/workinggroup.aspx?wg=basicprofile

Watch\download  a basic profile conformance nugget video here

Interface Support:-

With Asmx 2.0  you can now use interfaces to define the contract for your webservices.With this coming inot  the picture you ll get the benefit of versioning as well as separation of implementation logic.So what you attrinbute ll be applied to intefaces and what to the class?

[WebServiceBinding] , [WebMethod] , [SoapDocumentMethod] go on the interface while [WebService] goes on the class. When employing this model, all attributes that affect the service contract definition must be placed on the interface definition and not on the class. This includes [SoapDocumentService], [SoapDocumentMethod], and the various System.Xml.Serialization attributes that you could apply to method signatures. You cannot mix and match these attributes across the interface and class definitions, and ASMX helps to ensure that you don’t.

For example, once you’ve derived a class from an interface that contains these service contract attributes, ASMX will inspect the class at run time to make sure that you haven’t used any additional attributes that might further change the service contract.

 You’ll use [WebService] on the class to specify the <wsdl:service> details of the endpoint. This makes sense because you could have multiple services implementing the same service contract. Likewise, if you’re using WSE 3.0, you’ll use [Policy] on the class to apply a security policy configuration to the specific endpoint.

However, in some instances, you might also need to use [WebMethod] on the derived methods when you need to configure local processing behaviors through the various [WebMethod] properties (BufferResponse, CacheDuration, EnableSession, TransactionOption)

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public interface ICalculator
{
    [WebMethod]
     int Add(int num1, int num2);
    [WebMethod]
     int Substract(int num1, int num2);
}
[WebService(Namespace = "http://tempuri.org/&quot;)]
public class InterfaceBasedService : System.Web.Services.WebService,ICalculator
{
    public InterfaceBasedService()    {    }
 public int  Add(int num1, int num2)
{
      return num1+num2;
}
 
public int  Substract(int num1, int num2)
{
    return num1-num2;
} 
}
 Read Why Should You Care About Interfaces in asmx : Because its provide versioning  from Kirk’s blog Here
  Watch\DownLoad a msdnNugget Videos on Asmx interface support here

Server Interface with WSDL (/si) with WSDL.exe

 To generate the interface from the WSDL, you need to use the Wsdl.exe /si switch . In 1.1 you ll get an abstract base class from the /Server switch with wsdl.exe but that is inadequate and deprecated with the serverinterface switch which generates interfaces so that you can implement many interfaces as well as you need not have to copy attributes from the base class to derived class like 1.1.

An interface is generated for each binding in the WSDL document(s). The WSDL alone implements the WSDL contract (classes that implement the interface should not include either of the following on the class methods: Web Service attributes or Serialization attributes that change the WSDL contract).

 Using interface the benefit is implementation code is separate from the contract code that is if you change the wsdl and the regenerate the interfaces you ll not loose any implementation code thus do remember not to put any code in implementation that changes the contract.

Ex:- Wsdl.exe xx.wsdl /si

 Proxy Type Sharing:-
 You can now Share types between 2 services with the new wsdl sharetype switches.This feature allows you to share identical types from different Web services within the client-side proxy class. wsdl.exe recognizes identical types shared between two or more different Web services and emits one code file that has only one definition of the shared types.  This allows one client to share types between services without worrying about compile time errors due to multiple type definitions with the same name.  There is no need to delete extra code due to duplicate type definitions.
 
wsdl.exe /out:myproxies.cs /shareTypes [wsdl1 uri]  [wsdl2 uri]

 This will result in one file called myproxies.cs which contains the proxy implementations for  the firstsvc  and secondsvc  information as well as only one single .NET representation of the shared type schema.Thus now you  can generate the shared type in one proxy and passed the same to the other.

Apart from these you can see features like

New Code Separation :-           its the same code separation model in asp.net 2.0 with partial class and new compilation model.

Compression/ decompression support : –       from asmx view point youcan now point ur clientproxy.compression=true however web svc compression vs http comression and laregdata issue i ll try to cover in the next post.

NullableTypes and SQlType Support,inline generic support:-      with the 2.0 framework now you webmethod can be declared as generic types for know types that is inbuilt <list> etc as well as the Nullable and SqlType inbuilt support and ado.net Datatable serilization support are inbuilt.Also u can now use a usedefaultcredential with ur proxy directly instaedof proxy.cred=system.net.cred…cacahe.defaultcred..

 

 I ll cover the IxmlSerializable,SchemaImporterExtension and Sgen.exe in next post.

 
 Ok ,So far we have scratched into few asmx 2.0 supports and 2 are still many issues i idn’t yet covered ,however i have not yet scratch the mentioed topic on TOP yet and looking at the length of this post i ll try to keep it short and provide necessary references and writeup if found on the same topic by others.Finally if you are wondering where all thes fits be sure to read the next posts in this series.

 
 Due to space limitation in 1 post I ll continue this in the Next Post ClickHere to go to the next Entry Part2  on this series of posts. 

 last Part click here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s