In this section, we’ll build the environmental control procedure as defined in our demonstration scenario. Here’s a recap: To comply with international regulations relating to environmental protection, each product available for order must have achieved compliance with the appropriate standards for the country into which it will be sold. Determining compliance involves performing a series of calculations to determine the level of specific substances within the finished product. Since the calculation is relatively complex, it will be performed by a separate system. Once the calculation has been performed, the results should be sent to an environmental control officer for verification. We can see that our workflow should make use of calculation facilities provided by an external system. Since the calculation process is long running, an asynchronous pattern will be used—that is, a request will be sent to the external system, the system will acknowledge the request, and it will then begin performing the relevant work in a separate asynchronous process. Once the system has completed the prescribed work, it will communicate the results to the original caller.
Creating a Sample WCF Calculation Service
We’ll implement our demo calculation service using Windows Communication Foundation (WCF). WCF itself is a separate topic and in depth coverage is out of scope of this chapter, but I’ll use it for this example since it is one of the primary mechanisms used for communicating with external systems. Since we don’t actually need to perform any calculations, we’ll create a Windows Forms client application that receives incoming requests and writes them to a list. We’ll then be able to select requests from the list and manually submit a response to the workflow. To make this work, we need two WCF services—one in the Windows Forms client to receive the calculation request, and another within SharePoint to receive the response from the calculation service. We’ll create the Windows Forms client first.
Create a Windows Forms Client Hosting a WCF Service
TIPTo create a default implementation of an interface automatically using Visual Studio, right-click the name of the interface and then select Implement Interface | Implement Interface from the context menu. Our service implementation probably warrants some explanation. Since we’re going to write incoming requests to the data grid that we added to our user interface, we need to do this using the same thread that’s running the user interface to avoid cross-threading issues. In effect, our service does nothing more than write the requests to the user interface.
We can make use of the WCF test tools that are provided with Visual Studio to check that everything is working properly. Open up a Visual Studio command prompt and type the following:C:Program Files (x86)Microsoft Visual Studio 10.0VC>WCFTestClient This will start the WCFTestClient.exe application that we can use to submit requests to our calculation engine.
Before we can connect, we need to know the endpoint URI for our service. This can be found in the app.config file for our client application under system.serviceModel | Services | service | host | baseAddress. The URI will be similar to this: Time_Addresses/DemoCalculationEngine/CalculationRequestService/. Now, if we run the client application, we can choose File | Add Service in the WCFTestClient tool to generate a proxy that will allow us to send a test request. If all is well, we’ll see the requests being queued in our client app, as shown next:
Add a SharePoint-Hosted WCF Service
Now that our client WCF service is up and running, our next logical step is to implement a WCF service that can be hosted within SharePoint to receive calculation results from our client application.
Hosting an .svc File in SharePoint To make our service available for our client application, we need to host it somewhere. Since SharePoint runs on Internet Information Server (IIS), we need to create a .svc file with details of our service implementation. Of course, before we create the file, we need somewhere to put it; for the purposes of this demonstration, we’ll use a custom subfolder within the %SPROOT%TEMPLATELayouts folder. We can set up this folder automatically using our Visual Studio project.
Token Replacement in Visual Studio Visual Studio 2010 allows the use of replaceable tokens when creating SharePoint solution packages. Our code sample makes use of the token $SharePoint.Project.AssemblyFullName$ that will be replaced when the package is built, by the four-part assembly name for the associated assembly. However, at the time of writing, no WCF template is available for SharePoint. Therefore, tokens are not automatically replaced in files with an .svc extension. Thankfully, this is a simple problem to resolve. Navigate to C:Program Files (x86)MSBuildMicrosoft VisualStudio v10.0 SharePoint Tools and then open the Microsoft.VisualStudio.SharePoint.targets file. This is an XML format file that defines various configuration settings for building SharePoint projects. Find the TokenReplacementFileExtensions element and append svc to the list of file extensions as shown:<TokenReplacementFileExtensions>$ (TokenReplacementFileExtensions);xml;aspx;ascx;
Adding WCF Service Configuration to SharePoint As well as an .svc file, IIS also needs to read the configuration of the WCF service from the web.config file. For the purposes of our demonstration, we’ll make the necessary changes manually.
We’re now ready to deploy the service to SharePoint. From the Build menu select Deploy WorkflowDemonstration. Visual Studio will now build the solution, create a WSP package, and then deploy the package to our SharePoint server. As we did for our client application, we can now make use of WCFTestClient to send a test call to our WCF service. layouts/WorkflowDemonstration/CalculationResultService.svc. If all is well, our service will return True when invoked as per our stub implementation.
Creating a Pluggable Workflow Service
Having set up the communications mechanism between the calculation engine and SharePoint, our next step is to create a pluggable workflow service that can be hooked up to our SharePoint service to broker requests between the WCF service and SharePoint’s workflow engine. Before we get into the code, I’ll show you how pluggable workflow services work. As mentioned, pluggable workflow services can be created by inheriting from SPWorkflowExternalDataExchangeService. External data exchange services, also known as local services, are a key component of the WF framework. Without local services, a workflow runtime has no means of communicating with the external environment, and in fact SharePoint defines two local services that allow the workflow runtime to communicate with the SharePoint platform itself: SPWinOEWSSService and SPWinOETaskService. For the most part, the SharePoint workflow activities that are available out of the box make use of these services for communication. Generally speaking, WF can be configured using a configuration file. The configuration can specify which services should be available to the runtime and how certain functions are performed. Since allowing changes to the configuration at this level could cause major support issues, Microsoft chose to disallow workflow configuration in SharePoint via the normal channels. In previous versions of SharePoint, this meant that no additional local services could be added. However, with SharePoint 2010, an additional configuration handler has been implemented that allows objects of type SP Workflow External DataExchange Service to be added to the workflow runtime. External data exchange services are created in a similar fashion to WCF services. An interface is defined that determines the methods and events that should be available to the workflow runtime. Once the interface is completed, a local service class based on SPWorkflow External Data Exchange Service and implementing the interface is created. Finally, the local service class is added to the configuration for the workflow runtime. Using the ExternalDataExchange Attribute Now that you understand how pluggable services work, let’s move on to our implementation. We first add an interface for our service. Add a new interface file to the Work flow Demonstration solution named IExternal Calculation Service.cs. Add the following code:using System;
NOTECreating workflow services requires references to System.Workflow.Activities and System.Workflow .Runtime. Notice a few things about this code sample. Firstly, the ExternalDataExchange attribute is used to let the workflow runtime know that the interface should be accessible to workflow activities. We’ll build up a workflow later to see this in action. Secondly, any events that are raised must be derived from the External Data Event Args class and must be serializable. The External Data Event Args class defines the base parameters that are required to route the event to the correct workflow instance. Because the workflow will most likely be running in a different application domain, events must be serializable in order to be passed to the runtime.Deriving from SPWorkflow External Data Exchange Service With the interface in place, we can move on to creating an implementation of the service.
Add a new class named CalculationWorkflowService and then add the following code to the Calculation Workflow Service.cs file:
The main thing worth mentioning with regard to this code sample isthe override of CallEventHandler. CallEventHandler is defined on the SPWorkflowExternalDataExchangeService base class and is used to relay events back to the workflow runtime with sufficient information to recover the relevant SharePoint context. CreateSubscription and DeleteSubscription are marked as MustInherit in the base class but are not required by our service and therefore have default implementations.
Calling a WCF Service The next step is to flesh out the implementation of the SubmitCalculation method. Sincethis is where we’ll make a call out to our external calculation service, we need to add aservice reference to generate the appropriate proxy.
public void SubmitCalculation(string product)
When a service reference is added to a project, Visual Studio automatically stores the binding and endpoint configuration in either app.config or web.config, depending on the type of project. In our case, the configuration has been added to app.config even though this file is not utilized by the SharePoint deployment mechanism. Since SharePoint runs on IIS, any configuration information has to be included in the appropriate web.config file. However, when it comes to workflow, storing information in web.config doesn’t work as expected. Depending on the state of the workflow, it will be running either within IIS or within a separate server process. The problem here is that configuration information that will be available when running under IIS will not be available when running under the server process. To avoid problems locating configuration data, it’s generally good practice to capture such information as part of the workflow association process. For the purposes of our demonstration, we’ll hard code the configuration information for now. In the SubmitCalculation method, add the following code:
One important thing to note about this code is the EndpointAddress. This should be the URI for the Demo Calculation Engine WCF service to which we added a reference. Receiving WCF Messages The next piece of functionality that we need to consider is raising the CalculationComplete event. This event will let our workflow know that the external calculation process has completed as well as provide the result of the calculation.
You’ll remember that when we added the SharePoint WCF service, we added a basic stub implementation for the ProcessCalculationResult method. We can now go back and revisit this since a call to this method ultimately signals that the calculation process has completed. Rather than have two separate objects, one for handling the Process Calculation Result message and another for passing that message onto the workflow, we can perform both tasks in a single method on the CalculationWorkflowService.
Raising Events in a Workflow Service
We can see that the ProcessCalculationResult makes use of the parameters received to create a reference to an SPWeb object. It then passes this reference together with a workflow instance identifier to the RaiseEvent method. As its name suggests, RaiseEvent is responsible for raising an event within the appropriate workflow instance. Before the event is queued for the appropriate workflow instance, the CallEventHandler method is called to populate an appropriate ExternalDataEventArgsderived object. Add the following code to the CallEventHandler override to populate our CalculationResultArgs structure before the event is passed to the workflow:public override void CallEventHandler(Type eventType,
Configuring Pluggable Workflow Services
You’ll remember that SharePoint 2010 introduces a new configuration handler for pluggable workflow services. The final step that we need to take to enable our service is to add a configuration entry in web.config. In web.config, navigate to the configuration | SharePoint | WorkflowServices section and then insert the following element:
Unfortunately, on this occasion, we don’t have the luxury of Visual Studio token replacement so we have to find the PublicKeyToken by examining the properties of the WorkflowDemonstration assembly within the Global Assembly Cache (GAC). With this done, we can deploy the project to SharePoint. We’ve now completed the implementation of our pluggable workflow service as well as our SharePoint-hosted WCF service. Although we could test the service using WCFTestClient, we’ll receive errors since no genuine workflow instances are awaiting a calculation response.
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.
NOTEWhen 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)
We can now manually trigger calculation results by selecting an item from the data grid and then clicking the Send Result button.
TIPWhen 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 Allowed Impersonation Level to Impersonation, as shown in the preceding code sample.
Share Point 2010 Related Interview Questions
|Web Services Interview Questions||XML Interview Questions|
|Share Point 2010 Interview Questions||ASP.NET Interview Questions|
|Share Point Administration Interview Questions||BizTalk Admin Interview Questions|
|Microsoft Office SharePoint Server (MOSS) Interview Questions||Biztalk Server Interview Questions|
|Asp Dot Net Mvc 4 Interview Questions||Biztalk Esb Toolkit Interview Questions|
|InfoPath Interview Questions|
Share Point 2010 Tutorial
The Microsoft Sharepoint 2010 Platform
Developing With Sharepoint 2010
Presentation Layer Overview
Client Object Model
Infopath Forms Services
Enterprise Content Management
User Interface Customization
Application Services Overview
Service Application Framework
Word Automation Services
Data Access Overview
Linq To Sharepoint And Spmetal
Business Connectivity Services
User Profiles And Social Data
Packaging And Deployment Model
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.