+ All Categories
Home > Documents > SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… ·...

SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… ·...

Date post: 13-Jul-2020
Category:
Upload: others
View: 5 times
Download: 0 times
Share this document with a friend
32
Hands-On Lab SharePoint 2010 & Azure: Event Handlers Lab version: 1.0 Last updated: 4/29/2022
Transcript
Page 1: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

Hands-On LabSharePoint 2010 & Azure: Event Handlers

Lab version: 1.0

Last updated: 5/22/2023

Page 2: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

CONTENTS

SECTION 1: CREATING A WORKER ROLE AND TEST WEB ROLE......................................................3Overview.................................................................................................................................................3

Exercise 1: Creating a Worker Role..........................................................................................................4

Task 1 – Creating The New Worker Role Project.................................................................................4

Task 2 – Defining Configuration Values...............................................................................................5

Task 3 – Coding The Worker Role........................................................................................................6

Exercise 2: Creating a Test Web Role.....................................................................................................11

Task 1 – Creating The New Web Role................................................................................................11

Task 2 – Initializing the Storage Connection......................................................................................12

Task 3 – Implementing The Test Web Role........................................................................................12

Task 4 – Building and Testing.............................................................................................................14

Summary...............................................................................................................................................15

SECTION 2: COMMUNICATING WITH THE WORKER ROLE FROM A SHAREPOINT EVENT HANDLER................................................................................................................................................. 15

Overview...............................................................................................................................................15

Exercise 1: Creating a WCF Web Role....................................................................................................17

Task 1 – Creating The New WCF Web Role........................................................................................17

Task 2 – Initializing the Storage Connection......................................................................................17

Task 3 – Implementing The WCF Web Role.......................................................................................18

Task 4 – Building and Testing.............................................................................................................19

Exercise 2: Publishing the Worker Role.................................................................................................19

Task 1 – Editing the Web.config File..................................................................................................19

Task 2 – Publishing The Worker Role To Azure..................................................................................20

Exercise 3: Create a SharePoint Event Handler......................................................................................23

Task 1 – Creating The SharePoint Project..........................................................................................24

Task 2 – Creating a Content Type......................................................................................................25

Task 3 – Creating a List Definition......................................................................................................26

Task 4 – Creating an Event Handler...................................................................................................26

Task 5 – Deploying and Testing the Event Handler............................................................................26

Summary...............................................................................................................................................27

Page 3: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

Section 1: Creating a Worker Role and Test Web Role

Overview

In this lab, you will build a Worker Role that returns flight status information. This Worker Role will accept jobs through a queue and return flight status information through e-mail. You will then create a Web Role to test the Worker Role.

Objectives

In this lab, you will:

Learn to create a Worker Role and deploy it to Azure.

Learn to communicate with the Worker Role through a Web Role and queue.

System Requirements

You must have the following items to complete this lab:

Windows Azure SDK and Windows Azure Tools for Microsoft Visual Studio

Access to a Windows Azure account

Access to a Windows Live account

Access to a Bing development account

Setup

This lab uses a Windows Live account to send flight status information via e-mail. If you do not have a Windows Live account, then proceed to https://signup.live.com.

This lab uses the Bing API to retrieve flight status information. In order to retrieve the flight information, you will need to have a developer application ID. If you do not have a developer application ID, proceed to http://www.bing.com/developers/createapp.aspx and sign up.

Page 4: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

The Windows Azure SDK (included in Windows Azure Tools for Visual Studio) installs a simulation environment on your development machine for testing Azure applications locally before deploying them to the cloud. The simulation environment consists of the development fabric to host web and worker roles, and the development storage which simulates cloud blob, table and queue storage locally.

Development storage uses SQL Server as its underlying storage mechanism, and by default the SDK will attempt to configure it to use SQL Server Express. If you do not have SQL Server Express installed before installing the SDK, or you wish to simply use an existing SQL Server instance to host the development storage database, you must run the dsinit command to select the SQL Server instance where the database will be created.

Please see instructions below for how to run dsinit.

Using dsinit to Configure Development Storage

1. Open a command prompt.

2. Edit the following command line as appropriate for your environment, where [AzureSDKInstallDrive] is the drive where you installed the Azure SDK (or Windows Azure Tools for Visual Studio), and [YourSqlInstance] is the SqlServer where you want to create the development storage database.

[AzureSDKInstallDrive]\ Program Files\Windows Azure SDK\v1.3\bin\devstore\dsinit.exe /sqlinstance:[YourSqlInstance]

Example Command Line:“C:\Program Files\Windows Azure SDK\v1.3\bin\devstore\dsinit.exe” /sqlinstance:.

3. Note that the sample command line above uses the value “.” for the sqlinstance argument, which specifies that the local default SQL instance will be used for development storage.

Exercises

This Hands-On Lab is comprised of the following exercises:

1. Creating a Worker Role

2. Creating a Web Role

Estimated Time to complete this lab: 45 minutes

Exercise 1: Creating a Worker Role

In this exercise, you will create a Worker Role that e-mails flight information.

Task 1 – Creating The New Worker Role Project

Page 5: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

In this task, you will create the new Worker Role project.

1. Start Visual Studio 2010.

2. From the main menu, select File>>New>>Project.

3. In the New Project dialog, select Cloud>>Windows Azure Project.

4. Name the new project FlightInfoWorkerProject.

5. Click OK.

6. In the New Windows Azure Project dialog, select Worker Role and click the right arrow.

7. Rename WorkerRole1 as FlightInfoWorkerRole.

8. Click OK.

Task 2 – Defining Configuration Values

In this task, you will define the configuration values for the Worker Role. The configuration values establish connections to the storage account where the work queue will be created.

1. Under the FlightInfoWorkerProject>>Roles folder, double-click FlightInfoWorkerRole.

2. Click the Settings tab.

3. Click Add Setting.

4. Name the setting DataConnectionString.

5. Set the Type to Connection String.

6. Click the ellipsis under Value.

7. In the Storage Account Connection String dialog, select Use the Windows Azure Storage Emulator and click OK.

8. Click Add Setting.

9. Name the setting SmtpServer.

10. Set the Type to String.

11. Set the Value to smtp.live.com.

12. Click Add Setting.

13. Name the setting LiveID.

14. Set the Type to String.

15. Set the Value to your LiveID.

16. Click Add Setting.

17. Name the setting LivePassword.

Page 6: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

18. Set the Type to String.

19. Set the Value to your Live password.

20. Click Add Setting.

21. Name the setting BingAppID.

22. Set the Type to String.

23. Set the Value to your Bing Application ID.

Figure 1Worker Role Settings

Task 3 – Coding The Worker Role

In this task, you will implement the Worker Role. Communication with the Worker Role will be through a queue.

1. In the FlightInfoWorkerRole project, right-click the References node and select Add Reference.

2. In the Add Reference dialog, click the .NET tab.

3. Select System.Web.

4. Click OK.

5. In the Solution Explorer, open WorkerRole.cs for editing.

6. Add the following statements to the top of the file.

C#

using System.Xml;using System.Xml.Linq;using System.Net.Mail;using System.Text;using System.IO;using System.Web.UI;

Page 7: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

7. Add the following member variables within the WorkerRole class.

C#

private CloudQueueClient qc;private CloudQueue q;

8. Replace the entire body of the OnStart method with the following code.

C#

// Set the maximum number of concurrent connections ServicePointManager.DefaultConnectionLimit = 12;

CloudStorageAccount.SetConfigurationSettingPublisher(( configName, configSetting) => { var connectionString = RoleEnvironment.GetConfigurationSettingValue(configName); configSetting(connectionString); });

return base.OnStart();

9. Add the following code to the class to create a function that returns flight information from Bing.

C#

private XDocument GetFlightDetails(string AppID, string Flight, string Market){ string uri = String.Format( "http://api.bing.net/xml.aspx?AppId={0}&Query={1}& Sources=InstantAnswer&Version=2.2&Market={2}", AppID, Flight, Market);

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); XDocument flightResponse = XDocument.Load(sr); return flightResponse;}

Page 8: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

10. .Add the following code to the class to create helper functions that make build an HTML e-mail message with flight information.

C#

private string CreateHtmlMessage( string Subject, string Link, string AirlineName, string Status, string ScheduledDeparture, string UpdatedDeparture, string ScheduledArrival, string UpdatedArrival, string Origin, string Destination){ //Create HTML e-mail body StringWriter sw = new StringWriter(); using (HtmlTextWriter writer = new HtmlTextWriter(sw)) { //div writer.RenderBeginTag(HtmlTextWriterTag.Div); //anchor writer.AddAttribute(HtmlTextWriterAttribute.Href, Link); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write(Subject); writer.RenderEndTag(); //table writer.RenderBeginTag(HtmlTextWriterTag.Table); //rows writer.Write(CreateTableRow("Airline Name", AirlineName)); writer.Write(CreateTableRow("Status",Status)); writer.Write(CreateTableRow("Scheduled Departure",ScheduledDeparture)); writer.Write(CreateTableRow("Updated Departure",UpdatedDeparture)); writer.Write(CreateTableRow("Scheduled Arrival",ScheduledArrival)); writer.Write(CreateTableRow("Updated Arrival",UpdatedArrival)); writer.Write(CreateTableRow("Origin", Origin)); writer.Write(CreateTableRow("Destination",Destination)); writer.RenderEndTag(); writer.RenderEndTag(); }

return sw.ToString();}

private string CreateTableRow(string FieldName, string FieldValue){ StringWriter sw = new StringWriter(); using (HtmlTextWriter writer = new HtmlTextWriter(sw)) { writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Td);

Page 9: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

writer.Write(FieldName); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(FieldValue); writer.RenderEndTag(); writer.RenderEndTag(); } return sw.ToString();}

11. .Add the following code to send the flight nformation as an e-mail.

C#

private void SendMail(string Server, string Subject, string Body, string LiveID, string Password, string ReturnAddress){ MailMessage mm = new MailMessage(LiveID, ReturnAddress); mm.IsBodyHtml = true; mm.Body = Body; mm.Subject = Subject; SmtpClient c = new SmtpClient(Server, 25); c.DeliveryMethod = SmtpDeliveryMethod.Network; c.EnableSsl = true; c.Credentials = new NetworkCredential(LiveID, Password); c.Send(mm);

}

12. Replace the entire body of the Run method with the following code.

C#

Trace.WriteLine("Worker entry point called", "Information");

//Reference QueueCloudStorageAccount sa =CloudStorageAccount.FromConfigurationSetting("DataConnectionString");qc = sa.CreateCloudQueueClient();q = qc.GetQueueReference("flightrequests");q.CreateIfNotExist();

//Get Credentialsstring server = RoleEnvironment.GetConfigurationSettingValue("SmtpServer");string liveId = RoleEnvironment.GetConfigurationSettingValue("LiveID");string password = RoleEnvironment.GetConfigurationSettingValue("LivePassword");

Page 10: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

string appID = RoleEnvironment.GetConfigurationSettingValue("BingAppID");

while (true){ Thread.Sleep(5000); Trace.WriteLine("Getting Message", "Information");

//Retrieve work request message CloudQueueMessage m = q.GetMessage(new TimeSpan(0, 5, 0)); XDocument doc = null; try { doc = XDocument.Parse(m.AsString); } catch { m = null; }

if (m != null) { //Get flight information var flightRequest = (from e in doc.Descendants("Message") select new { Flight = e.Element("Flight").Value, Market = e.Element("Market").Value, ReturnAddress = e.Element("Email").Value }).First();

XDocument flightResponse = GetFlightDetails(appID, flightRequest.Flight, flightRequest.Market);

XNamespace ia = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/instantanswer"; XNamespace fls = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element/flightstatus";

var flightLink = (from d in flightResponse.Descendants(ia + "InstantAnswerResult") select new { Subject = d.Element(ia + "Title").Value, Link = d.Element(ia + "ClickThroughUrl").Value }).First();

var flightStatus = (from d in flightResponse.Descendants(fls + "FlightStatus") select new {

Page 11: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

AirlineName = d.Element(fls + "AirlineName").Value, FlightName = d.Element(fls + "FlightName").Value, Status = d.Element(fls + "StatusString").Value, ScheduledDeparture = d.Element(fls + "ScheduledDeparture").Value, UpdatedDeparture = d.Element(fls + "UpdatedDeparture").Value, ScheduledArrival = d.Element(fls + "ScheduledArrival").Value, UpdatedArrival = d.Element(fls + "UpdatedArrival").Value, OriginName = d.Element(fls + "OriginAirport").Element(fls + "Name").Value, DestinationName = d.Element(fls + "DestinationAirport").Element(fls + "Name").Value, OriginCode = d.Element(fls + "OriginAirport").Element(fls + "Code").Value, DestinationCode = d.Element(fls + "DestinationAirport").Element(fls + "Code").Value }).First();

//Create HTML document with flight info string htmlBody = CreateHtmlMessage( flightLink.Subject, flightLink.Link, flightStatus.AirlineName, flightStatus.Status, flightStatus.ScheduledDeparture, flightStatus.UpdatedDeparture, flightStatus.ScheduledArrival, flightStatus.UpdatedArrival, String.Format("{0}({1})", flightStatus.OriginName, flightStatus.OriginCode), String.Format("{0}({1})", flightStatus.DestinationName, flightStatus.DestinationCode));

//Email document SendMail(server,flightLink.Subject, htmlBody,liveId,password, flightRequest.ReturnAddress);

//Delete work request message q.DeleteMessage(m); }}

Page 12: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

Exercise 2: Creating a Test Web Role

In this exercise, you will create a simple Web Role to test the Worker Role locally before deploying to Azure.

Task 1 – Creating The New Web Role

In this task, you will add the new Web Role to the existing application.

1. In the FlightInfoWorkerProject, right click the Roles folder and select Add>>New Web Role Project.

2. In the Add New Role Project dialog, name the new Web Role FlightInfoWebRole and click Add.

3. Under the FlightInfoWorkerProject>>Roles folder, double-click FlightInfoWebRole.

4. Click the Settings tab.

5. Click Add Setting.

6. Name the setting DataConnectionString.

7. Set the Type to Connection String.

8. Click the ellipsis under Value.

9. In the Storage Account Connection String dialog, select Use the Windows Azure Storage Emulator and click OK.

Task 2 – Initializing the Storage Connection

In this task, you initialize the storage connection to gain access to queue storage.

1. Open Global.asax.cs for editing.

2. Add the following references at the top of the file

C#

using Microsoft.WindowsAzure;using Microsoft.WindowsAzure.Diagnostics;using Microsoft.WindowsAzure.ServiceRuntime;using Microsoft.WindowsAzure.StorageClient;

3. Add the following code to the Application_Start method.

C#

CloudStorageAccount.SetConfigurationSettingPublisher( (configName, configSetting) => { var connectionString =

Page 13: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

RoleEnvironment.GetConfigurationSettingValue(configName); configSetting(connectionString); });

Task 3 – Implementing The Test Web Role

In this task, you will implement the test Web Role. The Web Role will drop a flight request into the queue for the Worker Role to process.

1. Open Default.aspx in Source view for editing for editing.

2. Replace the ASPX markup in the BodyContent placeholder with the following markup..

ASPX

<div> <asp:Table ID="LayoutTable" runat="server"> <asp:TableRow> <asp:TableCell>Flight Number</asp:TableCell><asp:TableCell> <asp:TextBox ID="Flight" runat="server" /></asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell>E-mail Address</asp:TableCell><asp:TableCell> <asp:TextBox ID="ReturnAddress" runat="server" /></asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell>Market</asp:TableCell><asp:TableCell> <asp:TextBox ID="Market" runat="server" Text="en-us"/> </asp:TableCell> </asp:TableRow> </asp:Table> <br /> <asp:LinkButton ID="FlightRequest" runat="server" OnClick="FlightRequest_Click">Request Flight Status </asp:LinkButton></div>

3. Open Default.aspx.cs for editing.

4. Add the following references at the top of the code file.

C#

using Microsoft.WindowsAzure;using Microsoft.WindowsAzure.Diagnostics;using Microsoft.WindowsAzure.ServiceRuntime;using Microsoft.WindowsAzure.StorageClient;using System.Xml.Linq;

Page 14: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

5. Add the following member variables to the class.

C#

private CloudQueueClient qc;private CloudQueue q;

6. Add the following code to the Page_Load method.

C#

CloudStorageAccount sa = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");qc = sa.CreateCloudQueueClient();q = qc.GetQueueReference("flightrequests");q.CreateIfNotExist();

7. Add the following code to the FlightRequest_Click event.

C#

XDocument data = new XDocument( new XElement("Message", new XElement("Flight", Flight.Text), new XElement("Market", Market.Text), new XElement("Email", ReturnAddress.Text)));CloudQueueMessage m = new CloudQueueMessage(data.ToString(SaveOptions.DisableFormatting));q.AddMessage(m);

Task 4 – Building and Testing

In this task, you will test the solution locally.

1. Right click the FlightInfoWorkerProject and select Build Solution.

2. Press F5 to start debugging.

3. When the Web Role appears, enter some flight information.

Figure 2Flight Status Request

Page 15: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

4. Verify that you receive an e-mail from the Worker Role

Figure 3Flight Status E-mail

Summary

Worker Roles are used in Azure for handling long-running or resource-intensive processes. Once deployed, you can communicate with Worker Roles either directly using endpoints (TCP, HTTP, HTTPS) or indirectly using queues. This lab communicated with a Worker Role using a queue.

Section 2: Communicating with the Worker Role from a SharePoint Event Handler.

Overview

SharePoint event handlers to detect changes in list, libraries, and sites. These event handlers can call out to Azure Worker roles to perform long-running or resource-intensive operations. In this lab you will build a WCF Web Role to act as a front-end to the Worker Role and then call the Web Role from an event handler.

Objectives

In this lab, you will:

Learn to create a WCF Web Role that acts as a front-end for a Worker Role.

Learn to integrate a Worker Role with SharePoint event handlers.

Page 16: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

System Requirements

You must have the following items to complete this lab:

Windows Azure SDK and Windows Azure Tools for Microsoft Visual Studio

Access to a Windows Azure account

Access to a Windows Live account

Access to a Bing development account

Setup

This lab uses a Windows Live account to send flight status information via e-mail. If you do not have a Windows Live account, then proceed to https://signup.live.com.

This lab uses the Bing API to retrieve flight status information. In order to retrieve the flight information, you will need to have a developer application ID. If you do not have a developer application ID, proceed to http://www.bing.com/developers/createapp.aspx and sign up.

The Windows Azure SDK (included in Windows Azure Tools for Visual Studio) installs a simulation environment on your development machine for testing Azure applications locally before deploying them to the cloud. The simulation environment consists of the development fabric to host web and worker roles, and the development storage which simulates cloud blob, table and queue storage locally.

Development storage uses SQL Server as its underlying storage mechanism, and by default the SDK will attempt to configure it to use SQL Server Express. If you do not have SQL Server Express installed before installing the SDK, or you wish to simply use an existing SQL Server instance to host the development storage database, you must run the dsinit command to select the SQL Server instance where the database will be created.

Please see instructions below for how to run dsinit.

Using dsinit to Configure Development Storage

1. Open a command prompt.

2. Edit the following command line as appropriate for your environment, where [AzureSDKInstallDrive] is the drive where you installed the Azure SDK (or Windows Azure Tools for Visual Studio), and [YourSqlInstance] is the SqlServer where you want to create the development storage database.

[AzureSDKInstallDrive]\ Program Files\Windows Azure SDK\v1.3\bin\devstore\dsinit.exe /sqlinstance:[YourSqlInstance]

Example Command Line:“C:\Program Files\Windows Azure SDK\v1.3\bin\devstore\dsinit.exe” /sqlinstance:.

Page 17: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

3. Note that the sample command line above uses the value “.” for the sqlinstance argument, which specifies that the local default SQL instance will be used for development storage.

Exercises

This Hands-On Lab is comprised of the following exercises:

1. Creating a WCF Web Role

2. Publishing the Worker Role

3. Calling the solution from an event handler

Estimated Time to complete this lab: 60 minutes

Exercise 1: Creating a WCF Web Role

In this exercise, you will create a WCF Web Role to act as a front-end to the Worker Role.

Task 1 – Creating The New WCF Web Role

In this task, you will add the new WCF Web Role to the existing application.

1. In the FlightInfoWorkerProject, right click the Roles folder and select Add>>New Web Role Project.

2. In the Add New Role Project dialog, select WCF Service Web Role.

3. Name the new WCF Web Role FlightInfoWcfRole and click Add.

4. Under the FlightInfoWorkerProject>>Roles folder, double-click FlightInfoWcfRole.

5. Click the Settings tab.

6. Click Add Setting.

7. Name the setting DataConnectionString.

8. Set the Type to Connection String.

9. Click the ellipsis under Value.

10. In the Storage Account Connection String dialog, select Use the Windows Azure Storage Emulator and click OK.

Task 2 – Initializing the Storage Connection

In this task, you initialize the storage connection to gain access to queue storage.

1. In the Solution Explorer, right click the FlightInfoWcfRole project and select Add>>New Item.

Page 18: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

2. In the Add New Item dialog, select Global Application Class and click Add.

3. Open Global.asax.cs for editing.

4. Add the following references at the top of the file

C#

using Microsoft.WindowsAzure;using Microsoft.WindowsAzure.Diagnostics;using Microsoft.WindowsAzure.ServiceRuntime;using Microsoft.WindowsAzure.StorageClient;

5. Add the following code to the Application_Start method.

C#

CloudStorageAccount.SetConfigurationSettingPublisher( (configName, configSetting) => { var connectionString = RoleEnvironment.GetConfigurationSettingValue(configName); configSetting(connectionString); });

Task 3 – Implementing The WCF Web Role

In this task, you will implement the WCF Web Role. The WCF Web Role will drop a flight request into the queue for the Worker Role to process.

1. Open IService1.cs for editing.

2. Replace code with the following to define the interface.

C#

[OperationContract]void RequestFlightInfo(string FlightNumber, string Market, string ReturnAddress);

3. Open Service1.cs for editing.

4. Delete the code contained within the class definition.

5. Add the following references at the top of the code file.

C#

using Microsoft.WindowsAzure;using Microsoft.WindowsAzure.Diagnostics;

Page 19: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

using Microsoft.WindowsAzure.ServiceRuntime;using Microsoft.WindowsAzure.StorageClient;using System.Xml.Linq;

6. Add the following code to the RequestFlightInfo method.

C#

CloudStorageAccount sa = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");CloudQueueClient qc = sa.CreateCloudQueueClient();CloudQueue q = qc.GetQueueReference("flightrequests");q.CreateIfNotExist();

XDocument data = new XDocument( new XElement("Message", new XElement("Flight", FlightNumber), new XElement("Market", Market), new XElement("Email", ReturnAddress)));CloudQueueMessage m = new CloudQueueMessage(data.ToString(SaveOptions.DisableFormatting));q.AddMessage(m);

Task 4 – Building and Testing

In this task, you will test the solution locally.

1. Right click the FlightInfoWorkerProject and select Build Solution.

2. Press F5 to start debugging.

3. Verify that you can see the service definition.

Figure 4Service Definition

Page 20: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

Exercise 2: Publishing the Worker Role

Task 1 – Editing the Web.config File

In this task, you will edit the web.config file to support deployment to Azure.

1. In the FlightInfoWcfRole project, open web.config for editing

2. Modify the file to appear as follows.

XML

<?xml version="1.0"?><configuration> <system.diagnostics> <trace> <listeners> <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics"> </add> </listeners> </trace> </system.diagnostics> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <services> <service name="FlightInfoWcfRole.Service1" behaviorConfiguration="FlightInfoWcfRole.Service1 Behavior"> <endpoint address="" binding="basicHttpBinding" contract="FlightInfoWcfRole.IService1"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="FlightInfoWcfRole.Service1 Behavior"> <serviceMetadata httpGetEnabled="true"/> <useRequestHeadersForMetadataAddress> <defaultPorts> <add scheme="http" port="81"/> <add scheme="https" port="444"/>

Page 21: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

</defaultPorts> </useRequestHeadersForMetadataAddress> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer></configuration>

Task 2 – Publishing The Worker Role To Azure

In this task, you will publish the Worker Role to your Azure account.

1. In Visual Studio, set the deployment configuration for the solution to Release.

2. In the FlightInfoWorkerProject>Roles folder, double-click the FlightInfoWorkerRole.

3. Click Settings.

4. Click the ellipsis in the Value field for the DataConnectionString setting.

5. In the Storage Account Connection String dialog, select Enter Storage Account Credentials.

6. Enter your Account Name and Account Key.

7. Select Use Default HTTP Endpoints and click OK.

8. Click the ellipsis in the Value field for the Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString setting.

9. In the Storage Account Connection String dialog, select Enter Storage Account Credentials.

10. Enter your Account Name and Account Key.

11. Select Use Default HTTPS Endpoints and click OK.

12. Perform the same updates to the settings for the FlightInfoWebRole and FlightInfoWcfRole projects.

13. In the Solution Explorer, right click the FlightInfoWorkerProject solution and select Clean Solution from the context menu.

14. In the Solution Explorer, right click the FlightInfoWorkerProject solution and select Build Solution from the context menu.

15. In the Solution Explorer, right click the FlightInfoWorkerProject and select Publish from the context menu.

16. In the Deploy Windows Azure Project dialog, click Create Service Package Only and click OK.

Page 22: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

Figure 5Create Service Package

17. Open Internet Explorer, and go to http://windows.azure.com. Login with your Azure credentials. If you do not have a Windows Azure Account, sign-up for a new one.

18. In the Azure Portal, click New Hosted Service.

Figure 6New Hosted Service

19. In the Create a New Hosted Service dialog type Flight Info Queue in the Enter a Name for Your Service field.

Page 23: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

20. In the Enter a URL Prefix for Your Service field, enter a unique prefix for the service and make note of it for later use.

21. In the Choose a Region or Affinity Group list, select a region for hosting the service.

22. In the Deployment Options, select Deploy to Stage Environment.

23. In the Deployment Name field, type Flight Info Queue.

24. In the Package Location field, click Browse Locally.

25. Browse to the FlightInfoWorkerProject.cspkg file and click Open.

26. In the Configuration File field, click Browse Locally.

27. Browse to the ServiceConfiguration.csfg file and click Open.

28. In the Create a New Hosted Service dialog, click OK.

29. When you receive a warning that the role has only one instance, click Yes to continue.

Figure 7Warning Dialog

30. Wait for Azure to complete the creation of the new Hosted Service, which will be indicated by a Ready status.

31. After the deployment is complete, select Flight Info Queue service in the Azure Portal and click the Swap VIP button.

Page 24: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

Figure 8Swap VIP

32. In the Swap VIPs dialog, click OK to move the Staging bits to Production.

33. After the bits are moved into Production, locate the DNS Name in the Properties pane. Make note of the address exposed for communicating with the WCF Web Role. You will use this endpoint information later when calling from SharePoint.

Exercise 3: Create a SharePoint Event Handler

In this exercise, you will create a custom SharePoint list that will act as a local work queue for flight requests. When a new request is added, an event handler will fire that will call the WCF Web Role with the request.

Task 1 – Creating The SharePoint Project

In this task, you will create new SharePoint project.

1. Start Visual Studio 2010.

2. From the main menu, select File>>New>>Project.

3. In the New Project dialog, select SharePoint>>2010>>Empty SharePoint Project.

4. Name the new project FlightInfoEventHandler.

5. Click OK.

6. In the SharePoint Customization Wizard dialog, specify a Site Collection where the solution will be deployed.

7. Select Deploy as Farm Solution and click Finish.

8. In the Solution Explorer, right click the Features node and select Add Feature from the context menu.

9. Change the Scope of the new feature to Site.

10. In the Solution Explorer, right click the References node and select Add Service Reference from the context menu.

Page 25: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

11. In the Add Service Reference dialog, enter the address of the WCF Web Role you deployed earlier, which is the DNS Name concatenated with Service1.svc and located on port 8080.

12. Type FlightInfoService in the Namespace field and click OK.

Figure 9Add Service Reference

Task 2 – Creating a Content Type

In this task, you will create a content type that will be the basis for a new list definition.

1. In the Solution Explorer, right-click the FlightInfoEventHandler project and select Add>>New Item from the context menu.

2. In the Add New Item dialog, select Content Type.

3. Name the new item FlightRequest and click Add.

4. On the Choose Content Type Settings screen, choose to base the new content type on the Item content type and click Finish.

5. In the Solution Explorer, open Elements.xml for editing.

6. Modify the file to appear as follows.

C#

<?xml version="1.0" encoding="utf-8"?><Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Field ID="{06611607-61BA-4933-80C7-71CFE3241B02}" Name="FlightNumber" DisplayName="Flight Number" Type="Text" Group="Azure Columns"/> <Field ID="{734ABB99-1FFB-4948-93FE-9CFBCE13D276}" Name="FlightMarket" DisplayName="Flight Market"

Page 26: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

Type="Text" Group="Azure Columns"/> <Field ID="{54E358F7-F27F-4298-AAD7-1612925EA584}" Name="ReturnAddress" DisplayName="Return Address" Type="Text" Group="Azure Columns"/> <!-- Parent ContentType: Item (0x01) --> <ContentType ID="0x01007484facc74ca4319b4deb5b5f9ef2352" Name="FlightInfoEventHandler - FlightRequest" Group="Custom Content Types" Description="My Content Type" Inherits="TRUE" Version="0"> <FieldRefs> <FieldRef ID="{06611607-61BA-4933-80C7-71CFE3241B02}" Name="FlightNumber" DisplayName="Flight Number"/> <FieldRef ID="{734ABB99-1FFB-4948-93FE-9CFBCE13D276}" Name="FlightMarket" DisplayName="Flight Market"/> <FieldRef ID="{54E358F7-F27F-4298-AAD7-1612925EA584}" Name="ReturnAddress" DisplayName="Return Address"/> </FieldRefs> </ContentType></Elements>

Task 3 – Creating a List Definition

In this task, you will create a list definition based on the content type you created earlier.

1. In the Solution Explorer, right-click the FlightInfoEventHandler project and select Add>>New Item from the context menu.

2. .In the Add New Item dialog, select List Definition from a Content Type.

3. Name the list definition FlightsRequestsListDef and click Add.

4. In the Choose List Definition Settings dialog, change the Display Name to Flight Requests and click Finish.

Task 4 – Creating an Event Handler

In this task, you will create an event handler for the list.

1. In the Solution Explorer, right-click the FlightInfoEventHandler project and select Add>>New Item from the context menu.

2. In the Add New Item dialog, select Event Receiver and click Add.

3. In the Choose Event Receiver Settings dialog, check An Item was added and click Finish.

4. Open EventReceiver1.cs for editing.

5. Place the following code in the ItemAdded method.

Page 27: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

C#

string flightNumber = properties.ListItem["FlightNumber"].ToString();string flightMarket = properties.ListItem["FlightMarket"].ToString();string returnAddress = properties.ListItem["ReturnAddress"].ToString();

FlightInfoService.Service1Client client = new FlightInfoService.Service1Client();client.RequestFlightInfo(flightNumber, flightMarket, returnAddress);

properties.ListItem["Title"] += " (Sent)";properties.ListItem.Update();

Task 5 – Deploying and Testing the Event Handler

In this task, you will deploy the SharePoint feature and test the communication with the WCF Web Role.

1. Open the web.config file associated with the Site Collection where the feature will be deployed in Visual Studio for editing.

2. Open the app.config associate with the FlightInfoEventHandler project and copy the contents of the <system.serviceModel> element into the <system.serviceModel> element in the SharePoint web.config file.

3. Save the SharePoint web.config file.

4. In the Solution Explorer, right-click the FlightInfoEventHandler project and select Build from the context menu.

5. In the Solution Explorer, right-click the FlightInfoEventHandler project and select Deploy from the context menu.

6. In the Internet Explorer, navigate to the Site Collection where the solution was deployed.

7. Click on the list entitled FlightInfoEventHandler - ListInstance1.

8. Click Add New Item and fill in a flight data request.

Page 28: SharePoint 2010 and Azure: Event Handlersaz12722.vo.msecnd.net/spazuretrainingcourse1-0/labs/… · Web viewSharePoint 2010 and Azure: Event Handlers Description In this lab you will

Figure 10A Flight Status request from SharePoint

9. Click Save.

10. Verify that you received an e-mail with flight status information.

Summary

Event handlers are useful artifacts for receiving notification when things occur inside SharePoint. These event handlers can call out to other processes such as WCF Web Roles to perform functions. In this lab, you created a fully-featured solution using SharePoint event handlers and Azure Roles.


Recommended