Tuesday, April 27, 2010

Building and deploying a WCF service to SharePoint 2010, and writing a console client, all in 3min 28sec

Here's a 3m 28s screencast (which could have been a lot quicker, if I didn't fumble about so much), where I build and deploy a WCF service to a blank SharePoint 2010 site, and then create a console client to make a request from the service.


A couple of quick tricks make it swifter than a blink of an eye - seriously.

1: Avoid manually typing the full assembly (and PublicKeyToken) reference in your .svc files

To do this, make a one-time update to your build box' SharePoint MSBuild targets. Go to your "Program files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\SharePointTools" folder, and open the .targets-file found there. Locate the "TokenReplacementFileExtensions" node, and add "svc" to the processed extensions.

This will essentially make .svc files eligible for replacements such as described in http://msdn.microsoft.com/en-us/library/ee231545.aspx. Which means that your .svc files can now include:

<%@ ServiceHost
Factory="..."
Language="C#"
Service="Namespace.ServiceClass, $SharePoint.Project.AssemblyFullName$"
%>

The full assembly reference will then be filled in upon build.

2: Use a Factory, rather than an explicit web.config file alongside your .svc

This is an excerpt from a ReSharper live template I setup in my own dev environment, which is merged with the ServiceHost block above:

Factory="Microsoft.SharePoint.Client.Services.$FACTORY$,
Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c"

Where $FACTORY$ is either:
  • MultipleBaseAddressBasicHttpBindingServiceHostFactory for a SOAP service.
  • MultipleBaseAddressWebServiceHostFactory for a REST service.
  • MultipleBaseAddressDataServiceHostFactory for an ADO.NET Data Service.

To provide a MEX endpoint for your service, add an "[BasicHttpBindingServiceMetadataExchangeEndpoint]" attribute to your service implementation. This is defined in the assembly Microsoft.SharePoint.Client.ServerRuntime. The namespace is Microsoft.SharePoint.Client.Services.

Also make sure it has "[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]", otherwise it won't run at all. This is found in the System.ServiceModel assembly, which is required for WCF in general.

3: Deploy using Visual Studio 2010

Using one of the new Visual Studio 2010 project templates:
  1. Add your service code
  2. Right-click the project node and add a mapped SharePoint folder, such as LAYOUTS or ISAPI
  3. Deploy your .svc file(s) to a project folder within the mapped folder
  4. Hit build, deploy and take it for a spin.

No comments: