Archive for November, 2006

This post is a continuation of Post 1 of the series of posts i am writing on the Asmx Stuff to WCF route.Do read the First Part Here.
To refresh u  in this series of posts i am trying to cover the issues,,hype,standards,practices and happening in Webservices to WCF Journey and i ll try to provide references and links  as well as few writeup and my views on the same.I ll also try to cover WSE,WS* and few other simlilar topics on the same road.
In Part1 I have started with providing the new features in asmx 2.0 except the IxmlSerlizable and SchemaimporterExtensions which I ll cover Now before delving into the depth further:-
IxmlSerlizable and SchemaImporterExtension:-
This interface although presents in framework 1.1 was not documented and this usage was notimpemented by many.What this menat for you??Well ever you tried to take control over the webservice serlization mechanism or did u ever tried to take control over the schema generation  of webservices?
if your answer is yes then you might be aware of the fact that the default xmlserlization of webservice might not be always what you are expecting out of the serlization wire.Let say you want to serilized a type which didn’t implement the Iserilizable ,let say you want to serilize a hashtable,another example might be you want send data in chunks instead of a large set ..then friend the IxmlSerlizable interface is your friend which not only let you control over the Serilization and Deserilization  but also it helps you in controlling the schema generation[which you might control to certain extent by denoting various xml and typeof attributes on top of webmethods].
To control the serilization , implement the ReadXml and WriteXml methods to control the XmlReader and XmlWriter classes used to read and write the XML.To control the schemageneration you must apply the XmlSchemaProviderAttribute to the serializable type, and specify the name of the static member that returns the schema.Further to that the class that  implements the interface must  have a parameterless default constructor.
A quick and useful example would be you take control of the serilization by implementing the writexml in serverside to chunk your largedata and in client side you implement the readxml or schemaimporter extension to reuinte the can also follow the reverse approach but often this ends with your choice between push or pull model .
When i was not aware of the IxmlSerilizable let me admit that i opted the approach of sending data in chunk [in string of course which was a bad choice then then the chunk of strongly typed object   ] to websvc asynchrounously in a  different thread and then to Backend and in Backend i have used the binary Text Column append using pointer and used a similar approach to get the data back.That was a adeqaute solution from the fact that i took over the control of the serilization but no longer you need to follow the same tedious approach
 better you can hookup the writexml and readxml and own the serilization.Let  me mention the important point that you can opt to go for the chunking bacause of the 4096 KB limitation of iis buffering payload[although u can configure the maxrequestlength
in web.config that itself has issues like security and what exactsize you can opt for.
Finally one more point to note is that you need not have to implement the getxml method of ixmlserilizable just return Null from it.It can be used only when the DataSet instance is cast to an IXmlSerializable interface.
SchemaImporterExtension on the other hand as i mentioned above helps you in controlling the behavior in the otherside by adhering to your code instaed of the code generated by wsdl.exe or the add webref option of the Visualstudio.I had seen quite a few system where the ultimate option was to fall for manually modify the generated proxy in visual studio.One example might be when u return a custom array of objects in Fx 1.1 and you want to bind the result to the grid…you need to manually modify the proxy ..but with the schemaimporter extension you don’t need to manually modify the proxy.
Enough of writing  on  this now let me put some example links on this[not providing my own example here since there are already quite a few elegant and good example available on web to refer to :-
Ode to the System.Xml.Serialization.Advanced.SchemaImporterExtension Class
Watch /download the msdn nugget for Ixmlserializable Here.
SGEN.EXE :- this tool is meant for serlization performance and startup and often useful for scneario when u are calling the assmebly once.when u r using the sgen generated assembly ur assembly is precompiled and pregenerated and thus is providing performance improvement .further this tool is a useful one sql05 websvc scenario.
While i was reinventing the wheel on asmx 2.0 i found that there is already a good webcast by kirk and christian had also a series of post on the same.however i have coined them in my way and my intention of this post is not meant to provide the new bits of asmx 2.0 only.Found this post useful ? comment…
I ll continue the next post on this series where i ll cover more different issue like compression,REST as well as what is in WSE ,asmx stack and how u ll be faring with WCF with these.its 4 am now and i ll update the post tomorrow to get it back to track of where it started and not on asmx 2.0.good night…oh…good morning…guys…bye..
For  Last Part Click Here
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 2.0 for asynchrony in 2.0.

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


    public string ReverseString(string strToreverse)     {

        //Force a Delay So that You can test AsyncCall


        char[] arr = strToreverse.ToCharArray();


        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);



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

See for below article by Aaron for further details:- 

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)]
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.
                                                <!– <remove name="HttpSoap"/> –>
                                                <!– <remove name="HttpSoap1.2"/> –>
If u check ur wsdl u can found 2 implementation by defauld correcponds to 1.2 and earlier one.


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
     int Add(int num1, int num2);
     int Substract(int num1, int num2);
[WebService(Namespace = ";)]
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 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 Datatable serilization support are inbuilt.Also u can now use a usedefaultcredential with ur proxy directly instaedof…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

Last week i found an issue which was quite interesting with Nunit and the EnterpriseLibrary.The issue was my dev team reports that they are not being able to setup Nunit with enterpriseLibrary to successfully test the BLL.Although i can sidelined the issue being an architect i could have ask them its a dev issue but i couldn’t & I Can’t .Upon looking at the process i found that they are getting an issue where by the configuration is not recognised by enterpriselibrary when called from a unittest routine.
In this short post i ll try to cover the unittest approaches,Process and few principles you might follow or you are planning to follow in future:-I ll try to keep it short and simple .
Before delving further let me first provide the process and steps adopted so that if you are planning to go for unittesting your BLL which you must often found very useful would be a little easier:-
For unittesting you  can follow different approaches but TDD is  the most common that is the basic idea behind the process is to desgin your TestCases  before writing Code .Often i found it useful to add a Unittest Layer and a different Class Library based TestProject which help you test the necesary methods.However the critical issue came here is how do i test the UI and often people recommend the use of MVC pattern so that you can test  your logics [good one most of the time but not always although i strongly believe Martin Fowlers principles of keeping the presentation tiers free of almost any code] since you have a separation between your view and presentation tiers and since your logic is seprated from the presentation tiers you can now unittest your logics which  you always should test afterall that is the part where the core functionality lies and is most vulenerable to defects and changes.I am not again delving into the details of testing UI layer that i can cover someothertime or you can see many post on the same in web.
So we design  our DAL,BLL,UI or presentation Layers,BE[back end] as well as we have a TestLayer[Often a class Library project ] which ll contain the testcases and methods which will reference the other layer so that we can test method/function in those layers.We have written our Test methods or Testcases which we need to test and the necessary Test  and TestFixture attributes[it does not matter as this ll be change with tools] and we ll fire some unittest tools and run our tests.we might display success,failure info as well as assertions.
Here my dev team had also similar approach ,they have the MVC but we are not supposed to test the UI[we followed martin fowlers principle here:)]but the BLL and DAL calls primitively.The BLL and DAL were using the EnterPriseLibrary for dataaccess,Logging and ExceptionHandling purposes.In the Unit Test Project [class library] one they have the testcases or testmethods which is calling the BLL and DAL and EntLib methods.Now all these setup-ed and configured they fired the Nunit[VsUnit or any other you might ve ] and they load the test assembly and firedup the unittest cases[run the unit tests].
 Here comes the gotcha while testing the results the methods which were not reference to the Enterpriselibrary were sucess but all methods which used the enterpriselibrary failed with exceptions like "unrecognised configuration section dataconfiguration".if you ve used nunit with similar purposes you might alreday pointed it out that where the config created or copied for enterpriselibrary configuration to the UnitTEST project’ bin folder.Yes you need to create a copy of the same configuration in your UNittest project for the enterpriselibrary and even the documentaion of nunit says the same because at runtime the Enterpriselibrary will lookfor the config in ur app and when it not found one it ll through the exception config not found .you can drop one in the BIN folder of the unittest project but for us we already have the config created but it was still failing with unrecognised configuration Section .I crossed chcek the same creating a demo app and it works fine with theabove appoach but there was still the same error.I cross check the Xml configuration to findout if any erorr was there due to CASE
sensitiveness in xml but no the problem was somewhere else.The configuration file added to the test project was not at all recognised by enterpriselibrary and hence the problem.The moment i opened up the configuration file in NeterpriseLibrary configuration tool and defined the necessary configuration for DataAccess,ExceptionHandling and Logging error gone.
So if you have similar problem you know what to do?if you rae planning for unittesting and is not aware of much processed and hope this clarifies few of your doubts and provides an oerview of concepts from where you cab start looking into Unittesting.I am providing few more links to unittest frameworks and posts which helps you further:-


MbUnit vs. NUnit Vs. Team System Unit Testing – Choosing a unit test framework

series of posts from Roy on unittesting :-

Refactoring NUnit Unit Tests to VSUnit

unitetsting in  .NET by justin

Testing with NMOCK in msdnmag


VSTS unitesting walkThrough


HowtoCreate Asp.Net Unittest

intro article in informit

How to: Author a Unit Test  :-
Simplify Data Layer Unit Testing using Enterprise Services :-
Strengthening Visual Studio Unit Tests :-
Overview of Data-Driven Unit Tests  :-
unittesting framework

There are lot  more and i ll provide more info if anyone interested.However this ll hopefully give a start.I ll update this post soon for more update into this arena and soon post few more into the process of unitest.