3. Calling a SharePoint-Hosted WCF Service
To complete our calculation engine implementation,
we need to add some code to our DemoCalculationEngine project. We need
a method that can make a call into our SharePoint WCF service to notify
the workflow that calculation is complete. With the SharePoint project
deployed, we first need to add a service reference to the SharePoint
WCF service.
In the DemoCalculationEngine project, choose Project | Add Service Reference. Set the Address to http://localhost/_layouts/WorkflowDemonstration/CalculationResultService.svc.
Since
the service is hosted within SharePoint, requests must be
authenticated; as a result, we need to enter credentials for a user
account with permissions to connect to the SharePoint site.
Once
the service metadata has been retrieved, set the Namespace to
CalculationResultService and the click OK to complete the process.
Note
When adding a service reference for a SharePoint,
you’ll sometimes see multiple prompts to enter credentials. Usually,
after entering valid credentials once, clicking Cancel on subsequent
prompts will allow the process to continue.
With our service reference in place, we can move on to add the following code to handle the button click event in Form1.cs:
private void button1_Click(object sender, System.EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
CalculationResultService.CalculationResultServiceClient client = new
CalculationResultService.CalculationResultServiceClient();
client.ClientCredentials.Windows.AllowedImpersonationLevel =
System.Security.Principal.TokenImpersonationLevel.Impersonation;
CalculationResultService.CalculationResult result = new
CalculationResultService.CalculationResult();
CalculationRequest selected = row.DataBoundItem as CalculationRequest;
result.Result = selected.ProductName + " Complete";
result.InstanceId = selected.InstanceId;
result.SiteId = selected.SiteId;
result.WebId = selected.WebId;
if (client.ProcessCalculationResult(result))
{
row.Selected = false;
_calculationList.Remove(selected);
}
}
}
We can now manually trigger calculation results by
selecting an item from the data grid and then clicking the Send Result
button.
Tip
When hosting WCF services in SharePoint,
it’s important that the client proxy allows impersonation; otherwise,
some weird and wonderful COM errors may be thrown by SharePoint. To
allow impersonation, set the AllowedImpersonationLevel to Impersonation, as shown in the preceding code sample.