>
Blog
Book
Portfolio
Search

7/26/2006

3542 Views // 0 Comments // Not Rated

InfoPathology - Part 9 - Calling Web Services From Code

One of the nicest things InfoPath can do for a developer is aggregate Web Services and transparently present their functionality to use as secondary data sources. These data sources are great for binding drop down lists and populating repeating controls. However, they are not so great when we want to store the data they return and manipulate it later.

Calling Web Services from code is also usef when we run into situations in which the conditions under which we want to invoke a web method are too complex to define with rules. Also, this gives us the ability to call Web Services asynchronously in our form methods.

Although this is a rather straight-forward task for a .NET developer, there are a few nuances that InfoPath brings to the table. Here's how to do it:

  1. Add a web reference to your InfoPath project, just the same as you would for any other project.  (One of the main points of this article is to point out that a great deal of .NET functionality is completely identical for InfoPath projects, although it might not seem so...)  Make sure to add it to the "inner" project (with the form code).
  2. Configure it to point to your web server.
  3. Create a global variable to instantiate the web service.
  4. SET THE CREDENTIALS!  This is a crucial step, since, without giving the Credentials property a value, despite compiling just fine, any web service call will fail with the 401: Unauthorized error.  This is true regardless of any impersonation code that may have implemented or permissions of the current user.

In most cases, the following will work:

Code Listing 1

  1. using System.Net;
  2. ...
  3. webServiceReference.Credentials = CredentialCache.DefaultCredentials;

However, depending on IIS settings and other security mechanisms in place on the network, this might still fail. So use the following call to "force" successful web service authentication:

Code Listing 2

  1. using System.Net;
  2. ...
  3. webServiceReference.Credentials = new NerworkCredential("admin username", "admin password", "domain");

I've run into situations, especially when working with SharePoint web services, where the default credentials worked on a development server, but not in production. So, when working around .NET and Windows Server security, it never hurts to be as explicit as possible.

Finally, invoke the web methods (synchronously or asynchronously) in your form code, bypassing the limitations of using standard InfoPath web service implementations when they get in the way.

4 Tags

No Files

No Thoughts

Your Thoughts?

You need to login with Twitter to share a Thought on this post.


Loading...