openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · web viewin this...

17
Module 05: Data Binding with Content Controls Lab 5 Lab 05: WordprocessingML Content Controls Data Binding using Content Controls In the last two labs you’ve been focused on building a document from the ground up. While that gives you complete control of the document’s content, it isn’t very flexible when it comes to changing the document. Any changes to the content, whether it’s a simple font change or a more complicated rebuild of the document require the developer to be involved with every step of the change. Wouldn’t it be more convenient if the document’s manager could make all the changes he wanted in another application and then provide that document to your generation tool to be processed? WordprocessingML supports a page element called a structured document tag that allows you to add named custom controls directly to a page. As a developer you can write code that will look through the /word/document.xml package part to find these tags and then directly modify their content. Structured document tags have another feature as well that once configured eliminates the need to modify the /word/document.xml file. This feature, known as data binding, allows structured document tags to contain an XPath query that will locate the data for the tag. Office Open XML 1

Upload: lykiet

Post on 03-Mar-2018

213 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Module 05: Data Binding with Content Controls Lab 5

Lab 05: WordprocessingML Content ControlsData Binding using Content Controls

In the last two labs you’ve been focused on building a document from the ground up. While that gives you complete control of the document’s content, it isn’t very flexible when it comes to changing the document. Any changes to the content, whether it’s a simple font change or a more complicated rebuild of the document require the developer to be involved with every step of the change.

Wouldn’t it be more convenient if the document’s manager could make all the changes he wanted in another application and then provide that document to your generation tool to be processed?

WordprocessingML supports a page element called a structured document tag that allows you to add named custom controls directly to a page. As a developer you can write code that will look through the /word/document.xml package part to find these tags and then directly modify their content.

Structured document tags have another feature as well that once configured eliminates the need to modify the /word/document.xml file. This feature, known as data binding, allows structured document tags to contain an XPath query that will locate the data for the tag. That XPath query is then used to access data in a special package part known as a customXml part. Now all you need to do when creating a new version of the document based on XML data is to replace the content of the custom xml package part.

Office Open XML 1

Page 2: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Lab 05 Module 05: Data Binding with Content Controls

In this exercise you’ll perform the three steps necessary to use content controls to perform data binding. First you’ll add content controls to an existing document. Next you’ll modify the /word/document.xml package part to add data binding to each of the content controls. Finally you’ll add the customXml package part that the controls bind to.

Exercise 0: Getting Started

In this exercise, you will open the OfficeOpenXML solution, which contains the starting points for all of the labs.

To open the Office Open XML solution:

1. In Visual Studio 2010, on the File menu, select to Open, and then click Project/Solution.

2 Office Open XML

Raw DocumentCreated using Word 2010

Document with Content ControlsAdd content controls to document

Document with Data BindingAdded data binding markup to document

Completed Output DocumentEmbedded CustomXml document.

Page 3: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Module 05: Data Binding with Content Controls Lab 5

If Visual Studio 2010 is not open, click Start, point to All Programs, point to Microsoft Visual Studio 2010, and then click Microsoft Visual Studio 2010.

2. In the Open Project dialog box, navigate to the C:\OfficeOpenXML\Labs\Starter folder, select Starter.sln, and then click Open.

3. Locate the Lab05 project in the Solution Explorer. All of the following exercises will be done using this project.

If the Solution Explorer is not visible, click View and select Solution Explorer to open it.

4. Right click Lab05 in the Solution Explorer and select Set as StartUp Project. This will cause all commands such as Build and Debug to act on this project.

Exercise 1: Adding Content Controls to an existing document.

The first step in data binding to content controls is to add the content controls to the document. This could be done by the developer or even by the document’s manager. The placement of content controls by the document manager gives them more control over the look and feel of the document. Content controls can be placed by any application that supports WordprocessingML and the structured data tag (w:sdt) element. In this exercise you’ll be using Word 2010.

Adding a content control to a document in Word 2010 is done using a special set of options that are not visible by default. These options are stored on the Developer tab in the office ribbon and are only accessible once a Word option to show the ribbon tab is selected. Once this is enabled, you can add content controls to the document.

<!-- Before Content Control Addition --><w:p> <w:r w:rsidRPr="00971733"> <w:t>$610,881.02</w:t> </w:r></w:p>

<!-- After Content Control Addition --><w:p> <w:sdt>

Office Open XML 3

Page 4: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Lab 05 Module 05: Data Binding with Content Controls

<w:sdtPr> <w:alias w:val="TotalSales" /> <w:tag w:val="TotalSales" /> <w:id w:val="100621848" /> <w:lock w:val="contentLocked" /> <w:placeholder> <w:docPart w:val="DefaultPlaceholder_22675703" /> </w:placeholder> <w:text /> </w:sdtPr> <w:sdtContent> <w:r w:rsidRPr="00971733"> <w:t>$610,881.02</w:t> </w:r> </w:sdtContent> </w:sdt></w:p>

When you add a content control to the document, a structure data tag (w:sdt) element is added to the WordprocessingML. There are two primary sections, the structured data tag properties (w:sdtPr) element and the structure data tag content (w:sdtContent) element. The first section defines the name, the locked state of the control, as well as data binding information (you’ll be adding this later). The content section defines the current content of the content control. Notice that this is a simple run (w:r) element.

Adding label content controls in Word 2010:

1. Using the Solution Explorer open the Resources\BaseWordprocessingML.docx.

2. In Word 2010, click on File and select Options.

3. Check on Customize Ribbon in the panel.

4. Under the Choose commands from drop down list, select All Tabs.

5. Add the Developer tab to the Ribbon.

4 Office Open XML

Page 5: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Module 05: Data Binding with Content Controls Lab 5

This option will add a new tab to the ribbon that exposes controls that are targeted toward

developers, not every day users.

6. Select the total sales value text ($10.00).

7. Select the Developer tab and click the Text content control ribbon button to add a text content control.

8. With the new content control selected, click the Properties ribbon button on the Developer tab.

9. In the Content Control Properties dialog, enter a name of TotalSales and check the Contents cannot be edited.

Office Open XML 5

Page 6: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Lab 05 Module 05: Data Binding with Content Controls

10. Click OK to apply the changes.

11. Repeat steps 4 through 8 for each Territory total in the document. Use the chart below to determine the name for each Text content control.Territory Content Control Name

Australia AustraliaTotalsCanada CanadaTotalsCentral CentralTotalsFrance FranceTotalsGermany GermanyTotalsNortheast NortheastTotalsNorthwest NorthwestTotalsSoutheast SoutheastTotalsSouthwest SouthwestTotalsUnited Kingdom UnitedKingdomTotals

Adding date picker content controls in Word 2010:

1. Select the begin date (1/1/2003) at the top of the document.

2. Select the Developer tab and click the Date Picker content control ribbon button to add a date picker content control.

6 Office Open XML

Page 7: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Module 05: Data Binding with Content Controls Lab 5

3. With the new content control selected, click the Properties ribbon button on the Developer tab.

4. In the Content Control Properties dialog, enter a name of BeginDate and check the Contents cannot be edited.

5. Click OK to apply the changes.

6. Repeat steps 1 through 5 for the end date (12/31/2003). Use the name EndDate for the date picker content control.

7. Close and save the BaseWordprocessingML.docx file.

Exercise 2: Data binding to a customXml package part

Now you have a WordprocessingML document containing structured data tag (w:sdt) elements in the locations where data must be customized for the current sales report summary. The next step is to embed the sales report summary directly into the document and then bind the content controls to that data.

Office Open XML 7

Page 8: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Lab 05 Module 05: Data Binding with Content Controls

You’ll start by adding a new /customXml/summaryData.xml package part. This will contain the custom Xml data shown below.

<SalesReportSummary beginDate="2006-01-01T00:00:00" endDate="2006-12-31T00:00:00" salesTotal="$1000.00" ...> <Territories territory="Australia" salesTotal="$100.00" /> <Territories territory="Canada" salesTotal="$100.00" /> ...</SalesReportSummary>

Once the document and relationships are in place, you’ll add the data binding information to each structured data tag (w:sdt) element. This data binding element is made up of three pieces of information: the data store id, prefix/namespace mappings, and an XPath query.

<w:dataBinding w:prefixMappings="xmlns:ns0= 'http://adventureworks.com/2006/sales'" w:xpath="ns0:SalesReportSummary/@salesTotal" />

In this exercise you’ll be creating the customXml package parts and defining the necessary relationships. Once that is complete, you’ll be adding the data binding (w:dataBinding) element to each structured data tag (w:sdt) element to complete the bound document.

Adding the custom XML package part:

1. Using the Solution Explorer open Program.cs.

2. Locate the CreateTemplateDocument method.

3. Create a new PackageHelper object named package based on the BaseWordprocessorML resource.

// create the template packageusing (PackageHelper package = new PackageHelper( Properties.Resources.BaseWordprocessingML)){}

4. Inside the using statement, add the code to create the new /customXml/summaryData.xml package part.

// add the customXml package partUri customXmlUri = new Uri("/customXml/summaryData.xml", UriKind.Relative);package.CreateNewPart(customXmlUri, "application/xml", Properties.Resources.SummaryXmlTemplate);

8 Office Open XML

Page 9: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Module 05: Data Binding with Content Controls Lab 5

The summary xml template resource contains a sample Xml document that will be bound to until

the custom Xml package part is replaced with real data.

5. Add the relationship between the /word/document.xml package part and the /customXml/summaryData.xml package parts.

// add the relationship between the document and custom xmlUri documentUri = new Uri("/word/document.xml", UriKind.Relative);package.CreateInternalRelationship(documentUri, customXmlUri, "http://schemas.openxmlformats.org/officeDocument/" + "2006/relationships/customXml");

Adding the data binding to the content controls:

1. Locate the AddDataBinding method.

2. Build the xPath query to locate the content control by name.

// lookup the content control and add the databinding nodestring documentQuery = string.Format("//w:sdt/w:sdtPr[w:alias/@w:val='{0}']", contentControlName);

The XPath query above searches for all structured data tag (w:sdt) elements in the

document with the appropriate name.

3. Execute the XPath query on the documentXml parameter to find the structured data tag.

XPathNavigator contentControlNav = documentXml.CreateNavigator().SelectSingleNode( documentQuery, Namespaces.NamespaceManager);

4. Using the XPathNavigator object, append a child node to the document. This node will be used to store the data binding parameters.

// append a child node using a XmlWriterusing (XmlWriter writer = contentControlNav.AppendChild()){}

5. Inside the previous using statement, write the data binding element to the structured document tag (w:sdt) element.

// add the databinding// <w:dataBinding// w:prefixMappings=// "xmlns:ns0='http://adventureworks.com/2006/sales'"

Office Open XML 9

Page 10: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Lab 05 Module 05: Data Binding with Content Controls

// xPath="..." storeItemId="..." />writer.WriteStartElement(Prefixes.WordprocessingML, "dataBinding", Namespaces.WordprocessingML);writer.WriteAttributeString(Prefixes.WordprocessingML, "prefixMappings", Namespaces.WordprocessingML, "xmlns:ns0='http://adventureworks.com/2006/sales'");writer.WriteAttributeString(Prefixes.WordprocessingML, "xpath", Namespaces.WordprocessingML, xPathQuery);

Write the new template document:

1. Locate the CreateTemplateDocument method.

2. At the end of the method, add the code to read the /word/document.xml package part into an XmlDocument.

// load the document package part into a XmlDocumentXmlDocument documentXml = package.GetWritablePart(documentUri);

3. Use the AddDataBinding method to add the data binding markup to the BeginDate content control using an XPath query of ns0:SalesReportSummary/@beginDate.

// add databinding to the content typesAddDataBinding(documentXml, "BeginDate", "ns0:SalesReportSummary/@beginDate");

BeginDate corresponds to the name of the content control in this document and ns0:SalesReportSummary/@beginDate

corresponds to the element in the source XML data set.

4. Repeat the previous step using the content control names and XPath queries belowContent Control XPath

EndDate ns0:SalesReportSummary/@endDateTotalSales ns0:SalesReportSummary/@salesTotal

5. Use the AddDataBinding method to add data binding markup for the territory totals.

AddDataBinding(documentXml, "AustraliaTotals", "ns0:SalesReportSummary/ns0:Territories" + "[@territory='Australia']/@salesTotal");

This XPath query uses a test that compares the territory attribute value to a string to find the

appropriate Territories element.

10 Office Open XML

Page 11: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Module 05: Data Binding with Content Controls Lab 5

6. Repeat the previous step using the content control names and territory name below. Replace the comparison to Australia with a comparison to the territory name below.Content Control Territory Name

CanadaTotals CanadaCentralTotals CentralFranceTotals FranceGermanyTotals GermanyNortheastTotals NortheastNorthwestTotals NorthwestSoutheastTotals SoutheastSouthwestTotals SouthwestUnitedKingdomTotals United Kingdom

7. Save the changes to the XmlDocument back into the /word/document.xml package part.

// save the document xml back into the packagepackage.SavePart(documentUri, documentXml);

8. Save the package to the file system in the file Lab05Template.docx.

// save the template documentpackage.Save("Lab05Template.docx");

Run and verify the results

1. Build the project by opening the Build menu and clicking Build Lab05.

2. Run the project by opening the Debug menu and clicking Start Without Debugging.

If you try to run the application while the output file is currently in use, the sample will fail.

Simply close the generated file and run the sample again.

3. Open Windows Explorer and navigate to C:\OfficeOpenXML\Labs\Starter\Lab05\bin\Debug and open Lab05Template.docx. You should see a document similar to the one below.

If Windows Explorer is not open, click Start, right click My Computer and click Explore.

Office Open XML 11

Page 12: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Lab 05 Module 05: Data Binding with Content Controls

Notice that the content of this document is the same as the SummaryXmlTemplate resource.

Exercise 3: Replacing the CustomXml package part with new data

In the previous two exercises you started with a document designed in Word 2010 and converted it to a data bound document. Now that you have this template data bound document in your library, it is a simple process to replace the custom Xml and consequently create a new document. This technique is very powerful since you can quickly generate an entirely new document in very few lines of code.

In this exercise you’ll be using the SalesReportData project to provide you with new sales data. You’ll take this data and serialize it to Xml and use that Xml to replace the existing /customXml/summaryData.xml package part. The goal of this exercise is to show how easy it is to replace a customXml package part, and have the results updated on the main body of the document.

Replacing the custom Xml package part:

1. Locate the ReplaceCustomXml method.

2. Add the code to open the package using the BoundTemplate resource.

12 Office Open XML

Page 13: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Module 05: Data Binding with Content Controls Lab 5

// create the package based on the templateusing (PackageHelper package = new PackageHelper(Properties.Resources.BoundTemplate)){}

The BoundTemplate resource is a resource containing the same content as you created in the

last exercise. It is included as a resource to simplify the process of performing this exercise.

3. Inside the using statement, load the customXml XmlDocument from the SalesReportData project.

// load the custom xml into an XmlDocumentXmlDocument customXml = GetCustomXml();

The GetCustomXml method loads the data from the SalesReportData project and serializing to

an XmlDocument using the XmlSerializer. For more information, see the GetCustomXml method.

4. Replace the xml data in the /customXml/summaryData.xml using the customXml XmlDocument.

// replace the data in the customXml partUri customXmlUri = new Uri("/customXml/summaryData.xml", UriKind.Relative);package.SavePart(customXmlUri, customXml);

5. Save the package to the file system in the file Lab05Solution.docx.

// save the documentpackage.Save("Lab05Solution.docx");

Run and verify the results

1. Build the project by opening the Build menu and clicking Build Lab05.

2. Run the project by opening the Debug menu and clicking Start Without Debugging.

If you try to run the application while the output file is currently in use, the sample will fail.

Simply close the generated file and run the sample again.

3. Open Windows Explorer and navigate to C:\OfficeOpenXML\Labs\Starter\Lab05\bin\Debug and open Lab05Solution.docx. You should see a document similar to the one below.

Office Open XML 13

Page 14: openxmldeveloper.orgopenxmldeveloper.org/cfs-filesystemfile.ashx/__key/...  · Web viewIn this exercise you’ll be using Word 2010. ... These options are stored on the Developer

Lab 05 Module 05: Data Binding with Content Controls

If Windows Explorer is not open, click Start, right click My Computer and click Explore.

To finish up:

1. On the File menu, click Save All.

2. On the File menu, click Close Solution.

14 Office Open XML