Adding own custom web service to SharePoint

I posted awhile back about InfoPath and Web Service data connection and I got question about using own web services in SharePoint (or at least I interpreted it that way :-). I tried to describe idea to have own custom "proxy" web service that would do all the necessary stuff inside SharePoint so that you could use local API and not the web service API. So if you know about application pages then you know what I'm talking about. Same things apply to web services too. But as always... I'm not good at telling stuff so let's jump to the code :-)

I just quickly created Microsoft.MCS.WebService.ExampleWebService.asmx and added it to the layouts folder (=C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS). This time I skipped features/solutions and did my example the easy way (as always :-).

Here is the content of the .asmx file:

 12
 <%@ WebService Class="Microsoft.MCS.WebService.ExampleWebService,Microsoft.MCS.WebService,Version=1.0.0.0,Culture=neutral,PublicKeyToken=a030a6768fa75cfc" %>

And code behind is in here (I signed it and put it into GAC):

 1234567891011121314151617
 using System;using System.Web.Services;using Microsoft.SharePoint;using System.Security.Principal;namespace Microsoft.MCS.WebService{  public class ExampleWebService : System.Web.Services.WebService  {    [WebMethod]    public string WhoAmI()    {      return WindowsIdentity.GetCurrent().Name +          " <->" + SPContext.Current.Web.CurrentUser.LoginName;    }  }}

Code is pretty simple since it just returns string that contains current users WindowsIdentity name and LoginName using SharePoint API.

If you run this stuff directly from SharePoint using browser you'll get something like this:

And now you can use this stuff from InfoPath as well:

So if you want to have weird SharePoint functionality (like enumerating lists) in your InfoPath forms you could use your own "proxy" web service to make it happen. This example was just skeleton that shows that this kind of stuff can be done but the exact implementation is left to you. I hope that I answered one of the questions that have been asked in my blog :-)

And if you try to update stuff in your code you'll most likely end up with SPException saying that "The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. "... but don't worry because that's the way it works :-) You can turn off the security validation check temporary with AllowUnsafeUpdates = true. I'll leave rest of that stuff for you...

Anyways... Happy hacking!

J