32
Hands-On Lab Office 2010 Service Applications Lab version: 1.0.0 Last updated: 7/5/2022

Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

  • Upload
    lyanh

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Hands-On LabOffice 2010 Service Applications

Lab version: 1.0.0

Last updated: 5/5/2023

Page 2: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

CONTENTS

OVERVIEW................................................................................................................................................. 3

EXERCISE 1: CREATE REPORTS USING EXCEL SERVICES................................................................4Task 1 – Create the Report Generation web part................................................................................4

Task 2 – Use Excel Services REST interface to retrieve the data........................................................10

Task 3 – Configure the report site web parts.....................................................................................12

Exercise 1 Verification.......................................................................................................................14

EXERCISE 2: GENERATING DOCUMENTS USING WORD SERVICES................................................16Task 1 – Create the Printable Document Library event receiver.......................................................16

Task 2 – Build the PrintingStatus web part........................................................................................21

Task 3 – Place the Printing Status web part on the page...................................................................25

Exercise 2 Verification.......................................................................................................................25

SUMMARY................................................................................................................................................ 28

Page 3: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Overview

In this lab exercise, use the Office 2010 services applications to build a report generation application. This application uses Excel Services to access an Excel workbook via REST services and generate a Word document based on the data. Word Services converts the Word document into a PDF and XPS file and stores it in a report repository. Finally, Visio Services presents a graphical representation of the process to the user showing which reports have been generated.

Objectives

In this lab you will:

Use Word Services to generate PDF and XPS files based on a Word document

Use Excel Service’s REST interface to access information in an Excel workbook

System Requirements

This lab assumes that you have SharePoint Server installed in a test environment. For guidance on how to setup SharePoint Server see http://msdn.microsoft.com/en-us/library/ee554869(office.14).aspx. Note that any URL referred to in this lab must be adjusted for use with your local setup. You must have the following items to complete this lab:

Microsoft® Windows® Vista SP1 or Microsoft® Windows Server 2008 (64-bit)

Microsoft® SharePoint Server 2010 (64-bit)

Microsoft® Office Professional Plus 2010 (32-bit or 64-bit)

Microsoft® Visual Studio 2010

Setup

You must perform the following steps to prepare your computer for this lab. This consists primarily of creating a SharePoint site collection at http://intranet.contoso.com/sites/OfficeServiceApplications and installing the code snippets for this lab.

1. Run the command file Setup.bat located at %Office2010DeveloperTrainingKitPath%\Labs\OfficeServiceApplications\Source\.

Page 4: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Exercises

This Hands-On Lab is comprised of two exercises:

1. Create reports using Excel Services

2. Generating documents using Word Services

Estimated time to complete this lab: 60 minutes.

Starting Materials

This Hands-On Lab includes the following starting materials.

Visual Studio solutions. The lab provides the following Visual Studio solutions that you can use as starting point for the exercises. Lab instructions will reference the Training Kit location after installation as %Office2010DeveloperTrainingKitPath%.

◦ %Office2010DeveloperTrainingKitPath%\Labs\OfficeServiceApplications\Source\[language]\Starter\StateReportApplication\StateReportApplication.sln: Uses Word Services and Excel Services to generate XPS and PDF documents based on data stored in an Excel workbook.

Note: Inside the lab’s Source folder, you will find a Solution folder containing an end solution with the completed lab exercise.

Exercise 1: Create Reports using Excel Services

In this exercise you will access an Excel Workbook using the Excel Services REST interface. The results of these REST requests will be integrated into a Word template document using the Open XML SDK and archived in a document repository.

Task 1 – Create the Report Generation web part

In this task, you will create the web part that initiates report generation. You will define the web part’s UI and put the code in place to start the process of building the report.

1. Open the starter StateReportApplication project in Visual Studio 2010

Page 5: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

a. Open the StateReportApplicaiton.sln file in the %Office2010DeveloperTrainingKitPath%\Labs\OfficeServiceApplications\Source\[language]\Starter\StarteReportApplication folder

2. Add a new Visual Web Part to the project

a. Right click StateReportApplication in the Solution Explorer and click Add -> New Item

b. In the Add New Item dialog, select the Visual C#\Visual Basic -> SharePoint -> 2010 template category

c. Select the Visual Web Part template

d. Set the Name to GenerateReport and click Add

Figure 1(a)

Page 6: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Figure 1(b)Add New Visual Web Part

3. Design the user interface for the web part

a. Open the designer by right clicking GenerateReportUserControl.ascx in the Solution Explorer and clicking View Designer

b. Switch to the Source view using the button at the bottom of the window

c. At the bottom of the ascx file, add the following markup

ASPX

<table> <tr> <td>Generate Report for&nbsp;</td> <td><asp:DropDownList ID="States" runat="server" /></td> </tr> <tr><td colspan="2"></td></tr> <tr> <td colspan="2" align="right"> <asp:Button ID="GenerateReport" Text="Generate Report" runat="server" /> </td> </tr></table>

Page 7: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

d. Switch to the Design view using the button at the bottom of the window and verify it looks like the image below

Figure 2Completed Web Part Design

4. Load the web part with a list of all states

a. Switch to the code for the web part by right clicking the designer window and clicking View Code

b. Add the following using statements

C#

using System.Collections.Generic;using System.IO;using System.Linq;using Microsoft.Office.Word.Server.Conversions;using Microsoft.SharePoint;

Visual Basic

Imports System.Collections.GenericImports System.IOImports System.LinqImports Microsoft.Office.Word.Server.ConversionsImports Microsoft.SharePoint

c. Add code to the Page_Load method to make sure the drop down list is only initialized when the page is first loaded

C#

if (!IsPostBack || States.Items.Count == 0){ }

Visual Basic

If (Not IsPostBack) OrElse States.Items.Count = 0 ThenEnd If

Page 8: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

d. Create a list of states that exclude the ones that already have reports and add them to the drop down list

C#

if (!IsPostBack || States.Items.Count == 0){ States.Items.AddRange( Constants.States.Select(n => new ListItem(n)).ToArray());}

Visual Basic

If (Not IsPostBack) OrElse States.Items.Count = 0 ThenStates.Items.AddRange(Constants.States.Select(Function(n) New ListItem(n)).ToArray())

End If

5. Add code to the button click event handler to create a new folder for the state and generate the report in the new folder

a. Open the designer for the visual web part by right clicking GenerateReportUserControl.ascx in the Solution Explorer and selecting View Designer

b. Generate the click event handler by double clicking the button in the designer

c. In the new GenerateReport_Click event handler, add the following code to lookup the State Reports document library

C#

SPWeb web = SPContext.Current.Web; SPDocumentLibrary stateReports = SPContext.Current.Web.Lists["State Reports"] as SPDocumentLibrary;

Visual Basic

Dim web As SPWeb = SPContext.Current.WebDim stateReports As SPDocumentLibrary = TryCast(SPContext.Current.Web.Lists("State Reports"), SPDocumentLibrary)

d. Using the States control’s SelectedValue, lookup the folder in the States Report document library

C#

string state = States.SelectedValue; SPListItem listItem = stateReports.Folders.Cast<SPListItem>().

Page 9: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

FirstOrDefault(n => (n["Name"] as string) == state);

Visual Basic

Dim state As String = States.SelectedValueDim listItem As SPListItem = stateReports.Folders.Cast(Of SPListItem)().FirstOrDefault(Function(n) (TryCast(n("Name"), String)) = state)

e. If no folder for the selected state was found, add the new folder named after the selected state

C#

if (listItem == null){ listItem = stateReports.AddItem(string.Empty, SPFileSystemObjectType.Folder); listItem["ContentTypeId"] = SPContext.Current.Web.ContentTypes["Folder"].Id; listItem["Name"] = state; listItem.Update();}

Visual Basic

If listItem Is Nothing ThenlistItem = stateReports.AddItem(String.Empty,

SPFileSystemObjectType.Folder)listItem("ContentTypeId") =

SPContext.Current.Web.ContentTypes("Folder").IdlistItem("Name") = statelistItem.Update()

End If

f. Using the StateReport class, generate a new report and save it in the new folder

C#

using (MemoryStream stream = new MemoryStream()){ StateReport report = new StateReport(web, "Data/StateRankings.xlsx", state); report.GenerateReport(stream); listItem.Folder.Files.Add("Report.docx", stream.ToArray(), true); }

Visual Basic

Using stream As New MemoryStream()

Page 10: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Dim report As New StateReport(web, "Data/StateRankings.xlsx", state)

report.GenerateReport(stream)listItem.Folder.Files.Add("Report.docx", stream.ToArray(),

True)End Using

Task 2 – Use Excel Services REST interface to retrieve the data

In this task, you will add the Excel Services REST requests to the web part to provide the appropriate data to the report generation code.

1. Setup the WebClient object used to make web request to Excel Services

a. Open the StateReport.cs(StateReport.vb in case of VB) class by double clicking it in the Solution Explorer

b. In the GenerateReport method, create a new WebClient object and set it to use the default user credentials

C#

WebClient client = new WebClient();client.UseDefaultCredentials = true;

Visual Basic

Dim client As New WebClient()client.UseDefaultCredentials = True

2. Load the StateReportCard template docx file into a new WordprocessingDocument

a. Write the template docx file to the stream

C#

stream.Write(Properties.Resources.StateReportCard, 0, Properties.Resources.StateReportCard.Length);

Visual Basic

stream.Write(My.Resources.StateReportCard, 0, My.Resources.StateReportCard.Length)

b. Create a new writable WordprocessingDocument object using the stream

C#

using (WordprocessingDocument document = WordprocessingDocument.Open(stream, true)){}

Page 11: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Visual Basic

Using document As WordprocessingDocument = WordprocessingDocument.Open(stream, True)End Using

3. Perform the REST requests for the graphical report

a. Inside the using statement wrapping the WordprocessingDocument, generate the REST url to request the Report chart from the Excel Workbook

C#

string reportRestUrl = string.Format("{0}/model/Charts('Report')?Ranges('State')={1}", m_baseUrl, m_state);

Visual Basic

Dim reportRestUrl As String = String.Format("{0}/model/Charts('Report')?Ranges('State')={1}", m_baseUrl, m_state)

Note: The Ranges(‘State’) parameter in the url sets a cell in the workbook to a specific state causing the report’s content to be updated

b. Using the rest url, open the URL as a stream and write it to the first image part in the WordprocessingDocument

C#

using (Stream imageStream = client.OpenRead(reportRestUrl)) document.MainDocumentPart.ImageParts.First().FeedData(imageStream);

Visual Basic

Using imageStream As Stream = client.OpenRead(reportRestUrl)

document.MainDocumentPart.ImageParts.First().FeedData(imageStream)End Using

4. Perform the REST request for the atom feed representing the report’s title

a. Immediately following the image write, generate the REST url to retrieve the title atom feed

C#

Page 12: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

string titleRestUrl = string.Format("{0}/model/Ranges('Title')" + "?Ranges('State')={1}&$format=atom", m_baseUrl, m_state);

Visual Basic

Dim titleRestUrl As String = String.Format("{0}/model/Ranges('Title')" & "?Ranges('State')={1}&$format=atom", m_baseUrl, m_state)

b. Use the rest url to retrieve the atom xml data for the range and write it to the custom XML part in the document

C#

using (Stream titleStream = client.OpenRead(titleRestUrl)) WriteCustomXmlPart(document.MainDocumentPart, "{3D15FA4A-EB75-46F1-93D1-8DA4AAFE30A5}", titleStream);

Visual Basic

Using titleStream As Stream = client.OpenRead(titleRestUrl)WriteCustomXmlPart(document.MainDocumentPart, "{3D15FA4A-

EB75-46F1-93D1-8DA4AAFE30A5}", titleStream)End Using

Note: The WriteCustomXmlPart method is a helper method that finds a custom xml part based on its ID and then writs the stream into the part

5. Perform the REST request for the atom feed representing the report card data

a. Immediately after the title custom xml part write, write the report card custom xml

C#

string reportCardRestUrl = string.Format("{0}/model/Ranges('ReportCard')" + "?Ranges('State')={1}&$format=atom", m_baseUrl, m_state);using (Stream reportCardStream = client.OpenRead(reportCardRestUrl)) WriteCustomXmlPart(document.MainDocumentPart, "{5182EF05-94F6-41B6-B0F4-6BE836E29F5F}", reportCardStream);

Visual Basic

Dim reportCardRestUrl As String = String.Format("{0}/model/Ranges('ReportCard')" & "?Ranges('State')={1}&$format=atom", m_baseUrl, m_state)

Page 13: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Using reportCardStream As Stream = client.OpenRead(reportCardRestUrl)

WriteCustomXmlPart(document.MainDocumentPart, "{5182EF05-94F6-41B6-B0F4-6BE836E29F5F}", reportCardStream)End Using

Task 3 – Configure the report site web parts

In this task, you will place the new web part on the site’s main page and configure the site for use.

1. Build and deploy the State Report application to SharePoint

a. Right click StateReportApplication in the Solution Explorer and click Deploy

2. Enable the Office Service Application features on the site

a. In Internet Explorer navigate to http://intranet.contoso.com/sites/OfficeServiceApplications

b. Click Site Actions -> Site Settings

c. On the Site Settings page, click the Site collection features link

d. Activate the SharePoint Server Enterprise Site Collection features feature

Figure 3Activated Site Collection Feature

e. Navigate back to the Site Settings page using Site Actions -> Site Settings

f. Click the Manage Site Features link

Figure 4Activated Site Feature

g. Activate the SharePoint Server Enterprise Site features feature

3. Add the GenerateReport Web Part to the main page

a. In Internet Explorer navigate to http://intranet.contoso.com/sites/OfficeServiceApplications

b. Click Edit Page on the Page ribbon tab

c. Click Add a Web Part in the left web part zone

Page 14: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

d. In the Web Part pane, choose the Lists and Libraries category and the State Reports web part

e. Click Add to add the web part to the page

Figure 5Add State Reports List Web Part

f. Click Add a Web Part in the right web part zone

g. In the Web Part pane, choose the Custom category and the GenerateReport web part

Figure 6Add Generate Report Web Part

h. Click Add to add the web part to the page

i. Stop editing by clicking the Stop Editing button on the Page ribbon tab

Page 15: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Figure 7Completed Web Part Page

Exercise 1 Verification

In order to verify that you have correctly performed all steps of exercise 1, proceed as follows:

Test the Web Part

Test the GenerateReport web part by generating reports for several states.

1. In Internet Explorer navigate to http://intranet.contoso.com/sites/OfficeServiceApplications

2. Choose AL in the drop down list inside the GenerateReport web part and click Generate Report

3. Verify that AL shows up in the State Reports list

Figure 8Alabama State Report

4. Verify the report is correctly generated in the AL folder inside the State Reports document library

a. Click the AL link in the State Reports web part

b. Click the drop down arrow to the right of Report and select Edit in Microsoft Word

Page 16: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Figure 9Edit Report in Word 2010

c. Verify the document contains information for Alabama

Figure 10Generated Report viewed in Word 2010

Exercise 2: Generating Documents using Word Services

Page 17: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

In this exercise you will be adding an Event Receiver to the State Reports document library that will convert all docx files submitted into XPS and PDF files. This is done using Word Services and a scheduled job that converts all registered documents every 15 minutes. To provide feedback to the user you will also be implementing a simple web part that will provide a summary of the jobs submitted to Word Services.

Task 1 – Create the Printable Document Library event receiver

In this task, you will define a List Item Event Receiver that will fire anytime an item a new file is added or updated in the document library. This Event Receiver will start a print job that will convert the added or updated docx file into an XPS and PDF document.

1. Create a new event receiver item in the PrintableDocumentLibrary item

a. Right click PrintableDocumentLibrary in the Solution Explorer and select Add -> New Item

b. In the Add New Item dialog, select the Visual C#\Visual Basic -> SharePoint -> 2010 template category

c. Select the Event Receiver template

d. Set the Name to PrintableDocumentReceiver and click Add

e. In the dialog check the checkboxes by

i. An item was added

ii. An item was updated

Figure 11Create new Event Receiver

Page 18: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

f. Click Finish to create the Event Receiver

2. Create a StartJob method that accepts the files to convert and the format and starts a conversion job

a. Add the following using statement to the file

C#

using Microsoft.Office.Word.Server.Conversions;

Visual Basic

Imports Microsoft.Office.Word.Server.Conversions

b. In the PrintableDocumentReceiver class, add the following StartJob method

C#

private void StartJob(SPWeb web, SaveFormat format, string sourceUrl, string targetUrl){}

Visual Basic

Private Sub StartJob(ByVal web As SPWeb, ByVal format As SaveFormat, ByVal sourceUrl As String, ByVal targetUrl As String)End Sub

c. In the new method, create a ConversionJobSettings object to control how the documents are converted

C#

ConversionJobSettings settings = new ConversionJobSettings(){ OutputFormat = format, UpdateFields = true, OutputSaveBehavior = SaveBehavior.AlwaysOverwrite };

Visual Basic

Dim settings As New ConversionJobSettings() With {.OutputFormat = format, .UpdateFields = True, .OutputSaveBehavior = SaveBehavior.AlwaysOverwrite}

d. Create a new ConversionJob using the settings and your current user token

C#

Page 19: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

ConversionJob conversionJob = new ConversionJob(Constants.WordServicesAppName, settings){ SubscriptionId = Constants.SubscriptionId, UserToken = web.CurrentUser.UserToken};

Visual Basic

Dim conversionJob As New ConversionJob(Constants.WordServicesAppName, settings) With {.SubscriptionId = Constants.SubscriptionId, .UserToken = web.CurrentUser.UserToken}

Note: The SubscriptionId is a shared Guid that allows the application to find its active jobs.

e. Add the source and target file urls to the job and then start it

C#

conversionJob.AddFile(sourceUrl, targetUrl);conversionJob.Start();

Visual Basic

conversionJob.AddFile(sourceUrl, targetUrl)conversionJob.Start()

Note: It is possible to add multiple source/target pairs and even choose to convert entire folders or lists. In this case, you are starting one job for each type of conversion.

3. Implement a PrintDocument method that uses StartJob to convert all docx files to XPS and PDF

a. Add a new PrintDocument method to the PrintableDocumentReceiver class

C#

private void PrintDocument(SPWeb web, string listItemUrl){}

Visual Basic

Private Sub PrintDocument(ByVal web As SPWeb, ByVal listItemUrl As String)End Sub

b. Wrap all the code in the method with an if statement that checks if the listItemUrl ends with a .docx extension

Page 20: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

C#

private void PrintDocument(SPWeb web, string listItemUrl){ if (listItemUrl.EndsWith(".docx")) { }}

Visual Basic

Private Sub PrintDocument(ByVal web As SPWeb, ByVal listItemUrl As String)

If listItemUrl.EndsWith(".docx") ThenEnd If

End Sub

c. Calculate the sourceUrl using the web’s url and the list item’s url

C#

string sourceUrl = web.Url + "/" + listItemUrl;

Visual Basic

Dim sourceUrl As String = web.Url & "/" & listItemUrl

d. Calculate the target url by removing the .docx

C#

string targetUrl = sourceUrl.Substring(0, sourceUrl.Length - 5);

Visual Basic

Dim targetUrl As String = sourceUrl.Substring(0, sourceUrl.Length - 5)

e. Start a job for XPS and PDF conversion using the StartJob method

C#

StartJob(web, SaveFormat.XPS, sourceUrl, targetUrl + ".xps");StartJob(web, SaveFormat.PDF, sourceUrl, targetUrl + ".pdf");

Visual Basic

StartJob(web, SaveFormat.XPS, sourceUrl, targetUrl & ".xps")StartJob(web, SaveFormat.PDF, sourceUrl, targetUrl & ".pdf")

4. Implement the ItemAdded and ItemUpdated methods by having them call the PrintDocument method

Page 21: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

C#

/// <summary>/// An item was added./// </summary>public override void ItemAdded(SPItemEventProperties properties){ PrintDocument(properties.Web, properties.ListItem.Url); base.ItemAdded(properties);}

/// <summary>/// An item was updated./// </summary>public override void ItemUpdated(SPItemEventProperties properties){ PrintDocument(properties.Web, properties.ListItem.Url); base.ItemUpdated(properties);}

Visual Basic

''' <summary>''' An item was added.''' </summary>Public Overrides Sub ItemAdded(ByVal properties As SPItemEventProperties)

PrintDocument(properties.Web, properties.ListItem.Url)MyBase.ItemAdded(properties)

End Sub

''' <summary>''' An item was updated.''' </summary>Public Overrides Sub ItemUpdated(ByVal properties As SPItemEventProperties)

PrintDocument(properties.Web, properties.ListItem.Url)MyBase.ItemUpdated(properties)

End Sub

Task 2 – Build the PrintingStatus web part

In this task you will create a web part that will monitor the printing jobs started in a Printable Document Library. This web part will show the total number of jobs in action and the number of jobs in each state.

1. Add a new Visual Web Part to the project

a. Right click StateReportApplication in the Solution Explorer and click Add -> New Item

Page 22: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

b. In the Add New Item dialog, select the Visual C#\Visual Basic -> SharePoint -> 2010 template category

c. Select the Visual Web Part template

d. Set the Name to PrintingStatus and click Add

2. Design the user interface for the web part

a. Open the designer by right clicking PrintingStatusUserControl.ascx in the Solution Explorer and clicking View Designer

b. Click the Source button at the bottom of the designer

c. At the bottom of the ascx file, add the following markup to define status indicators for the total number of printing jobs, total jobs in progress, and total jobs not started.

ASPX

<table> <tr> <td>Active Printing Jobs</td> <td><asp:Label ID="ActiveJobs" runat="server" /></td> </tr> <tr> <td style="padding-left:20px">Jobs In Progress</td> <td><asp:Label ID="InProgressJobs" runat="server" /></td> </tr> <tr> <td style="padding-left:20px">Jobs Not Started</td> <td><asp:Label ID="NotStartedJobs" runat="server" /></td> </tr>

d. Add the following markup to the end of the file to provide a spacer row and an display of the next scheduled Word Services execution

ASPX

<tr><td></td><td></td></tr> <tr> <td colspan="2" align="center">Next execution: <asp:Label ID="NextRunTime" runat="server" /></td> </tr></table>

e. Switch to the Design view using the button at the bottom of the window and verify it looks like the image below

Page 23: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Figure 12Completed Print Status Design

3. Implement the web part’s Page_Load method to display information about active jobs

a. View the web parts code by right clicking the designer and selecting View Code

b. Add the following using statements to the file

C#

using System.Collections.ObjectModel;using System.Linq;using Microsoft.Office.Word.Server.Conversions;using Microsoft.Office.Word.Server.Service;using Microsoft.SharePoint.Administration;

Visual Basic

Imports System.Collections.ObjectModelImports System.LinqImports Microsoft.Office.Word.Server.ConversionsImports Microsoft.Office.Word.Server.ServiceImports Microsoft.SharePoint.Administration

c. In the Page_Load method add the following code to retrieve all active jobs and update the UI

C#

ReadOnlyCollection<ConversionJobInfo> activeJobs = ConversionJobStatus.GetAllActiveJobs( Constants.WordServicesAppName, Constants.SubscriptionId);ActiveJobs.Text = activeJobs.Count.ToString();

Visual Basic

Dim activeJobs As ReadOnlyCollection(Of ConversionJobInfo) = ConversionJobStatus.GetAllActiveJobs(Constants.WordServicesAppName, Constants.SubscriptionId)ActiveJobs.Text = activeJobs.Count.ToString()

Note: The SubscriptionId is used to only return jobs started by the event receiver created in the previous task

Page 24: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

d. Traverse through the list of active jobs and find how many documents are in the InProgress or NotStarted state

C#

int inProgressJobs = 0;int notStartedJobs = 0;foreach (ConversionJobInfo info in activeJobs){ ConversionJobStatus status = new ConversionJobStatus(Constants.WordServicesAppName, info.JobId, null); inProgressJobs += status.InProgress; notStartedJobs += status.NotStarted; }

Visual Basic

Dim inProgressJobs As Integer = 0Dim notStartedJobs As Integer = 0For Each info As ConversionJobInfo In activeJobs

Dim status As New ConversionJobStatus(Constants.WordServicesAppName, info.JobId, Nothing)

inProgressJobs += status.InProgressnotStartedJobs += status.NotStarted

Next info

Note: The GetAllActiveJobs method gets us information about each active job. You will need to create ConvertsionJobStatus objects to find all the details about the jobs.

e. Using the total conversions in progress and not started, update the UI

C#

InProgressJobs.Text = inProgressJobs.ToString();NotStartedJobs.Text = notStartedJobs.ToString();

Visual Basic

InProgressJobs.Text = inProgressJobs.ToString()NotStartedJobs.Text = notStartedJobs.ToString()

4. Use the WordService object to retrieve the next schedule run time of the conversion jobs

a. Add the following code to the end of the Page_Load method to access the WordService object

Page 25: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

C#

WordService service = SPFarm.Local.Services.GetValue<WordService>();

Visual Basic

Dim service As WordService = SPFarm.Local.Services.GetValue(Of WordService)()

b. Using the JobDefinitions list, retrieve the first schedule job in the collection

C#

SPJobDefinition job = service.JobDefinitions.First();

Visual Basic

Dim job As SPJobDefinition = service.JobDefinitions.First()

c. Using the job’s Schedule property, calculate the next occurrence and display it to the screen

C#

NextRunTime.Text = job.Schedule.NextOccurrence(DateTime.Now). ToShortTimeString();

Visual Basic

NextRunTime.Text = job.Schedule.NextOccurrence(Date.Now).ToShortTimeString()

Task 3 – Place the Printing Status web part on the page

In this task, you will update the main site page by adding a Printing Status web part to the page.

1. Build and deploy the State Report application to SharePoint

a. Right click StateReportApplication in the Solution Explorer and click Deploy

2. Add a Printing Status web part to the main page of the site

a. In Internet Explorer navigate to http://intranet.contoso.com/sites/OfficeServiceApplications

b. Click Edit Page on the Page ribbon tab

c. Click Add a Web Part in the right web part zone

d. In the Web Part pane, choose the Custom category and the PrintingStatus web part

e. Click Add to add the web part to the page

Page 26: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

f. Once the web part is added, drag it below the existing Generate Report web part and click Stop Editing

Figure 13Completed Printing Status Web Part

Exercise 2 Verification

In order to verify that you have correctly performed all steps of exercise 2, proceed as follows:

Test the Event Handler and Web Part

Test your event handler and web part by generating a new state report and verifying an XPS and PDF file are generated as well by Word Services.

1. In Internet Explorer navigate to http://intranet.contoso.com/sites/OfficeServiceApplications

2. Choose AL in the drop down list inside the GenerateReport web part and click Generate Report

3. Verify that AL shows up in the State Reports list and verify that a printing job shows up in the PrintStatus web part.

Figure 14Printing jobs in progress

4. Since the job is scheduled in the future, use Central Admin to force it to run now

a. In another Internet Explorer tab, navigate to http://demo2010a:2010/default.aspx

b. In the Monitoring section, click the Check job status link

Page 27: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Figure 15Check job status link

c. In the View drop down, choose Job Definition

d. In the Job Definition drop down choose Change Job Definition

Figure 16Filter by Job Definition

e. Page to the right until you find Word Automation Services Timer Job and click it

f. Click the job in the Scheduled section at the top of the page

g. On the Edit Timer Job page, click Run Now to force the conversion jobs to execute

Page 28: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Figure 17Run the job now

5. Verify an XPS and PDF version of the report are in the AL folder

a. Back in the site tab of Internet Explorer, click the link to the AL folder in the State Reports web part

b. Verify there are three documents in the folder, a docx, an XPS, and a PDF

Figure 18Printed Report Files

c. Click the link on the XPS file to view it

Page 29: Office 2010 Service Applications Lab - …az12722.vo.msecnd.net/.../labs/serviceapplicationslab3 …  · Web viewNow with both C# and VB code samples! In this lab, you will use the

Figure 19Printed Report as XPS

Summary

In this exercise you learned how to use the Office Service Applications to enhance your SharePOint applications and provide services specific to the types of documents in your application. Excel services provides access to Excel Workbooks using a programmatic REST interface. Word Services renders Word documents on the server allowing complete server side generation of documents.