October 22, 2012

How to use ASMX services in visual web part development

Use case:
Visual web part needs to fetch data from aspx web service. WSDL url is provided.
Service reference vs Code generation:
There are two ways to add reference to asmx services. You can directly right click the web part project and click on add service reference, click on advance and then choose asmx service reference.
Adding service reference will hard code the service url. So it is suggested that we use WSDL.exe available in .net framework tools to generate a client proxy.
How to use WSDL.exe to generate service proxy?
  1. Go to .net command prompt
  2. type wsdl /language:csharp /out:c\csfilename.cs
This will automatically generate the cs file provided in out paramter. Add the class to your web part folder and adjust the namespace.
Further Considerations:
  1. Url of the service should not be hard coded, it should be coming from web part property.
  2. To imlpement this, add a custom property in web part to store service url
  3. Add another paramterized constructor to the first class. See example below:
    Default constructor:
     public Spotlight()
            {
                this.Url = "web service url";
            }
    New constructor:
     public Spotlight(string _url)
    {
      this.Url = _url;
    }
  4. Generally the first class in wsdl generated proxy cs will be the one where you need to add the new constructor.
  5. You can confirm this by looking at the first class and it will be inheriting from
          "System.Web.Services.Protocols.SoapHttpClientProtocol" class.
  6. When web part property for service url is blank, use default constructor
  7. When web part property for service url is not blank use parameterized constructor.
  8. When your service will change, you have to repeat the process to generate proxy and add additional parameterized constructor
Other best practices:
  1. Always use proper error handling to make sure exceptions are not visible to end users
  2. Always show appropriate message in case of no data to users
  3. Always show appropriate message in case of error getting data from service
  4. Always use best practice to parse xml data.
  5. If possible use xml deserializers to convert xml data into List
Conclusion:
We find it very useful to use WSDL.exe to generate asmx proxy and using constructor injection to initialize the service url from web part property.

If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment