IT tutorials
 
Windows
 

Using the Windows Azure Service Bus with SharePoint (part 2) - Create the Listener Service

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
11/21/2012 9:30:08 AM

Create the Listener Service

  1. Open Microsoft Visual Studio 2010 and click File | New and then Project. Select Windows in the installed templates directory, and then select Console Application.

  2. Provide a name for your project (such as ListenerService), and click OK.

  3. Right-click the project and select Add Reference. Add three libraries to the new project: Microsoft.SharePoint.dll, System.ServiceModel.dll, and Microsoft.ServiceBus.dll.

  4. Right-click the project and select Properties. Click the Application tab and make sure that the Target framework (that is, the Microsoft .NET Framework) is set to .NET Framework 3.5. Also, click the Build tab and make sure that the Platform target is set to Any CPU.

  5. Right-click the project and add a new class. Provide a name for the class (such as AddSharePointDataService) and click Add.

  6. Amend the code in the newly added class as shown in the following bolded code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using Microsoft.SharePoint;
    
    namespace ListenerService
    {
        [ServiceBehavior(Name = "SharePointService", Namespace =
    "http://samples.microsoft.com/ServiceModel/Relay/")]
        public class AddSharePointDataService : IAddSharePointData
        {
            public string AddSharePointListItem(string contactName)
            {
                Console.WriteLine("Adding a record to SharePoint: {0}", contactName);
                using (SPSite mySiteCollection = new SPSite("http://blueyonderdemo/"))
                {
                    using (SPWeb myWeb = mySiteCollection.OpenWeb())
                    {
                        SPList myList = myWeb.Lists["Sales"];
                        SPListItem myListItem = myList.Items.Add();
                        myListItem["Title"] = "Acme";
                        myListItem["Contact"] = contactName;
                        myListItem["FY09"] = "$590,000.00";
                        myListItem["FY10"] = "$610,210.00";
                        myListItem["FY11"] = "$656,222.00";
                        myListItem.Update();
                    }
                }
                return contactName + " and related sales data was added.";
            }
        }
    }

    The preceding code is the core code that integrates with SharePoint and is the processing code in your listener service. It will accept a contact name (contactName) as a parameter and then add that parameter along with some hard-coded data into a SharePoint list called Sales. You’ll note that you need to initially set the context for SharePoint with the using statements. When you’ve set up the context for the SharePoint site, you can then access the specific list by using the Lists property, and then programmatically add the hard-coded values and the single passed parameter by assigning values to the list item fields (that is, myListItem[“Title”]). You push the changes to the server by finally calling the Update method.

    The code uses the SharePoint server object model because this service will live on the same server as the SharePoint site collection. You should note that if you’re trying to decide which way to integrate with SharePoint programmatically, the server object model performs well out of the APIs and web services natively available within SharePoint. However, if you intend to use the server object model, remember that your code must live on the SharePoint server, or you can use the SharePoint client object model for remote integration.

  7. Right-click the project and select Add | New Item. Then select Interface from the list of available items. Make sure you call your interface IAddSharePointData. The following bolded code represents the service interface contract for the service you created in the previous step:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text;
    using System.ServiceModel;
    
    namespace ListenerService
    {
        [ServiceContract(Name = "SharePointServiceContract", Namespace = "http://samples.
    microsoft.com/ServiceModel/Relay/")]
        public interface IAddSharePointData
        {
            [OperationContract]
            string AddSharePointListItem(string contact);
        }
    }
  8. Double-click Program.cs and amend the class as shown in the following bolded code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    using Microsoft.ServiceBus;
    using Microsoft.ServiceBus.Description;
    
    namespace ListenerService
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.Title = "SharePoint Listening Service";
    
                Console.Write("Namespace Domain: ");
                string nsDmn = Console.ReadLine();
                Console.Write("Name: ");
                string issrName = Console.ReadLine();
                Console.Write("Secret: ");
                string issrSecret = Console.ReadLine();
    
                Uri address = ServiceBusEnvironment.CreateServiceUri("sb",
                              nsDmn, "SharePointService");
    
                TransportClientEndpointBehavior sharedCreds = new
                    TransportClientEndpointBehavior();
                sharedCreds.CredentialType = TransportClientCredentialType.SharedSecret;
                sharedCreds.Credentials.SharedSecret.IssuerName = issrName;
                sharedCreds.Credentials.SharedSecret.IssuerSecret = issrSecret;
                try
                 {
    
                   ServiceHost svcHost = new ServiceHost(
                    typeof(AddSharePointDataService), address);
    
                    IEndpointBehavior svcRegSettings = new
                        ServiceRegistrySettings(DiscoveryType.Public);
    
                    foreach (ServiceEndpoint svcEndpoint in
                        svcHost.Description.Endpoints)
                    {
                        svcEndpoint.Behaviors.Add(sharedCreds);
                    }
    
                    svcHost.Open();
    
                    Console.WriteLine("Service information: " + address);
                    Console.WriteLine("Hit [Enter] to exit application...");
                    Console.ReadLine();
    
                    svcHost.Close();
                  }
                 catch (Exception e)
                   {
                    Console.Writline(e.ToString());
                   }
    
            }
        }
    }

    In the Program.cs file, the preceding code manages the creation of the WCF service endpoint instance that calls out to the AppFabric service bus. To do this, the instance of the service requires three main things: the domain namespace of the service (nsDmn), the management key name (issrName), and the management key secret (issrSecret). Using these three items, you can create and communicate across the service bus by constructing a service URI programmatically, and then assigning the specific security credentials to that URI. You then use the ServiceHost object to create an instance of the service class you created earlier in the exercise (AddSharePointDataService). Setting the DiscoveryType.Public in the service makes the service publicly visible, after which you add the service endpoint (svcEndpoint) with the appropriate credentials. Finally, you can open the service, which waits for the service to be called. You then close the service out after the user clicks the Enter button.

    Note that to get the three key variables, this console application prompts you to enter them. For your own testing purposes, you might hard-code these variables, because entering the secret key manually can be cumbersome.

  9. The last step to complete this example is to add an app.config file with the service configuration information in it. To add the file, right-click the project and select Add | New Item. Select General, and then click Application Configuration. Name the project app.config and amend the config file as follows:

    <?xml version="1.0"?>
    <configuration>
      <system.serviceModel>
        <services>
          <service name="ListenerService.AddSharePointDataService">
            <endpoint contract="ListenerService.IAddSharePointData"
              binding="netTcpRelayBinding"/>
          </service>
        </services>
      </system.serviceModel>
      <startup>
    <supportedRuntime version="v2.0.50727"/></startup>
    </configuration>

You’ve now completed the listener service. Let’s move on to the calling service.

Create the Calling Service

The calling service is a similarly constructed console application that prompts you for a contact name and then calls the listener service to interact with SharePoint.

  1. Open the Visual Studio solution you created in the previous exercise and select Add | New | Project.

  2. Select Windows, and then select Console Application.

  3. Provide a name for the project (such as CallingService) and click OK.

  4. Ensure that the properties are set to the same settings as in the previous exercise; that is, the target .NET Framework should be set to Microsoft .NET Framework 3.5 and the platform target to Any CPU.

  5. Right-click the project and select Add Reference. Add the System.ServiceModel.dll and Microsoft.ServiceBus.dll libraries to the project.

  6. Right-click the project and select Add | New Item, and then select Interface from the available items.

  7. Provide a name for the interface (such as ICallSharePointService) and click Add.

  8. Amend the interface code as shown in the following bolded code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using Microsoft.ServiceBus;
    
    namespace CallingService
    {
        [ServiceContract(Name = "SharePointServiceContract", Namespace =
    "http://samples.microsoft.com/ServiceModel/Relay/")]
        public interface ICallSharePointService
        {
                [OperationContract]
            string AddSharePointListItem(string contact);
        }
    }
  9. Double-click the Program.cs file and then amend the code as shown in the following bolded code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using Microsoft.ServiceBus;
    
    namespace CallingService
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                Console.Title = "SharePoint Calling Service";
    
                Console.Write("Namespace Domain: ");
                string nsDmn = Console.ReadLine();
                Console.Write("Name: ");
                string issrName = Console.ReadLine();
                Console.Write("Secret: ");
                string issrSecret = Console.ReadLine();
    
                Uri svcURI = ServiceBusEnvironment.CreateServiceUri("sb",
                              nsDmn, "SharePointService");
    
                TransportClientEndpointBehavior sharedCreds = new
                    TransportClientEndpointBehavior();
                sharedCreds.CredentialType = TransportClientCredentialType.SharedSecret;
                sharedCreds.Credentials.SharedSecret.IssuerName = issrName;
                sharedCreds.Credentials.SharedSecret.IssuerSecret = issrSecret;
    
                ChannelFactory<ICallSharePointService> channelFactory = new
                    ChannelFactory<ICallSharePointService>("RelayEndpoint",
                    new EndpointAddress(svcURI));
    
                channelFactory.Endpoint.Behaviors.Add(sharedCreds);
    
                ICallSharePointService channel = channelFactory.CreateChannel();
                ((ICommunicationObject)channel).Open();
    
                Console.WriteLine("Enter contact name to add to SharePoint:");
                string input = Console.ReadLine();
                while (input != String.Empty)
                {
                    try
                    {
                        Console.WriteLine("Contact added: {0}",
                           channel.AddSharePointListItem(input));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: " + e.Message);
                    }
                    input = Console.ReadLine();
                }
                ((ICommunicationObject)channel).Close();
                channelFactory.Close();
            }
        }
    }

    You can see many similarities in the base service creation code here because you are essentially creating a second service endpoint that also uses the AppFabric service bus. In this case, though, the code uses the ChannelFactory class to programmatically create the service endpoint, and you’re entering some data (the contact name) that it reads and passes to the AddSharePointListItem method.

  10. To complete this example, add an app.config file with the service configuration information in it. To add the file, right-click the project and select Add | New Item. Select General, and then click Application Configuration. Name the file app.config and update its contents as follows:

    <?xml version="1.0"?>
    <configuration>
      <system.serviceModel>
        <client>
          <!-- Application Endpoint -->
          <endpoint name="RelayEndpoint" contract="CallingService.ICallSharePointService"
            binding="netTcpRelayBinding"/>
        </client>
      </system.serviceModel>
      <startup>
    <supportedRuntime version="v2.0.50727"/></startup>
    </configuration>

You’ve now completed both the listener and the calling service, so you’re ready to test their interaction with SharePoint via the service bus. To test the services, right-click the ListenerService project and select Debug | Start New Instance. Enter the required information when requested in the console application (the namespace, name, and secret key). When the application responds with “Hit [Enter] To Exit Application…”, return to Visual Studio and right-click the CallingService project. Select Debug | Start New Instance from the context menu. Add the information when requested, and then enter a name when asked (such as Brian Smith) in the Enter Contact Name To Add To SharePoint field. Press Enter.

The two services will communicate by using the service bus, and the code within the ListenerService application will add a record to SharePoint using the name you entered as the contactName parameter.

Figure 2 shows the ListenerService application running and then providing an update on a record being added to SharePoint.

Figure 3 shows the CallingService application with the contact (and SharePoint record) added to SharePoint.

Finally, Figure 4 shows the newly added record in SharePoint. The name you entered in the console application was passed as a parameter by using the service bus, and then the hard-coded information in the SharePoint server object model code was used to update the record in SharePoint.

The listener service being called and showing status for an added record.

Figure 2. The listener service being called and showing status for an added record.

The calling service waiting to be called.

Figure 3. The calling service waiting to be called.

The added record from the listener service as it appears in SharePoint.

Figure 4. The added record from the listener service as it appears in SharePoint.

The ListenerService and CallingService applications demonstrated how to communicate across the AppFabric service bus to interact with SharePoint; however, in reality you’d probably need a slightly different architecture than two simple services talking to one another. With that in mind, the next set of exercises walks through the creation of an on-premises service and then shows you how you can use the AppFabric service bus to mediate a WCF service that is deployed to Windows Azure. This is a much more powerful design, because you now abstract the ability to interact with SharePoint and the service bus away from the server on which SharePoint resides. This means that the consuming client application can be a mobile device, such as a Windows Phone 7 application, or it can be SharePoint Online in Microsoft Office 365 or another .NET Framework application. The point is that you can create an abstracted service layer for your SharePoint site that cuts across devices and platforms—and is usable by anything that can consume a WCF service endpoint.

 
Others
 
- Using the Windows Azure Service Bus with SharePoint (part 1) - Create a Service Bus Namespace
- Windows 8 : Working with User Accounts (part 3) - Switching Users
- Windows 8 : Working with User Accounts (part 2) - Changing User Account Settings
- Windows 8 : Working with User Accounts (part 1) - Add a User
- Mac OS X Hints
- Securing Your Windows 8 Computer : Maintaining Your Privacy
- Securing Your Windows 8 Computer : Switching to a Local Account
- Buyers' Guide : Mac Dreams (Part 3) - iPod classic, iPod Touch, iPod nano, iPod shuffle
- Buyers' Guide : Mac Dreams (Part 2) - MacBook Pro Retina Display, Mac mini, iPhone 5, New iPad
- Buyers' Guide : Mac Dreams (Part 1) - Mac Pro, iMac, MacBook Pro, MacBook Air
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
Technology FAQ
- Is possible to just to use a wireless router to extend wireless access to wireless access points?
- Ruby - Insert Struct to MySql
- how to find my Symantec pcAnywhere serial number
- About direct X / Open GL issue
- How to determine eclipse version?
- What SAN cert Exchange 2010 for UM, OA?
- How do I populate a SQL Express table from Excel file?
- code for express check out with Paypal.
- Problem with Templated User Control
- ShellExecute SW_HIDE
programming4us programming4us