Service Remoting with Service Bus - Johns Hopkins University



Hands-On LabAppFabric: Service Remoting With Service BusLab version:1.0.0Last updated: DATE \@ "M/d/yyyy" 12/22/2009Contents TOC \h \z \t "Heading 3,2,pp Topic,1,PP Procedure start,3" Overview PAGEREF _Toc249260768 \h 3Exercise 1: Using the Service Bus to Host Services Remotely PAGEREF _Toc249260769 \h 6Task 1 – Running the Service On-Premise PAGEREF _Toc249260770 \h 7Task 2 – Provisioning and Configuring the AppFabric Project PAGEREF _Toc249260771 \h 11Task 3 – Configuring AppFabric Access Control for Authentication PAGEREF _Toc249260772 \h 17Task 4 – Configuring the Service to Listen on the AppFabric Service Bus PAGEREF _Toc249260773 \h 25Task 5 – Configuring the Client Application to Connect to a Service on the AppFabric Service Bus PAGEREF _Toc249260774 \h 30Verification PAGEREF _Toc249260775 \h 32Exercise 2: Publishing Services Hosted in Windows Azure with the Service Bus PAGEREF _Toc249260776 \h 34Task 1 – Hosting the Service in a Windows Azure Worker Role PAGEREF _Toc249260777 \h 35Task 2 – (Optional) Configuring the CRM Data Service to Listen on the AppFabric Service Bus PAGEREF _Toc249260778 \h 44Verification PAGEREF _Toc249260779 \h 47Summary PAGEREF _Toc249260780 \h 49Appendix 1 - Using the AppFabric Access Control Management Command Line Tool PAGEREF _Toc249260781 \h 50OverviewDue to recent bank regulation, the Fictional Bank is ordered to split into two separate banking entities: Fictional Investment and Fictional Retail. The IT department needs to restructure the existing customer relationship management such that both banking entities can continue to share customer data even though they are no longer within the same corporate network boundary. The existing CRM Web services in Fictional Bank are largely written using Windows Communication Foundation and hosted on-premise.Initially, the IT department decides to continue hosting the CRM Web services on-premise, at Fictional Investment. To achieve the goal of providing services to both entities, they choose to expose a subset of the CRM functionality through a second service, which they publish externally using the AppFabric Service Bus, thus allowing clients at Fictional Retail access to the required functionality. This solution enables them to accomplish their objective with minimal changes to the service and client applications, which are mostly limited to WCF configuration changes.In a second phase, Fictional Investment outsources its application services hosting. As a result, they relocate the service that they share with Fictional Retail to Windows Azure and host it in a worker role. Despite its new location, and because the Service Bus namespace allows the service to continue to be published at its present location, clients remain unaware of the change.This Hands-On lab walks you through this scenario using a sample application that replicates, albeit in a simplistic manner, the application architecture at Fictional Bank.ObjectivesIn this Hands-On Lab, you will learn how to:Provision AppFabric projects and service namespacesManage Access Control issuers and rules to provide service and client authenticationHost services on-premise and publish then remotely using the Service BusPublish services hosted in Windows Azure using the Service BusPrerequisitesThe following is required to complete this Hands-On Lab:IIS 7 (with , WCF HTTP Activation)Microsoft .NET Framework 3.5 SP1Microsoft Visual Studio 2008 SP1 (or above)Windows Azure Tools for Microsoft Visual Studio (November 2009)Windows Azure platform AppFabric SDKYou must have Internet access to complete the lab.SetupFor convenience, much of the code used in this hands-on lab is available as Visual Studio code snippets. To check the prerequisites of the lab and install the code snippets:Run the SetupLab.cmd script located in the lab's Source\Setup folder to check dependencies and install any missing prerequisites.Once you have verified every prerequisite, follow the instructions to install the code snippets. Using the Code SnippetsWith code snippets, you have all the code you need at your fingertips. The lab document will tell you exactly when you can use them. For example, To add this code snippet in Visual Studio, you simply place the cursor where you would like the code to be inserted, start typing the snippet name (without spaces or hyphens), in this case LabNameEx01RunmethodCS, watch as Intellisense picks up the snippet name, and then hit the TAB key twice once the snippet you want is selected. The code will be inserted at the cursor location. Figure 1Hit TAB to select the highlighted snippet.Figure 2Hit TAB again and the snippet will expandTo insert a code snippet using the mouse rather than the keyboard, right-click where you want the code snippet to be inserted, select Insert Snippet followed by My Code Snippets and then pick the relevant snippet from the list.To learn more about Visual Studio IntelliSense Code Snippets, including how to create your own, please see Hands-On Lab comprises the following exercises:Using the Service Bus to Host Services RemotelyPublishing Services Hosted in Windows Azure with the Service BusEstimated time to complete this lab: 45 minutes.Exercise 1: Using the Service Bus to Host Services RemotelyIn this exercise, you start with a solution that implements the Fictional Bank application architecture. The solution consists of two web services hosted by Fictional Investment. The first service, the CRM Data Service, provides application services for Fictional Investment. A second service, the FI Public Service, makes use of the first and exposes a subset of the CRM functionality to make it available to users in Fictional Retail.Figure 3Application architecture with services and clients directly connected Initially, you run the service to reproduce a scenario where all services are hosted on-premise and communicate directly with their clients using a NetTcpBinding. Such a scenario is feasible when all services reside within the same network and there are no intervening firewalls or Network Address Translation (NAT) devices along the path. Nonetheless, Fictional Retail clients are not located within Fictional Investment’s network. In order to make the services externally accessible to Fictional Retail clients, you then update the WCF configuration to expose the FI Public Service over the Service Bus using a NetTcpRelayBinding and a public endpoint address. This makes the service reachable from anywhere and allows you to fulfill one of the goals in the proposed scenario. Task 1 – Running the Service On-PremiseIn this task, you run the solution and test it locally using a NetTcpBinding to replicate the fully on-premise scenario, with services and clients located within the same network boundary.Open Microsoft Visual Studio 2008 from Start | All Programs | Microsoft Visual Studio 2008.In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex1-ServiceRemotingWithServiceBus\Begin in the Source folder of this lab, select ServiceRemoting.sln in the folder for the language of your preference (Visual C# or Visual Basic) and click Open. The solution contains the following projects:CommonA library project, shared by all the projects in the solution, containing the service and data contracts as well as the client proxies for the Web services in the application FictionalInvestment.Crm.DataA console application that hosts the CRM application services for Fictional BankFictionalInvestment.PublicServicesA console application that hosts the public service for Fictional BankFictionalRetail.Crm.ClientA Windows Forms application that uses the public services provided by the CRMFigure 4Solution Explorer showing the CRM application components (C#)Figure 5Solution Explorer showing the CRM application components (VB)Configure the solution to launch the client and both the CRM Data Service and the FI Public Service simultaneously. To do this, in Solution Explorer right-click the ServiceRemoting solution and select Set StartUp Projects. In the Solution 'ServiceRemoting' Property Pages dialog, select the Multiple startup projects option. Then, set the Action for the Fictional.Investment.Crm.Data, Fictional.Investment.PublicServices, and FictionalRetail.Crm.Client projects to Start and ensure that the order of the projects is as shown in the figure below. To change the starting order, select a project in the list and click the up or down arrow to move it. Press OK to confirm your changes.Figure 6Configuring the start up order of the projects in the solutionPress F5 to build the solution and start the services and the client application.Notice that each service displays the URL where it listens and that both services, the CRM Data Service and the FI Public Service, are currently using net.tcp and listen at the loopback address.Switch to the Fictional Retail CRM Client application. The UI presents a list of customers and their current assignment to one of the two banking entities. Move one or more customers from Fictional Investment to Fictional Retail by selecting the check box next to each customer's name and clicking Move to Fictional Retail Bank. Confirm that the operation succeeds by observing the status messages in the console windows of the CRM Data Service and the FI Public Service. Figure 7Testing the on-premise scenario with a NetTcpBindingNote: The client application invokes the ListCustomers operation of the CRM service to retrieve the list of customers and the MoveCustomersToBankingEntity operation of the service to transfer the customers to another entity.Press ENTER in both console windows to terminate the services and then exit the client application.Task 2 – Provisioning and Configuring the AppFabric ProjectTo use the Service Bus, you need to create a Windows Azure AppFabric Project and define a service namespace for your application. In this task, you provision the AppFabric account and configure it.Navigate to . You will be prompted for your Windows Live ID credentials if you are not already signed in.If this is your first visit to the portal, you need to sign up by creating a new AppFabric project. Enter a Project Name, for example, your company name or your own name, accept the Terms of Use and click the OK button. Figure 8Creating an AppFabric project in the Windows Azure portalIn the My Projects page, click the link for the newly created project to display its information page.Now, add a Service Namespace to your new project. A service namespace provides an application boundary for each application exposed through the Service Bus. To create a namespace, click the Add Service Namespace link.Figure 9AppFabric project information pageEnter a name for your Service Namespace, select a Region for your service to run in, and click the Create button. Make sure to validate the availability of the name first. Service names must be globally unique as they are hosted in the cloud and accessible by whomever you decide to grant access.Figure 10Creating a new service namespacePlease be patient while your service is activated. It can take several minutes for the provisioning to complete. Note: You may need to refresh your browser to show that the service is active. Once the namespace is active, click its name in the list of available namespaces to display the Service Namespace information page. Figure 11Project summary page listing available service namespacesIn the Service Namespace information page, locate the Service Bus section and record the value shown for Default Issuer Key. You will need this value later on, when you set up authentication for your service using the Access Control.Figure 12Service namespace information pageYou have now created a new AppFabric project and defined a namespace for this hands-on lab. To sign in at any time, simply navigate to , click Sign In and provide your Live ID credentials. Clicking the AppFabric tab on the left will list the AppFabric projects associated with your account. Figure 13My Projects page showing available AppFabric projects Task 3 – Configuring AppFabric Access Control for AuthenticationThe Windows Azure platform AppFabric Access Control (AC) service controls Service Bus authentication. You can take advantage of AC to authenticate a host that listens on the Service Bus as well as clients that use the bus to connect to the service. An issuer in Access Control represents a trusted application. Using AC, you can create rules to map incoming claims from trusted identity providers into claims issued by AC that an application or service consumes. More specifically, in the case of the Service Bus, these rules map the identity of the issuer into a series of claims that Service Bus uses to determine which actions the issuer is allowed to perform. For example, a Listen claim issued by AC allows an application to expose services on the Service Bus, while a Send claim allows it to send messages.A management service allows you to administer Access Control resources using a REST API, including its trusted issuers and the transformation rules. The AppFabric SDK includes both a command line tool (ACM.EXE) and a graphical user interface application known as the AppFabric AC Management Browser (ACMBROWER.EXE) that you can use for managing Access Control service resources.In this task, you use the management browser GUI tool to create two issuers, one issuer for Fictional Investment and another one for Fictional Retail. Then, you create rules to map the identity of the Fictional Investment issuer to the Listen and Send claims, allowing it to publish a service and send messages, and a second rule to map the identity of the Fictional Retail issuer to the Send claim, so that it can connect and send messages to services published on the Service Bus.Note: For an alternative procedure that uses the command line tool to create issuers and Access Control rules, see Appendix 1 - Using the AppFabric Access Control Management Command Line Tool.Launch the AcmBrowser.exe tool located in the Assets\AcmBrowser folder inside the Source folder of this lab. Note: You can find the source code for the AcmBrowser tool as a sample in the AppFabric SDK. A copy of the code is included in the Source\Assets folder of the lab and built during the setup procedure of the lab. Make sure that you run the setup script of the lab to create the executable file; otherwise, build the project manually by loading and compiling the solution in Visual Studio. In the Service Namespace field located in the toolbar area of the management browser, enter the name of the service namespace you defined earlier and append an "-sb" suffix to this value. For example, for the "fictionalnvestment" namespace, enter "fictionalInvestment-sb" as the value for this setting. Next, set the Management Key setting to the value of the Default Issuer Key for the service namespace that you recorded in the previous task, when you created the namespace. Then, click the Load from Cloud button to load the information for the namespace.Figure 14Loading a service namespace in the management browser toolCreate an issuer for the Fictional Investment entity. Recall that an issuer in the Access Control represents a trusted application or service. To create an issuer, right-click the Issuers node in the Resources tree view and choose Create. In the Create New Issuer dialog, enter the information shown in the table below and click OK to create the new issuer.Display NameFictionalInvestment (Service)AlgorithmSymmetric256BitKeyIssuer NamefictionalInvestmentCurrent KeyClick the Generate button to auto-generate a keyPrevious KeyClick the Generate button to auto-generate a key Figure 15Creating an Access Control issuer for the serviceNote: This step creates an issuer with a friendly name of "FictionalInvestment (Service)" and an issuer name of "fictionalInvestment". Now, create an issuer for the Fictional Retail entity. Again, right-click the Issuers node in the Resources tree view and choose Create. In the Create New Issuer dialog, enter the following information and click OK to create the new issuer.Display NameFictionalRetail (Client)AlgorithmSymmetric256BitKeyIssuer NamefictionalRetailCurrent KeyClick the Generate button to auto-generate a keyPrevious KeyClick the Generate button to auto-generate a key Figure 16Creating an Access Control issuer for the client applicationNote: This step creates an issuer with a friendly name of "FictionalRetail (Client)" and an issuer name of "fictionalRetail". Now, create a rule to grant Listen rights to the fictionalInvestment issuer. To create a rule, expand the Scopes node in the Resources tree view, right-click the Rules node for the service bus scope of your service namespace and select Create. In the Create New Rule dialog, enter the following information and click OK to create the new rule.Display NamefiListenTypeSimpleInput Claim - IssuerFictionalInvestment (Service)Input Claim - TypeIssuerInput Claim - ValuefictionalInvestmentOutput Claim - Typenet.windows.servicebus.actionOutput Claim - ValueListen Figure 17Creating an Access Control rule to grant listen rights to the serviceNote: A rule describes the logic executed when a request from a certain issuer to obtain a token for a certain resource is received. Given an incoming claim type and value, it specifies which claim type and value is included in the token that the AppFabric AC issues in response. The value of the outgoing claim specifies whether the service allows access to the resource or action being requested (if access is denied, there will not be an outgoing claim).In this case, the rule maps the issuer ID for Fictional Investment into a Listen Service Bus action.Add a second rule for the fictionalInvestment issuer to grant it Send rights. Repeat the procedure used in the previous step, using the following values this time.Display NamefiSendTypeSimpleInput Claim - IssuerFictionalInvestment (Service)Input Claim - TypeIssuerInput Claim - ValuefictionalInvestmentOutput Claim - Typenet.windows.servicebus.actionOutput Claim - ValueSendFigure 18Creating an Access Control rule to grant send rights to the serviceNote: Granting Send rights to the fictionalInvestment issuer is in preparation for Exercise 2, when the CRM Data Service is published on the Service Bus and the FI Public Service becomes a client of the CRM Data Service.Finally, create a rule to grant Send rights to the fictionalRetail issuer using the values shown in the following table.Display NamefrSendTypeSimpleInput Claim - IssuerFictionalRetail (Client)Input Claim – TypeIssuerInput Claim – ValuefictionalRetailOutput Claim - Typenet.windows.servicebus.actionOutput Claim - ValueSendFigure 19Creating an Access Control rule to grant Send rights to the clientNote: You have now created issuers for both the service and the client application and set up rules for the service issuer to grant it Listen and Send privileges and for the client application permission to Send.Record the value assigned for the Current Key for the FictionalInvestment (Service) and for the FictionalRetail (Client) issuers. You will require these values later.Figure 20Retrieving the key assigned to an issuerTo save your changes, first click the Clear Service Namespace in Cloud button on the toolbar. Figure 21Service Bus scope showing the newly created rulesWhen prompted, confirm that you want to delete all the resources in the service namespace.Figure 22Deleting all resources in the service namespaceFinally, click Save to Cloud on the toolbar of the application.Figure 23Updating the service bus namespaceTask 4 – Configuring the Service to Listen on the AppFabric Service BusThe FI Public Service registers its endpoint with the Service Bus, which exposes the service through specific, discoverable URIs and makes it available to anyone regardless of where they are located, even when the service sits behind a firewall.Figure 24Application architecture with services and clients connected via the Service BusPublishing the FI Public Service on the Service Bus is very simple to do. You only need to add a reference to the Service Bus assembly, change the binding used by the service from NetTcpBinding to NetTcpRelayBinding, and update the endpoint address of the service to its new location in the cloud. In this task, you update the Fictional Bank application to publish and consume the services it provides over the Service Bus.If not already open, launch Microsoft Visual Studio 2008 from Start | All Programs | Microsoft Visual Studio 2008.In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex1-ServiceRemotingWithServiceBus\Begin in the Source folder of this lab, select Begin.sln in the folder for the language of your preference (Visual C# or Visual Basic) and click Open. Add a reference to the Service Bus assembly in the FI Public Service project. To do this, in Solution Explorer, right-click the FictionalInvestment.PublicServices project and select Add Reference. In the .NET tab, select the Microsoft.ServiceBus assembly and click OK.Figure 25Adding a reference to the Microsoft.ServiceBus assemblyOpen the App.config file of the FictionalInvestment.PublicServices project.In the services section of system.ServiceModel, locate the endpoint element for the service named FictionalInvestment.PublicServices.CrmPublicService. For this endpoint, update the value of the address attribute to sb://[YOUR-NAMESPACE].servicebus.CrmPublicService, where [YOUR_NAMESPACE] is the Service Bus namespace that you defined for your project.Note: The service namespace provides an application boundary for each application exposed through the Service Bus. You define namespaces at the Windows Azure Developer Portal.Next, change the value of the binding attribute from netTcpBinding to netTcpRelayBinding.Finally, add a new behaviorConfiguration attribute to the endpoint element and set its value to serviceBusCredentialBehavior. You will define this behavior in the next step. The updated endpoint element should appear as shown in the figure below, except for the namespace that should match your own. Figure 26Configuring the endpoint used to publish the service on the Service BusInside system.serviceModel, provide the behavior configuration that you specified for the endpoint in the previous step. This behavior provides the Service Bus with the credentials required to authenticate the service publisher. To supply the credentials, insert a behaviors element as shown in the following (highlighted) configuration fragment. Replace the value of the issuerSecret attribute with the Current Key for the fictionalInvestment issuer that you recorded in the previous task, when you created the issuer.(Code Snippet - Service Remoting with Service Bus Lab - Ex01 CredentialsBehavior)XML<configuration> <system.serviceModel> <services> ... </services> <client> ... </client> <behaviors> <endpointBehaviors> <behavior name="serviceBusCredentialBehavior"> <transportClientEndpointBehavior credentialType="SharedSecret"> <clientCredentials> <sharedSecret issuerName="fictionalInvestment" issuerSecret="[YOUR_FI_ISSUER_KEY]" /> </clientCredentials> </transportClientEndpointBehavior> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel></configuration>To complete the changes required to publish the service on the Service Bus, configure the connectivity mode of the service. Open the Program.cs file (for Visual C# projects) or Module1.vb file (for Visual Basic projects) in the FictionalInvestment.PublicServices project and insert the following (highlighted) code at the start of method Main.(Code Snippet - Service Remoting with Service Bus Lab - Ex01 ConnectivityMode - CS)C#internal static void Main(){ // Tcp: All communication to the Service Bus is performed using outbound TCP connections. // Http: All communication to Service Bus is performed using outbound HTTP connections. // AutoDetect: The Service bus client automatically selects between TCP and HTTP connectivity. Microsoft.ServiceBus.ServiceBusEnvironment.SystemConnectivity.Mode = Microsoft.ServiceBus.ConnectivityMode.AutoDetect; using (ServiceHost serviceHost = new ServiceHost(typeof(CrmPublicService))) { ... }}(Code Snippet - Service Remoting with Service Bus Lab - Ex01 ConnectivityMode - VB)Visual BasicSub Main() ' Tcp: All communication to the Service Bus is performed using outbound TCP connections. ' Http: All communication to Service Bus is performed using outbound HTTP connections. ' AutoDetect: The Service bus client automatically selects between TCP and HTTP connectivity. Microsoft.ServiceBus.ServiceBusEnvironment.SystemConnectivity.Mode = Microsoft.ServiceBus.ConnectivityMode.AutoDetect Using serviceHost As New ServiceHost(GetType(CrmPublicService)) serviceHost.Open() ... End UsingEnd SubNote: The default connection mode between the listener service and the AppFabric Service Bus is TCP. However, if the network environment does not allow outbound TCP connections beyond HTTP, for example, because of changes in Fictional Investment’s IT policy, you can configure the corresponding binding to use an HTTP connection to communicate with the Service Bus.For most scenarios, it is recommended that you set the Mode to AutoDetect. This indicates that your application will attempt to use TCP to connect to the Service Bus, but will use HTTP if unable to do so. Task 5 – Configuring the Client Application to Connect to a Service on the AppFabric Service BusIn the previous task, you configured the service to listen on the Service Bus. In this task, you set up the client application in a similar manner to allow it to connect to the service.Add a reference to the Service Bus assembly in the client application project. To do this, in Solution Explorer, right-click the FictionalRetail.Crm.Client project and select Add Reference. In the .NET tab, select the Microsoft.ServiceBus assembly and click OK.Open the App.config file in the FictionalRetail.Crm.Client project.Locate the single endpoint element in the client section of system.serviceModel. Change the value of the address for the endpoint to sb://[YOUR-NAMESPACE].servicebus.CrmPublicService, where [YOUR_NAMESPACE] is the Service Bus namespace that you defined for your project. Next, change the value of the binding attribute from netTcpBinding to netTcpRelayBinding.To complete the endpoint configuration, add a new behaviorConfiguration attribute to the endpoint element and set its value to serviceBusCredentialBehavior. Note that here you essentially apply the same changes to the client that you made to the service configuration. The updated service element should appear as shown in the figure below.Figure 27Configuring the client to consume a service on the Service BusFinally, add a behaviors element to the system.serviceModel section as shown below to define the behavior configuration that you specified for the endpoint in the previous step. This behavior provides the Service Bus with the credentials required to authenticate the client application. Replace the value of the issuerSecret attribute with the Current Key for the fictionalRetail issuer that you recorded in the previous task, when you created the issuer. (Code Snippet - Service Remoting with Service Bus Lab - Ex01 CredentialsBehaviorClient)XML<configuration> <system.serviceModel> <client> ... </client> <behaviors> <endpointBehaviors> <behavior name="serviceBusCredentialBehavior"> <transportClientEndpointBehavior credentialType="SharedSecret"> <clientCredentials> <sharedSecret issuerName="fictionalRetail" issuerSecret="[YOUR_FR_ISSUER_KEY]" /> </clientCredentials> </transportClientEndpointBehavior> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel></configuration>Set the connectivity mode of the client application. Right-click the Main.cs file (for Visual C# projects) or Main.vb file (for Visual Basic projects) in the FictionalRetail.Crm.Client project and select View Code, then insert the following (highlighted) code at the start of the constructor for the Main class.(Code Snippet - Service Remoting with Service Bus Lab - Ex01 ConnectivityModeClient - CS)C#public Main(){ // Tcp: All communication to the Service Bus is performed using outbound TCP connections. // Http: All communication to Service Bus is performed using outbound HTTP connections. // AutoDetect: The Service bus client automatically selects between TCP and HTTP connectivity. Microsoft.ServiceBus.ServiceBusEnvironment.SystemConnectivity.Mode = Microsoft.ServiceBus.ConnectivityMode.AutoDetect; this.client = new PublicServiceClient(); this.InitializeComponent();}(Code Snippet - Service Remoting with Service Bus Lab - Ex01 ConnectivityModeClient - VB)Visual BasicPublic Sub New() ' Tcp: All communication to the Service Bus is performed using outbound TCP connections. ' Http: All communication to Service Bus is performed using outbound HTTP connections. ' AutoDetect: The Service bus client automatically selects between TCP and HTTP connectivity. Microsoft.ServiceBus.ServiceBusEnvironment.SystemConnectivity.Mode = Microsoft.ServiceBus.ConnectivityMode.AutoDetect Me.client = New PublicServiceClient() Me.InitializeComponent()End SubVerificationYou are now ready to test the application using the Service Bus.Configure the solution to launch both the CRM Data Service and the FI Public Service simultaneously. To do this, in Solution Explorer, right-click the ServiceRemoting solution and select Set StartUp Projects. In the Solution 'ServiceRemoting' Property Pages dialog, select the Multiple startup projects option, then set the Action for the Fictional.Investment.Crm.Data and Fictional.Investment.PublicServices projects to Start and in that same starting order; set the remaining projects to None. To change the starting order, select a project in the list and click the up or down arrow to move it.Note: Because the service may take slightly longer to start listening when hosted on the Service Bus, this time, you start the client application manually to ensure that the service has already started.Press F5 to build and run the application. This launches both the CRM Data Service and the FI Public Service.Wait for both services to start and show their status in their respective console windows. Notice the URL at which the FI Public Service is listening and how its scheme is now “sb:” and the URI contains your service namespace.Note: Do not proceed with the next step until both services have started successfully. On startup, each service displays the URL where it is listening in its console window.In Solution Explorer, right-click FictionalRetail.Crm.Client, point to Debug and select Start new instance to start the client application.Notice that the client application presents the list of customers retrieved from the service showing that it successfully accessed the service published on the Service Bus.Select one or more customers from the list and click Move To Fictional Retail Bank.Figure 28CRM application working against the service published by the Service BusNotice that the client application continues to work as it did when the service was listening locally. This demonstrates that clients that are not located within the Financial Investment network are still able to connect to the service via the Service Bus.Press ENTER in both console windows to terminate the services and then exit the client application.Exercise 2: Publishing Services Hosted in Windows Azure with the Service BusAzure-hosted services can publish their endpoints using the Service Bus too. Figure 29Application architecture with services deployed to Windows Azure and listening on the Service BusIn this exercise, you update the FI Public Service project and convert it into a worker role. This allows you to host the service in Windows Azure. Because the service is already listening via the Service Bus, clients remain unaware of the change and continue to run with no changes to their code or their configuration. Nevertheless, in this scenario, the CRM Data Service remains on-premise and you now need to configure it to listen on the Service Bus in order for the FI Public Service to access it.Task 1 – Hosting the Service in a Windows Azure Worker RoleIn this task, you update the FI Public Service project, which is currently a Windows Console application, and convert it into a worker role.Open Microsoft Visual Studio 2008 in elevated administrator mode, from Start | All Programs | Microsoft Visual Studio 2008 by right clicking the Microsoft Visual Studio 2008 shortcut and choosing Run as Administrator.Note: Running in elevated administrator mode is required to run cloud projects in the Development Fabric.In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex2-AzureServicesUsingServiceBus\Begin in the Source folder of the lab, select ServiceRemoting.sln in the folder for the language of your preference (Visual C# or Visual Basic) and click Open. Alternatively, you may continue with the solution that you obtained after completing the previous exercise.Add a reference to the Windows Azure assemblies to the FI Public Service project. To do this, in Solution Explorer, right-click the FictionalInvestment.PublicServices project and select Add Reference. In the .NET tab, select the Microsoft.WindowsAzure.Diagnostics, Microsoft.WindowsAzure.ServiceRuntime and Microsoft.WindowsAzure.StorageClient components and click OK.Figure 30Adding a reference to the Windows Azure assembliesSeveral assemblies required by the service are not ordinarily present in a Windows Azure VM, so you must ship these assemblies with the service package to ensure that they are available. You do this by configuring the Copy Local property of the corresponding assembly reference.For Visual C# projects, to configure a reference, expand the References node for the FictionalInvestment.PublicServices project in Solution Explorer, right-click the corresponding reference in the References list, and select Properties. For Visual Basic projects, right-click the FictionalInvestment.PublicServices project in Solution Explorer and select Properties. In the Project Properties window, switch to the References tab, select the required assembly, and press F4.To add the assembly to the service package, in the Properties window of the assembly, change the value of the Copy Local setting to True.Use this procedure to include the Microsoft.ServiceBus assembly in the Windows Azure service package and ensure that both Microsoft.WindowsAzure.Diagnostics and Microsoft.WindowsAzure.StorageClient are deployed locally too.Figure 31Including an assembly in the Windows Azure service packageNext, create a new cloud service project and add it to the solution. In Solution Explorer, right-click the ServiceRemoting node, point to Add and select New Project. In the New Project dialog, expand the language of your preference (Visual C# or Visual Basic) in the project types list and select Cloud Service. In the Templates list, select Windows Azure Cloud Service, set the Name of the project to CloudService and accept the proposed location in the folder of the solution. Click OK to create the project.Figure 32Creating a new Windows Azure Cloud Service projectIn the New Cloud Service Project dialog, click OK without adding any new roles. You will repurpose the existing service project and use it as a worker role.Figure 33No additional roles are requiredAdd the FI Public Service project as a worker role in the cloud service project. In Solution Explorer, right-click the Roles node in the CloudService project, point to Add and then select Worker Role Project in Solution. In the Associate with Role Project dialog, select the FictionalInvestment.PublicServices project and click OK.Figure 34Adding the FI Public Service project as a worker roleNote: The FictionalInvestment.PublicServices project is an ordinary Windows Console Application project. Ordinarily, you would not use this type of application as the starting point for a worker role. In order for Visual Studio to recognize it as a worker role candidate and allow its name to appear in the Associate with Role Project dialog, it was necessary to modify the project (.csproj) file to specify its RoleType. To be able to use the existing service project as a worker role, you need to include a role entry point in the project. To insert a pre-built entry point class, in Solution Explorer, right-click the FictionalInvestment.PublicServices project, point to Add and select Existing Item. In the Add Existing Item dialog, navigate to Assets in the Source folder of this lab and select the WorkerRole.cs file (for Visual C# projects) or WorkerRole.vb file (for Visual Basic projects).Figure 35Solution Explorer showing the new worker role entry point class (C#)Figure 36Solution Explorer showing the new worker role entry point class (VB)Note: The WorkerRole class is a RoleEntryPoint derived class modified to host the service. It contains methods that Windows Azure calls at various stages during the lifetime of the role.Windows Azure invokes the OnStart method when the role starts. You can use this method to initialize the role. In the provided class, the OnStart method contains code to set up diagnostics settings that schedule an automatic transfer of the worker role logs to an Azure Storage account, where you can retrieve them. Note that the code initializes the Windows Azure Diagnostics configuration from a connection string in the service configuration file (ServiceConfiguration.cscfg), which is currently set to use Development Storage. If you deploy the service to Windows Azure, you need to update this configuration with your own Azure Storage account settings. The Run method of the WorkerRole class contains the code executed by the role to provide its functionality. In this case, it sets up a WCF ServiceHost for the FI Public Service and starts listening for requests on the Service Bus.Finally, Windows Azure calls the OnStop method just before it shuts down the worker role. Here, it is used to close the WCF service.Open the App.config file in the FictionalInvestment.PublicServices project and replace the entry for the existing listener, named configConsoleListener, with the entry shown (highlighted) in the following configuration fragment.(Code Snippet - Service Remoting with Service Bus Lab - Ex02 AzureDiagnosticsConfig)XML<configuration> ... <system.diagnostics> <trace> <listeners> <add name="AzureDiagnostics" type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </listeners> </trace> </system.diagnostics> ...</configuration>Note: In order to provide diagnostics information, the service uses the Trace class in System.Diagnostics to write informational events and status messages to the log. Previously, the service used a ConsoleTraceListener to display this information in its console window. Now, when hosted in Windows Azure, the service needs to write this information to a place where you can view it. It uses a TraceListener specific to the Windows Azure environment that writes trace data to the application logs. (Optional) If you run the service in the Development Fabric, you must skip this step. However, a Windows Azure VM does not store the required configuration for AppFabric in its machine.config file. If you are going to deploy the service to the cloud, you need to replicate the necessary settings in the configuration file of the service. To do this, open the App.config file in the FictionalInvestment.PublicServices project and insert the following (highlighted) block into the system.serviceModel section.(Code Snippet - Service Remoting with Service Bus Lab - Ex02 BehaviorExtensions)XML<system.serviceModel> ... <!-- START AppFabric SDK settings--> <extensions> <behaviorExtensions> <add name="transportClientEndpointBehavior" type="Microsoft.ServiceBus.Configuration.TransportClientEndpointBehaviorElement, Microsoft.ServiceBus, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </behaviorExtensions> <bindingExtensions> <add name="netTcpRelayBinding" type="Microsoft.ServiceBus.TcpRelayBindingCollectionElement, Microsoft.ServiceBus, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </bindingExtensions> </extensions> <bindings /> <!-- END AppFabric SDK settings--></system.serviceModel>Note: The configuration settings shown above are not necessary when hosting the service in your local machine using the Development Fabric. During its installation, the AppFabric SDK writes these settings to the machine.config file. You can find these extensions, which reference the Microsoft.ServiceBus assembly, in the system.serviceModel section of this file.AppFabric requires Full Trust to run in Windows Azure. To enable full-trust, in Solution Explorer, expand the Roles node in the CloudService project and double-click the FictionalInvestment.PublicServices role. In the role properties page, select the Configuration tab and ensure that the .NET trust level is set to Full Trust.Figure 37Configuring the trust level of the worker roleTask 2 – (Optional) Configuring the CRM Data Service to Listen on the AppFabric Service BusBecause the FI Public Service now runs in Windows Azure and relies on the CRM Data Service, which continues to be hosted on-premise, it is necessary to update the latter to listen on the Service Bus. Note: The procedure required to do this is no different from the one that you performed in Exercise 1, when you published the FI Public Service itself via the Service Bus. If you started the current exercise from the solution that you obtained after completing Exercise 1, then, you need to complete this task; otherwise, if you used the begin solution provided for the current exercise, then you can safely skip this task. All the necessary changes are already included in the begin solution.In either case, you DO still require to update the endpoint address and the credentials of the service in the App.config file of the FictionalInvestment.Crm.Data.CrmDataService project, as well as the endpoint address and credentials of the client in the App.config file of the FictionalInvestment.PublicServices project. This is simply because the values are specific to your AppFabric project. You will find instructions on how to do this in the Verification section of this exercise.Add a reference to the Service Bus assembly in the CRM Data Service project. To do this, in Solution Explorer, right-click the FictionalInvestment.Crm.Data project and select Add Reference. In the .NET tab, select the Microsoft.ServiceBus assembly and click OK.Open the App.config file of the FictionalInvestment.Crm.Data project.In the services section of system.ServiceModel, locate the endpoint element for the service named FictionalInvestment.Crm.Data.CrmDataService. For this endpoint, update the value of the address attribute to sb://[YOUR-NAMESPACE].servicebus.CrmDataService, where [YOUR-NAMESPACE] is the Service Bus namespace that you defined for your project.Next, change the value of the binding attribute from netTcpBinding to netTcpRelayBinding.Finally, add a new behaviorConfiguration attribute to the endpoint element and set its value to serviceBusCredentialBehavior. The updated endpoint element should appear as shown in the figure below, except for the namespace that should match your own. Figure 38Configuring the endpoint used to publish the CRM Data Service on the Service BusInside system.serviceModel, insert a behaviors element as shown in the following (highlighted) configuration fragment. Replace the value of the issuerSecret attribute with the issuer key for the fictionalInvestment issuer that you obtained during the previous exercise.(Code Snippet - Service Remoting with Service Bus Lab - Ex02 CredentialsBehaviorACS)XML<configuration> <system.serviceModel> <services> ... </services> <client> ... </client> <behaviors> <endpointBehaviors> <behavior name="serviceBusCredentialBehavior"> <transportClientEndpointBehavior credentialType="SharedSecret"> <clientCredentials> <sharedSecret issuerName="fictionalInvestment" issuerSecret="[YOUR_FI_ISSUER_KEY]" /> </clientCredentials> </transportClientEndpointBehavior> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel></configuration>The FI Public Services makes use of the CRM Data Service, which now requires publishing on the Service Bus too. To complete the preparations for the service, replace the existing client section in system.serviceModel with the configuration shown (highlighted) below after substituting [YOUR-NAMESPACE] with the service namespace that you created for this project.(Code Snippet - Service Remoting with Service Bus Lab - Ex02 ClientEndpoint)XML<configuration> <system.serviceModel> ... <client> <endpoint address="sb://[YOUR-NAMESPACE].servicebus.CrmDataService" binding="netTcpRelayBinding" contract="Common.Contracts.ICrmDataService" behaviorConfiguration="serviceBusCredentialBehavior" /> </client> ... </system.serviceModel></configuration>VerificationBefore you begin, you need to ensure that you have configured the service endpoints and the issuer credentials correctly. Depending on how you arrived at the current solution, some of these values may already have been set. Note that this is necessary because the values are specific to your AppFabric project. After that, you will run the cloud project in the Development Fabric and test it using the client application.Open the App.config file of the FictionalInvestment.PublicServices project. Locate the single endpoint element in the services section of system.ServiceModel and replace the placeholder identified as [YOUR_NAMESPACE] in the address attribute of the endpoint with the Service Bus namespace that you defined for your project. Do the same for the existing endpoint defined in the client section of system.ServiceModel.In the behaviors section, locate the sharedSecret element inside transportClientEndpointBehavior and update the isssuerSecret attribute with the issuer key for fictionalInvestment. Recall that you registered the keys for each issuer during Exercise 1.Next, open the App.config file of the FictionalInvestment.Crm.Data project and repeat the previous steps to update the namespace for the endpoint in the services section and the credentials in the behaviors section using the same values.Finally, open the App.config file for the FictionalRetail.Crm.Client project. Once again, update the namespace in the client section of system.serviceModel with your service namespace. Then, update the credentials in the behaviors section, but this time use the issuer key for fictionalRetail instead.You are now ready to test the solution. To launch the cloud service project in the Development Fabric, in Solution Explorer, right-click CloudService, point to Debug and select Start new instance. The worker role starts, creates the service host, and starts listening at the Service Bus endpoint. Notice the information messages in the event log for the worker role showing the status of the service. Figure 39FI Public Service hosted in the Development FabricNext, start the CRM Data Service. To do this, in Solution Explorer, right-click the FictionalInvestment.Crm.Data project, point to Debug and select Start new instance. Wait for the service to start listening at its configured endpoint on the Service Bus. Notice the URL where the service is currently listening displayed in the console window.Figure 40CRM Data Service listening on the Service BusNow, launch the client application. Once again, right-click FictionalRetail.Crm.Client in Solution Explorer, point to Debug and select Start new instance. As you saw previously, the UI shows the list of customers and their current assigned entity, which confirms that the client is able to communicate with the service.Select one or more customers in the list and click Move to Fictional Retail Bank. Confirm that the call succeeds by observing the status messages in the console window of the CRM Data Service and the event log of the worker role in the Development Fabric.Figure 41Using the FI Public Service hosted in the Development FabricSummaryBy completing this Hands-On lab, you saw how, with minimal changes to code and configuration, you can take an existing service and make it reachable from anywhere using the Service Bus. During the course of the lab, you learnt how to provision an AppFabric account and configure namespaces for you service. You took advantage of AppFabric Access Control to provide claims based authentication, creating rules that map an identity into claims that determine what actions an issuer is allowed to perform. Finally, you relocated a service to Windows Azure and saw how its clients are not affected by the change because the service continues to listen at the same URL, whether it is hosted on-premise or in the cloud.Appendix 1 - Using the AppFabric Access Control Management Command Line ToolThe following procedure describes the steps required to create issuers and rules using the AppFabric Access Control Management Command Line Tool. For an alternative that uses the Access Control Management Browser tool, see Task 3 in Exercise 1: Using the Service Bus to Host Services Remotely. Note that you do not need to complete this procedure if you have already created the issuers and set up Access Control rules using the Access Control Management Browser.Open a command prompt window and change the current directory to the Tools folder of the AppFabric SDK, which you will find in %ProgramFiles%\Windows Azure platform AppFabric SDK\V1.0, provided you installed the SDK to its default location.Open the Acm.exe.config file in this folder with a text editor, Visual Studio or Notepad for example. This file contains configuration settings for the Acm.exe command line tool.In the Acm.exe.config file, locate the appSettings section and set the value of the service setting to the namespace that you created previously at the services portal, after appending an "-sb" suffix to this value. For example, for the "fictionalnvestment" namespace, enter "fictionalInvestment-sb" as the value for this setting. Set the mgmtkey setting to the value of the Default Issuer Key for the service namespace, which you can retrieve from the service namespace page in the development portal.Figure 42Configuring common parameters for the ACM toolNote: All operations executed with the ACM tool require the host address of the management service (host), the name of the service namespace that you want to manage (service), and a management key for the service namespace assigned by the AppFabric portal (mgmtkey). Because all these options are required for every command, adding them to the application configuration file allows you omit these parameters from the command line when you execute a command.Create an issuer for the Fictional Investment entity. Recall that an issuer in the Access Control represents a trusted application or service. At the command prompt, enter the following command, ensuring that there are no whitespace characters between a parameter name and its value, and press mand Promptacm.exe create issuer -name:"FictionalInvestment (Service)" -issuername:fictionalInvestment -autogeneratekeyFigure 43Creating an Access Control issuer for the serviceNote: The command creates an issuer with a friendly name of "FictionalInvestment (Service)" and an issuer name of "fictionalInvestment". Now, create an issuer for the Fictional Retail entity. To do this, enter the command shown below and press mand Promptacm.exe create issuer -name:"FictionalRetail (Client)" -issuername:fictionalRetail -autogeneratekey Figure 44Creating an Access Control issuer for the client applicationNote: The command creates an issuer with a friendly name of "FictionalRetail (Client)" and an issuer name of "fictionalRetail". To configure the service and the client applications, you need to have the corresponding keys that AC assigned to each issuer. Access Control uses this key to verify the authenticity of an issuer. To retrieve this information, execute the following command to retrieve all registered issuers in your service namespace, including their mand Promptacm.exe getall issuerFrom the output of the previous command, record the value of the id and key properties for both the fictionalInvestment and fictionalRetail issuers. You use the id value to create the access control rules. In addition, you use the key property to configure the service and the client application. Figure 45Retrieving information for issuers in the service namespaceHaving created the issuers and retrieved their keys, you now create rules to map the claims presented by an issuer into permissions to execute certain operations in the Service Bus. First, you need to determine the ID of the Service Bus scope because this information is required to create new rules. At the command prompt, enter the following command and press ENTER. Command Promptacm.exe getall scopeFrom the output of the previous command, locate the Service Bus scope for your namespace and record its id.Figure 46Retrieving the Service Bus scope ID for the service namespaceNow, enter the following command to create a rule to grant Listen rights to the fictionalInvestment issuer ensuring that you replace [YOUR_SCOPE_ID] with the Service Bus scope ID, which you retrieved in the previous step, and [FICTIONALINVESTMENT_ISSUER_ID] with the ID of the fictionalInvestment issuer that you recorded earlier, when you enumerated all issuers. Command Promptacm.exe create rule -scopeid:[YOUR_SCOPE_ID] -inclaimissuerid:[FICTIONALINVESTMENT_ISSUER_ID] -inclaimtype:Issuer -inclaimvalue:fictionalInvestment -outclaimtype:net.windows.servicebus.action -outclaimvalue:Listen -name:fiListenFigure 47Creating a new Access Control ruleNote: The command creates a new rule for the Service Bus scope that maps the issuer ID for Fictional Investment into a Listen Service Bus action.Add a second rule for the fictionalInvestment issuer to grant it Send rights, as shown below. Use the same values for [YOUR_SCOPE_ID] and [FICTIONALINVESTMENT_ISSUER_ID] that you specified in the previous mand Promptacm.exe create rule -scopeid:[YOUR_SCOPE_ID] -inclaimissuerid:[FICTIONALINVESTMENT_ISSUER_ID] -inclaimtype:Issuer -inclaimvalue:fictionalInvestment -outclaimtype:net.windows.servicebus.action -outclaimvalue:Send -name:fiSendNext, create a rule for the fictionalRetail issuer using the same value that you used in the previous step for [YOUR_SCOPE_ID] and replacing [FICTIONALRETAIL_ISSUER_ID] with the ID of the fictionalRetail issuer. Ensure that this time you specify fictionalRetail for the inclaimvalue and Send for the outclaimvalue, which is different from the values used in the previous mand Promptacm.exe create rule -scopeid:[YOUR_SCOPE_ID] -inclaimissuerid:[FICTIONALRETAIL_ISSUER_ID] -inclaimtype:Issuer -inclaimvalue:fictionalRetail -outclaimtype:net.windows.servicebus.action -outclaimvalue:Send -name:frSendYou have now created issuers for both the service and for the client application and set up rules for the service issuer to grant it Listen and Send privileges and for the client application permission to Send. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download