CHAPTER 2

image

Visio Services

You’ve probably heard that a picture is worth 1,000 words, and also that actions speak louder than words. If you put those two axioms together, you get the idea of Visio. It is often far easier to understand and simpler to explain a concept, a theory, or even a story by presenting actions visually in blocks and diagrams rather than using words. Visio is a very powerful vector graphic tool you can use for exactly that.

What Will You Learn?

By the end of the chapter, you’ll learn about

  • The essentials of Visio Services
  • Setting up Visio Services on SharePoint 2013
  • Publishing a basic Visio diagram to SharePoint
  • Connecting Visio diagrams to
  • A SharePoint list
  • SQL Server, with and without Secure Store Services
  • Data using a custom data provider (using Visual Studio and WCF)
  • Workflows and Visio with SharePoint Designer 2013
  • Management of Visio Services using Central Administration (CA)
  • Management of Visio Services using Windows PowerShell

Software Prerequisites

To get the most out of this chapter, you’ll need the following software:

Introduction to Visio Services

Let me walk you through a small story called “My day begins with  .  .  .” I wake up early in the morning, get ready, and start from home at about 7:15 AM. On my way driving to the office, I stop by the nearest coffee shop to pick up my morning beverage. I choose hot chocolate and head for the office—yet another decision to make, whether or not to take the freeway. I quickly look over my shoulder and, because there’s not a lot of traffic, I choose to drive on local streets. At 8:45 AM, I arrive at the office.

Notice the italicized words in my little story. It’s all about initiation, actions, decisions, and conclusions. Of course, these four elements and maybe few others are required to run our lives and, in fact, any job too. Simply put, if I want to tell my story in the form of a diagram or a flow chart, it becomes a sort of storyboard—a logical sequence of boxes connected together, as shown in Figure 2-1.

9781430258933_Fig02-01.jpg

Figure 2-1. “My day begins with  .  .  .” storyboard

This chapter introduces you to Visio Services and discusses using Visio with SharePoint 2013. If you’re already familiar with Visio, a few concepts might be redundant. You might want to either skip them or parse them quickly.

Why Visio?

With Visio, you can create a wide range of diagrams easily with the help of built-in shapes, stencils, and templates. The diagram scope can encompass the simple, like my storyboard, or the complex, like the network representation of an entire organizational infrastructure. It can target various audiences, from business analysts to developers to solutions architects. A construction engineer or an interior designer can create a floor plan. An electrical engineer can create a basic electrical circuit or a logic diagram. There are endless possibilities using Visio; you just need to focus your imagination on the available templates to create your own diagrams.

Now, what if your Visio diagrams could come to life? What if you could power these diagrams with data and share them with your colleagues?

Let me give you a real-life example. As an architect in the organization where I work, I’m often asked to give introductory sessions to many people on the project team, and I typically use a Visio diagram to explain the project details. Whenever there are enhancements, updates, or changes to the project, I have to redo my Visio diagram and present it to the team.

Instead of calling for another meeting, I could update and e-mail a new version of the Visio diagram and get final approval. But not everyone has Visio installed. Moreover, where does this information end up? E-mails! Or maybe in yet another set of printed documents that will just collect dust on the shelf. What’s missing here?

  1. Collaboration.
  2. Easy viewing. For a Visio diagram, you need either the Visio client and related licenses, or at least a Visio viewer. (There’s a free viewer available at www.microsoft.com/en-us/download/details.aspx?id=35811.)
  3. Instant update of the diagrams.
  4. Data connectivity.

You’ve all probably thought at some point, wouldn’t it be great to be able to share a Visio diagram that’s connected to data, where the diagram updates automatically when the data changes. And wouldn’t it be wonderful to be able to have end users view the diagram in their browsers without having to install the actual Visio client.

Well, that solution is here. With Visio Services in SharePoint 2013, you can publish Visio diagrams to SharePoint, drive them with real-time data, and share them easily even when the client is not installed. You can do all of this by using Visio Services in SharePoint 2013.

Presenting Visio Services

Visio Services is available as part of the Enterprise Client Access License (CAL), and they provide a platform where users can share the Visio diagrams using the SharePoint infrastructure. Visio Services provides various data-connectivity models to drive Visio diagrams with data, both real-time and historic.

Setting Up Visio Services

Setting up Visio Services is quite simple, requiring just few basic steps. Before beginning, however, ensure you have Farm Administrator privileges.

There are two approaches. In the first, in SharePoint 2013, simply go to Central Administration image Configuration Wizards and launch the Farm Configuration wizard as shown in Figure 2-2.

9781430258933_Fig02-02.jpg

Figure 2-2. Launching the Farm Configuration wizard

image Tip  If you are installing SharePoint for the first time, you’ll be prompted to run this step toward the end of the installation. If you prefer, you can just skip it for now and run it later.

Next, you are prompted to start the wizard, as Figure 2-3 shows.

9781430258933_Fig02-03.jpg

Figure 2-3. Choosing the farm configuration using the wizard

To set up the services, you need to have a service account and choose the required services from the wizard (Figure 2-4). Be sure you have Visio Graphics Service selected. If this is a fresh installation, this option will be enabled.

9781430258933_Fig02-04.jpg

Figure 2-4. Select the desired services using the Farm Configuration wizard

Click Next. SharePoint will provision all services selected in this step, and it prompts you to create a new site collection with the selected services. You cannot choose a service that’s already installed because it will be disabled, as shown in Figure 2-4.

image Note  With this default mode and the service application already available to the default web application, you can now create a site collection using one of the available templates.

This approach is very straightforward. Things get a little more interesting when you haven’t set up the services during installation or if you later upgrade your licensing model. In such situations, you can set up Visio Services using the following approach.

Go to Application Management image Service Applications image Manage Service Applications. Click the New button on the ribbon and then choose Visio Graphics Service. Provide a valid application name, and choose or create a new application pool under which this service application will run. As you create the application pool, you’ll have the option to use any already configured service accounts or to register a new managed account, as shown in Figure 2-5.

9781430258933_Fig02-05.jpg

Figure 2-5. Setting up a new Visio Graphics Service application

Your new service application will now appear in the list of available service applications and you can configure it, as we’ll discuss later in this chapter.

image Note  Once you create the new service application, you have to associate it with a web application. You can associate a new service application with a new web application or an existing web application.

To associate a new service application with a web application, on the Central Administration site go to Application Management image Service Applications image Configure service application associations and select the Web application you want to associate the service with. For the Configure service application association connections option, choose Custom. Select the desired custom service application, and click on OK.

Let’s now look at an example and see how to perform basic operations using Visio and Visio Services in SharePoint 2013.

PROBLEM CASE

Check the status of five major airline carriers at the airport using a Visio diagram that’s been published to SharePoint using Visio Services 2013.

Solution

  1. Verify that the SharePoint Server Enterprise Site Collection Features feature is activated. (This is required to use Visio Services.) You’ll find this on the Site Collection Features under the Site Collection Administration menu group on the Site Settings page.
  2. Open Visio 2013, choose Directional Map Shapes 3D (US Units) from the available diagrams, and add Airport to the page. Add a few images or shapes, such as Store 1, Tree, and Roof 1 from Directional Map Shapes 3D, and an Airplane from More Shapes image Visio Extras image Symbols (US units) image Airport, as shown Figure 2-6.

    9781430258933_Fig02-06.jpg

    Figure 2-6. Airport stencil with various shapes

    Your diagram doesn’t need to look exactly like this. You can design a scene that uses your own images and creativity to try this example. You can also use the Airport (BasicDiagram). vsdx file in the source code accompanying this book.

  3. On the File menu, click on Save and save the drawing to a local file location as a Visio Drawing—airport.vsdx in this example.

    image Note  .vsdx is a new file format introduced in Visio 2013, which allows you to save a Visio 2013 drawing directly to a SharePoint library without having to publish the file as a Visio Web Drawing (.vdw). In Visio Services 2010, you have to save and publish your Visio drawing in .vdw file format before it can be rendered in the browser. For more information on the .vsdx file format, refer to the article at msdn.microsoft.com/en-us/library/jj228622.aspx.

  4. Close Visio, and return to the folder where you saved the <filename>.vsdx file.
  5. Open your SharePoint site, and create a new document library from Settings image Add an App image Document Library; name it Visio Library.
  6. Click on new item. In the Add a document window, use the Browse option, choose the .vsdx file, and click OK. Optionally, update the properties of the document and click on the Save button.

    After the document is successfully uploaded, you’ll be returned to the document library, where you’ll see a new item—the document you just uploaded.

  7. Click on the document Name column to open the Visio diagram in full-screen mode in the browser, as shown in Figure 2-7.

    9781430258933_Fig02-07.jpg

    Figure 2-7. Visio web drawing file in the browser

As you’ve seen, it’s very easy to create, publish, and view Visio drawings on SharePoint platform. Now let’s discuss some of the features and capabilities of Visio Services.

image Tip  In Visio Services 2013, users can add comments to Visio diagrams and reply to comments posted by others. As shown in Figure 2-7, clicking on the Comments button opens the comments pane, which allows you to view comments, reply to a comment, and add a shape or page-level comment.

Visio Services Features

Following are some of the noteworthy features of Visio Services:

  • Visio diagrams are compatible with Internet Explorer and other major browsers, like Mozilla Firefox, Google Chrome, and Apple Safari.
  • Diagrams are rendered using Silverlight. If Silverlight is not installed on the client machine, diagrams are rendered as PNG image files.
  • You can connect data to shapes1 in a diagram from various supported data sources.
  • You can use a variety of data graphics2 for a given data field and corresponding shapes based on the conditions and data. Figure 2-8 shows the idea at a very high level.

    9781430258933_Fig02-08.jpg

    Figure 2-8. Data graphics that can be used on shapes

  • You can set hyperlinks on the shapes. You can link to an Internet address or another local Visio diagram, as shown in Figures 2-9 and 2-10.

    9781430258933_Fig02-09.jpg

    Figure 2-9. Adding a hyperlink to a shape

    9781430258933_Fig02-10.jpg

    Figure 2-10. Linking a shape to an Internet address or local file

  • No client-side installation is required—diagrams are fully loaded in the client browser.
  • Real-time data refresh means you can connect your diagrams with real-time data using various data sources, including
  • SQL Server
  • Excel
  • SharePoint Server Lists
  • OLE DB
  • ODBC
  • Custom data providers
  • Business Connectivity Services (BCS)

image Caution  Note that some data sources, such as SQL Server Analysis Services, are not supported.

  • Publish once, use multiple times. You can create the diagrams, connect them to data, and publish them to your SharePoint environment. The diagrams load data from the underlying data sources, and you won’t have to modify them unless the source diagrams change. When the data changes, the shapes will automatically reflect the changes.
  • Various authentication models 3 are supported, including
  • Secure Store Services (SSS)4
  • Kerberos or Integrated Windows Authentication
  • Unattended Authentication

image Note  In this chapter, we will discuss how to connect to a SQL Server data source, a SharePoint Server list, and a custom data provider, with examples.

In the first example, you saw how to publish a Visio drawing to SharePoint and view it. That’s one of the ways to integrate Visio with SharePoint. There are a number of other methods for loading and interacting with a Visio drawing on SharePoint 2013, including the following:

  • Visio Web Access Web Part: Use a Web part that can load a .vsdx/.vdw file.
  • JavaScript Mashup API: Communicate with a Visio Web Access Web Part and change HTML content as needed asynchronously.
  • Web Part connections: Connect and communicate with other Web parts on the page.
  • SharePoint Designerwith Visio: Create diagrams in Visio, import them into SharePoint Designer, and publish them to the SharePoint environment.
  • Commenting: Users can add comments to Visio diagrams and see comments posted by others.

We’ll discuss these later in this chapter, but first we’ll take a look the architecture and building blocks of Visio Services.

Architecture

Figure 2-11 shows the components a Visio Services environment. Visio Services is loaded into and becomes an integral part of SharePoint Server 2013, which runs on Windows Server 2008 R2 in conjunction with IIS, SQL Server, and Windows Identity foundation (formerly known as Geneva Framework). Visio Services can run in both hosted and nonhosted environments.

9781430258933_Fig02-11.jpg

Figure 2-11. The architecture of a Visio Services 2013 environment

image Note  Hosted environments are platforms provided by external vendors on which you can run your own applications. You might have some access to the physical servers and file system, but it can be rather limited. Still, this can be a very cost-effective solution that can reduce a lot of your operating costs. Nonhosted or in-house environments, on the other hand, are fully controlled by your own organization. These are physical servers commissioned in your own network that you have full access to.

To understand the architecture, take a look at the life cycle of a Visio drawing, as shown in Figure 2-12. A designer or a business analyst retrieves data from one of the supported data sources and creates a Visio diagram. He saves it as a drawing file (.vsdx), and then uploads or publishes the diagram to the SharePoint Server document. Visio Services then renders this document by accessing the data source and displaying the output to the end user(s) in either Silverlight or as a PNG file. Note that you don’t actually need a data source.

9781430258933_Fig02-12.jpg

Figure 2-12. Life cycle of a Visio diagram

Now here’s the interesting part: the designer who creates the diagram might not be a part of the entire life cycle of the diagram. He doesn’t need to have any knowledge of SharePoint. He can simply create the designs and provide them to the person in the next level in the hierarchy who can publish them to SharePoint. End users will access the diagrams through application servers and view them in the browser directly. However, the process of publishing a diagram to Visio Services is simple.

In the next section, we will explore how you can bind web drawings to data. In the “Link Data to Shapes” section, I’ll show you how to link data to shapes using the Data Selector wizard. In the “Data Graphics” section, I will also show you how , you can connect data to a shape and customize the appearance of a shape.

The Visio 2013 Client’s Data Tab

To bind data to a data source in the Visio 2013 client, you use the options accessed by clicking on the Data tab of the ribbon (Figure 2-13). To enable all the buttons that belong to this tab, you should have at least one diagram open. Let’s understand what each button does.

9781430258933_Fig02-13.jpg

Figure 2-13. Data tab in Visio 2013

Link Data to Shapes

Linking data to shapes is one of the ways you can connect a data source to a shape. You get a simple Data Selector wizard that connects to various supported data sources, as shown in Figure 2-14. You can create more than one data source using this option and use them to connect data to the shapes.

9781430258933_Fig02-14.jpg

Figure 2-14. The Data Selector window

image Note  Another way to create a data source is by using VBA code, as you’ll see when we look at designing a custom data provider.

Data Graphics

Data graphics is the mechanism that lets you connect data to the shape and customize the appearance of the shape. It allows you to add visual information about the data to the shape on the Visio diagram. You can build your own data graphic, assign it to any data field, and display the corresponding value in one of these forms: Text, Data Bar, Icon Set, or Color by Value. Data fields are the columns that belong to a list or data table available through the data source you selected.

Data graphics define additional design structures for the shape, and you can create more than one. Once you set your own custom data graphics, they can be used on any other shapes on the Visio diagram using the Automatically Link button.

Data graphics get data from the data source specified in Link Data to Shapes or Shape Data Window.5 When you link to the data source, the data graphics display real-time or historical information based on the customizations you’ve set on Visio Graphics Services in Central Administration.

Here’s how to create new data graphics :

  1. Click on the Data Graphics icon on the Data tab. This displays a settings window, as shown in Figure 2-15.

    9781430258933_Fig02-15.jpg

    Figure 2-15. Creating a new data graphic

  2. Click Create New Data Graphic to open the New Data Graphic window.
  3. Click New Item, and a new window opens with settings for display and position, as shown in Figure 2-16.

    9781430258933_Fig02-16.jpg

    Figure 2-16. The data graphics New Item window

  4. In the display section, the Data field drop-down consists of the available fields from the connected data source. When there’s no data source, few fields are displayed. If you need a data field and don’t have a data source, you can define a custom shape data label that can be used as a data field in this context.
  5. To create a custom shape data label, right-click on the shape on your diagram and, from the Data menu, select Define Shape Data. In the window that opens, enter the Label value as “Text” (or your own custom label); select the Type as String (or whatever data type you need); set the Value to a specific data value; and optionally configure other settings if necessary. Then click OK.
  6. The label will now appear in the Data field drop-down in the data graphics New Item window.
  7. Once you select your new Data field label, the Displayed as drop-down is enabled and has options for Text, Data Bar, Icon Set, and Color by Value.

For this example, let’s go with the Text option :

  1. Choose Text in the Displayed as field to display the Style drop-down, with various options.
  2. Once you’ve chosen the style, you can use the Position section to set the style either horizontally or vertically for the shape. For instance, if you want to display the value of the Text within a Circle callout and position it horizontally to the Right and vertically at the Bottom of the shape, the settings would be similar to those in Figure 2-17.

    9781430258933_Fig02-17.jpg

    Figure 2-17. Set data field styles, position, and details

  3. In the Details section, you can set the data field metadata values. For instance, @ in the Value Format field represents Text format.
  4. Clicking OK returns you to the New Data Graphic window.
  5. You can edit an existing item by clicking Edit Item, and you can delete an item by clicking the Delete button. Click OK to close the wizard.
  6. You can also set the value of the shape using the Shape Data Window that’s available when you select this option in the Show/Hide section of the Data tab. You can set the Text value and view how the value is displayed for the shape. For instance, to set the Text value for the flight shape as “Passenger Airplane,” select the shape and on the Shape Data Window, type in Passenger Airplane. The text will appear in the bottom right corner of the image as a callout, as per the previous position settings (Figure 2-18).

    9781430258933_Fig02-18.jpg

    Figure 2-18. Adding text to the shape

    image Note  You can obtain this shape from More Shapes image Visio Extras image Symbols (US units) image Airport.

    image Tip  You’ll notice the same text label beneath the shape; this is the general text that comes with the shape, and it’s what would be used as a condition for automatically linking other shapes.

Automatically Link

To use the Data tab’s Automatically Link functionality, first you need to set a Text value either by double-clicking on the shape or by using the Shape Data Window on all the shapes. Using the Data Graphics option, you can create items based on data fields (as shown in the previous section). First, you will have to create a complete data graphic for at least one shape. After you create the data sources, you can bind a shape to a row of data by simply dragging and dropping the row onto the shape. This process creates a link between the shape text, the data column name (for instance, Title), and the column values of the row. This is the final step before linking all the shapes. Click on the Automatically Link button in the External Data section of the Data tab. The wizard lets you decide whether to link Selected shapes or All shapes on this page, as shown in Figure 2-19.

9781430258933_Fig02-19.jpg

Figure 2-19. Automatically link data to shapes

Choosing one of these options takes you to the next step—mapping the Data Column to the Shape Field, as shown in Figure 2-20. Click Next to reach the Details page, or click Finish to complete the automatic linking. This step links all shapes with the text matching the Data Column name.

9781430258933_Fig02-20.jpg

Figure 2-20. Link a data column to a shape field

Refresh All

Once you create the data sources using Link Data to Shapes, you can refresh them either individually or all at once to get the updated data. When you hover over the Refresh All button, it opens a context menu as shown in Figure 2-21.

9781430258933_Fig02-21.jpg

Figure 2-21. Refresh All data window

image Note  Using Refresh All or Refresh Data doesn’t affect SharePoint in any way. These options work only with respect to the Visio diagram and the related data source.

You can choose the data source (if one is available) and click on either Refresh or Refresh All to refresh the available data sources as shown in the Figure 2-22. Either action will connect to the data source and retrieve the most recent data. Choosing the data source and clicking on Configure opens the data source configuration wizard. If no data source was configured earlier, none is listed in this window.

9781430258933_Fig02-22.jpg

Figure 2-22. Refresh Data window

Insert Legend

Use Visio 2013 Data tab:(as shown in Figure 2-23) to display information regarding the Data Bar, Icon Set, or Color by Value display options available from the Data Graphics dialog. Legends display information related to the existing page. You can set the legend direction to be either horizontal or vertical. However, legends are not automatically updated. If you modify the diagram, legends need to be manually deleted and inserted once again to reflect the changes.

9781430258933_Fig02-23.jpg

Figure 2-23. Insert Legend wizard

Shape Data Window

The Shape Data Window is made available by selecting the appropriate box on the Data tab. It displays data information about the shape, and you can also set the data values for the shape, as shown in the Figure 2-24.

9781430258933_Fig02-24.jpg

Figure 2-24. Shape Data window

External Data window

You can select the External Data Window box on the Data tab to make this window accessible. It displays all the available data sources for a given page of the Visio diagram, and you can create a new data source by clicking on Link Data to Shapes as shown in Figure 2-25.

9781430258933_Fig02-25.jpg

Figure 2-25. External data window

With the help of these options and settings, you can design the Visio diagrams with shapes, connect the shapes to data, and then publish the drawings to a SharePoint environment. In the next section, you’ll see how to integrate all that you’ve learned so far with Visio and Visio Services.

Integrating Visio with SharePoint

So far, you saw at a very high level how to integrate Visio diagrams with SharePoint. Now you’ll learn this practically, using some examples.

Let’s create a Visio diagram using a SharePoint list as a data source and see how to deploy the diagram to the SharePoint platform.

PROBLEM CASE

Take the airport flight status example, and populate information from a SharePoint list to the diagram. Then publish the diagram to the SharePoint environment, and view it with real-time data.

Solution

  1. Open a SharePoint site, and create a custom list with the name Airport Flight Stats, with columns as shown in Figure 2-26.

    9781430258933_Fig02-26.jpg

    Figure 2-26. Sample custom SharePoint list structure

  2. Populate a few rows of data for various airline carriers, as in Figure 2-27.

    9781430258933_Fig02-27.jpg

    Figure 2-27. Custom list with data used as a data source

  3. When you’ve created the list, open Visio.
  4. Open the Airport.vsd file, and click on the Link Data to Shapes icon either on the Data tab or from the External Data pane at the bottom of the page (Figure 2-28).

    9781430258933_Fig02-28.jpg

    Figure 2-28. Accessing Link Data to Shapes to build a data source

  5. From the Data Selector window, choose the Microsoft SharePoint Foundation list option and click Next.
  6. Enter the URL for the site where you created the custom list, and click Next.
  7. Choose Airport Flight Stats from the List box, and select the option Link to a list. You can also create a View on the custom list and choose Link to a view of a list. Click Next to continue.
  8. On the final screen, click Finish to complete the Data Selector wizard.
  9. If External Data Window is selected on the Data tab, you should now have the External Data window visible at the bottom of the screen with the custom list data loaded, as shown in Figure 2-29. Notice that the list name is added to the External Data Source window at the bottom.

    9781430258933_Fig02-29.jpg

    Figure 2-29. External Data window populated with selected data

  10. To link data to the shape, simply drag one of the rows to a particular shape on the page. If the data is properly linked, you’ll see a link icon in the External Data window next to the row (first column), as shown in Figure 2-30. Alternatively, you can select the shape first and right-click on the row you’d like to bind, and then from the context menu choose the option Link to Selected Shapes.

    9781430258933_Fig02-30.jpg

    Figure 2-30. Linking data to shapes from the External Data window

  11. As you can see, you can also disconnect the row data from the shape using the Unlink option from the context menu.
  12. When all the rows are linked, the leftmost columns will display link icons for all the rows.

    image Caution  If there is any mismatch between the column name and the text on the shapes, the linking will not work. Also, if you add a new row of data, you’ll need to create a new shape and link the row data to that shape.

  13. Click on Data Graphics, and choose the Create New Data Graphic option.
  14. Click on New Item. From the Data field, choose Arrival delays, and from the Displayed as options, choose Icon Set.
  15. From Style, choose the face icons as shown in Figure 2-31.

    9781430258933_Fig02-31.jpg

    Figure 2-31. Choosing a style for Arrival delays

  16. Under the Rules for showing each icon panel, set the conditions and values for each icon as in Figure 2-31.
  17. Choose the position as Right for Horizontal and Top for Vertical, and click OK.
  18. Once again, from the New Data Graphic window, click on New Item and in the Data field, choose Missing baggage count.
  19. Under the Displayed as option, choose Data Bar and select Star rating as the Style.
  20. In the Details section, set Minimum Value to 18 and Maximum Value to 0 and leave the other options as they are, as shown in Figure 2-32. Deselect Use default position, set Horizontal to Center, set Vertical to Top, and click OK.

    image Note  Because the maximum baggage count by any airline carrier in this example is 18, we’ll use this for easy comparison.

    9781430258933_Fig02-32.jpg

    Figure 2-32. Choosing a style for Missing baggage count

  21. Return to the New Data Graphic window, and notice the two data-field settings. If you click either Apply or OK, an alert asks “Do you want to apply this data graphic to the selected shapes?” Click Yes to close the prompt.
  22. Notice the two icon sets that are displayed for the British Airways flight; with the available data (Figure 2-33), the graphic must display ratings in the center top position and a frown icon in the right top corner.

    9781430258933_Fig02-33.jpg

    Figure 2-33. Data graphics set to the shape

  23. Select other shapes, and link corresponding rows of information to them as described earlier.

    image Tip  Alternatively, select each of the shapes in the diagram and set the Text property for each. Each Text value should have the same text as in the Title of the data source. For instance, if you want to set the first shape to British Airways, you have to make sure the text exactly matches the text in the Title column of the data source.

    Use the Automatically Link button on the Data tab, and choose the All Shapes on this page option. Then click Next. From the Automatically link rows to shapes window, choose Title from the Data Column and select Shape Text from the Shape field. Leave the default option of Replace existing links and click Next. View the final summary window, and click the Finish button. Data source rows are now automatically linked to shapes.

    After performing these steps, you’d see that star ratings and frown icons Styles are set for all the other shapes according to the data, as shown in Figure 2-34.

    9781430258933_Fig02-34.jpg

    Figure 2-34. Completed Visio diagram with data graphics set

  24. Now that your Visio diagram is ready, publish it to your SharePoint environment.
  25. From the File menu, select Save As. Choose the Save to SharePoint option, and browse to the Visio Library document library created earlier. Select the Visio Drawing File Type, and click the Save button to save the file as Airport.vsdx, overwriting the existing file.

    image Tip  You can decide to not overwrite the file it by choosing another file name, such as Airport_with_data.vsdx.

  26. Access your SharePoint site, and open the Visio Library document library.
  27. Click on Add document, browse to and choose the .vsdx file, and click OK.
  28. Click on the .vsdx document, and notice that the Visio diagram opens in a full browser window with the diagram and shapes connected to the SharePoint list data.

    image Note  You will see a Refresh Disabled warning the first time you open a diagram driven with data. (See Figure 2-35.) Click on Allow Refresh to refresh the data. By default, Visio Web Access disables data refresh unless you explicitly choose to allow it.

    9781430258933_Fig02-35.jpg

    Figure 2-35. Refresh status prompt for a Visio drawing

  29. Return to the Airport Flight Stats custom list, and edit the Lufthansa item. Change the Arrival delays value to 14 and Missing baggage count to 15 and click on Save.
  30. Return to the Visio Library document library, and click on the airport.vsdx drawing file. Notice that the Lufthansa flight data graphic styles have changed based on the new values.

    image Note  To get real-time values, you’ll want to set the Minimum Cache Age and Maximum Cache Age Value to zero. You’ll find these under Global Settings for Visio Graphics Service on the Central Administration screen (explained later in this chapter).

    You’ve already seen how to view Visio diagrams in the SharePoint environment by clicking on the .vsdx file in the document library; this opens the diagram in full-screen mode in the browser. Well, this might not be what you want in every situation. You might want to display diagrams on a page with other web parts, or you might be connecting to information with other web parts. For such cases, you can use the Visio Web Access web part.

Using the Visio Web Access Web Part

To have this functionality, be sure to activate the SharePoint Server Enterprise Site Collection Feature feature. You can access the Visio Web Access (VWA) web part, which is available out of the box, under the Business Data Category. To add this web part on a page, edit the page by clicking on Edit icon. Click the Insert tab on the ribbon, and select Web Part. Select Business Data folder and then Visio Web Access web part. Now click Add to add the Web Access web part to the page. The VWA web part seeks the .vsdx/.vdw file path to display the drawings. Use the Click here to open the tool pane link, and choose the .vsdx file from your Visio Library as shown in Figure 2-36. Then click Insert.

9781430258933_Fig02-36.jpg

Figure 2-36. Choosing a Visio drawing file for the Visio Web Access web part

On the tool pane, leave all the defaults as they are, and click the OK button at the bottom. The .vsdx file is now loaded, and you can view the diagram with data as in Figure 2-37.

9781430258933_Fig02-37.jpg

Figure 2-37. Visio web drawing file loaded using the Visio Web Access web part

The Visio Web Access web part header includes a number of options:

  • Open in Visio: Opens the file in either Read-Only or Edit mode, assuming you have the Visio client installed on your machine.
  • Refresh: Refreshes the data on the current page of the diagram. You can have more than one page in a diagram.
  • Shape Info: Displays a Shape Information pane (movable on the diagram) that provides Shape Data and any hyperlinks on the shape.
  • Choose Page: Displays any page from the web drawing.
  • Zoom in/out: Zooms the image from 10 to 200 percent.
  • Zoom to fit page to view: Fits the diagram to the web part height and width.

image Note  You can move the image in any direction by clicking and holding the left mouse button. You can use the scroll button on your mouse to zoom the diagram in or out.

Visio Web Access Web Part Connections

Visio Web Access web parts support two-way communications, providing rich interaction with other web parts on the page. They can act as both consumer and provider. Web part connections can be directly configured in the browser.

image Tip  After configuring the connections, if you use the view source option of the browser to view the page, you’ll notice that these web part connections are built using JavaScript.

There are many scenarios in which these connections can be helpful. You have already seen how to use a VWA web part that can load a .vwd file and connect to a SharePoint list. Let’s use the same SharePoint list and try to filter the information and reveal the shape that results from the filter criteria:

  1. Create a new site page (Airport Stats.aspx in this case), and add the VWA web part. Configure it to load the airport_with_data.vsdx drawing file or the Airport.vsdx file if you haven’t saved the file with a different name. Also, add the list app part (Airport Flight Stats) as shown in Figure 2-38.

    9781430258933_Fig02-38.jpg

    Figure 2-38. Adding the drawing file (using a VWA web part) and custom list to the page

  2. From the VWA web part menu, click on the Edit Web Part link. Once again from the VWA web part menu, choose Connections image Get Filter Results From image Airport Flight Stats, as shown in Figure 2-39.

    9781430258933_Fig02-39.jpg

    Figure 2-39. Visio Web Access web part connections

  3. Click on Apply or OK on the editor pane.
  4. Now apply the filter on the Airport Flight Stats list for the Number of cancelled flights column and choose 15.
  5. As soon as the filter is applied, notice that the shape with the corresponding value is selected, as Figure 2-40 shows.

    9781430258933_Fig02-40.jpg

    Figure 2-40. Visio Web Access web part connections with filtered data

image Tip  You can use web part connections with any list to obtain filtered data results on the drawing, assuming there is information to filter. If there’s no filtered information, you will not see any results.

Here are the various connection options:

  • Send Shape Data To (provider): Sends shape data to any other web part on the page.
  • Get Web Drawing URL and Page Name From (consumer): Gets the diagram URL from another web part on the page to render.
  • Get Shapes to Highlight From (consumer): Gets the shape name from another web part to highlight the corresponding shape.
  • Get Filter Results From (consumer): Gets shape data values from another web part to highlight the shapes based on the values provided.
  • Get Shape to View: Gets and zooms to the shape provided.

image Note  If you need to configure advanced options, you might have to use SharePoint Designer. You can extend and build custom interfaces to address connections to other web parts on the page using the IWebPartParameters interface. For more details, visit msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webparts.iwebpartparameters.aspx.

So far you’ve seen publishing Visio drawings either with data (using a SharePoint list) or without data. Now let’s see how to connect using SQL Server as a data source, publish the diagrams to SharePoint, and configure security options.

Using a SQL Server Data Source

Now that you’ve seen how to establish a data connection with a SharePoint list, let’s try to connect a Visio diagram to a SQL Server table. First, of course, you’ll need to create a database table and then populate the table with some data.

PROBLEM CASE

Display Washington, D.C. mall monuments with the number of visitors in a year and the landmarks’ popularity ratings. Publish this diagram to SharePoint, and use Visio Services to display real-time data.

Solution

  1. Create a new database named VisioServices.
  2. Create a table named tblLandmarks in the new database, and create the columns shown in Figure 2-41. Populate the columns with data as shown in Figure 2-42.

    9781430258933_Fig02-41.jpg

    Figure 2-41. Design a custom SQL table structure

    9781430258933_Fig02-42.jpg

    Figure 2-42. Populating the custom table with sample data

  3. Open Visio 2013, and create a new diagram. From More Shapes image Maps and Floor Plans image Map, choose Landmark Shapes (US Units) and add some of the available shapes to the page. Provide Titles for all the shapes either by using the Shape Data window or the shape’s label. When you create each label, make sure it matches the values in the Landmark column in Figure 2-42.
  4. Use Link Data to Shapes, choose the Microsoft SQL Server database option, and then click Next.
  5. In the Data Connection wizard, enter the Server name and the Log-on credentials, either Windows Authentication or User Name and Password. Click Next to continue.

    image Note  While communicating with SQL Server through Visio Services, you’ll need to configure an additional setting. If you’re using SQL Server with Windows Authentication, you’d connect using the following:

    Kerberos/Integrated Windows Authentication. This setting uses the current logged-in user account, which requires ­Kerberos delegation to authenticate to the database server. For more information on Kerberos, see http://technet.microsoft.com/en-us/magazine/ee914605.aspx.

    Secure Store Service (SSS). This setting uses either an individual user or group that’s mapped for authentication while using an office data connection file (*.ODC). SSS is explained in more detail later in this chapter.

    Unattended Service Account. This is a low-privilege Windows account mapped to a target application that is impersonated while connecting to the database. (This is also what you’d use with SQL Authentication.) We will be using this model with SSS while connecting to SQL Server as a data source.

  6. From the available databases, choose VisioServices and select the tblLandmarks table. Click Next to continue.
  7. The next step gives you the option to save the data connection file (.odc) as a physical file. Click on Browse to choose where to save the .odc   6 file (or skip this step by clicking on Finish). Provide a friendly name for the file, and click Finish to complete the wizard.

    image Note  To create a data-refreshable web drawing, you have to save the .odc file to the same SharePoint site location as the data connection library.

  8. On the Data Selector screen, choose the columns and rows to include and click Next to continue. After a successful import message, click on Finish.
  9. The External Data window will now load and display the data from the selected database table.
  10. Make sure that the text in the Landmark column is identical to the Title of the shapes. Drag row data from the External Data window to the shape on the page. If the column text is identical to the shape text, the link will be created successfully and you can then create the data graphics for the shape.
  11. Create the Data Graphics as explained earlier, and choose the Ratings data field. Deselect Use default position, and set the custom position for the Data Bar Style as horizontally Center and vertically Above Shape.
  12. Add the Visitors data field, and choose the Thermometer Data Bar style. Position it Far Right horizontally and Middle vertically. Click OK to close the Data Graphics wizard.
  13. Use the Automatically Link all shapes option to connect all the rows of data to the respective shapes. Choose the data column Landmark to match the shape field Shape Text, and click on Finish button.
  14. Now use the Insert Legend option to insert legend and rename the page as DC Landmarks.
  15. The web drawing should now look like the one in Figure 2-43.

    9781430258933_Fig02-43.jpg

    Figure 2-43. Visio drawing shapes connected to a SQL Server database table

    image Tip  I created the diagram in Figure 2-43 on a blank stencil using images and shapes from Landmark Shapes (US units).

  16. If the data changes and you want to make sure the drawing reflects the updates, choose either Refresh All or Refresh Data on the Data tab.
  17. Choosing either of these options opens the Refresh Data window (Figure 2-44), which displays all data sources related to this diagram. You can refresh one data source or all of them together. To configure a data source, just select it and choose Configure. Close the window when you’re finished.

    9781430258933_Fig02-44.jpg

    Figure 2-44. The Refresh Data window

  18. Now that you finished the diagram, publish it to the SharePoint environment. Choose File image Save As image SharePoint image Browse (select sharepoint document library) image Visio Drawing to save the file to SharePoint as Mall.vsdx.
  19. Alternatively, you can save the Mall.vsdx file locally, open the SharePoint site, and upload Mall.vsdx to the Visio Library.
  20. Click on the Visio drawing you uploaded, and view the drawing that is rendered in the browser.
  21. If SQL Server is on the same machine, the drawing will render correctly. However, if you are accessing SQL Server from a different machine or if you are on a domain controller, you’ll see the error shown in Figure 2-45.

    9781430258933_Fig02-45.jpg

    Figure 2-45. Error refreshing the data connection in the Web drawing

    If you encounter this error, it’s because of a scenario well-known as the double-hop issue.

THE DOUBLE-HOP ISSUE

Although you can use impersonated credentials locally, Windows won’t forward impersonated credentials to a remote resource (the second hop). So the user’s identity is lost even before he reaches the back end. And in this scenario, SharePoint can’t pass the credentials of the logged-in user all the way to the back end via the services. This scenario is known as The Double-Hop problem.

To solve the problem, a mechanism is needed by which the logged-in user can be impersonated “as someone else” to use Visio services and connect to the back-end data. You can achieve this by using the Secure Store Services (SSS) in SharePoint.

Secure Store Services

You can consider Secure Store Services (introduced in SharePoint 2010) the next generation of the single sign-on service in MOSS 2007. SSS is a credential store that saves account information securely in the database.

You can create and set these credentials on a per-application basis associated with an Application Id and use this Application Id for different services that are subject to the double-hop issue. You can consider SSS as a gatekeeper service for authenticating a user (or a group) against an application. You can also set ID for each target application at the farm level.

Configuring Secure Store Services

Let’s start by configuring Secure Store Services:

  • 1.  Make sure you are a Farm Administrator, and log on to the Central Administration site.
  • 2.  Click on Application Management, and choose Manage Service Applications from the Service Applications group (Figure 2-46).

    9781430258933_Fig02-46.jpg

    Figure 2-46. Choose “Manage service applications” on the Central Administration site

  • 3.  From the list of available services, click on Secure Store Service (Figure 2-47).

    9781430258933_Fig02-47.jpg

    Figure 2-47. Choose Secure Store Service

  • 4.  On the Secure Store Service page, set the following options:
  • Generate New Key: Before beginning to create a new target application, you need to generate a new key from a pass phrase (Figure 2-48). This key is used to encrypt and decrypt credentials that are stored in the database. You must have Administrator rights to create a key.

    9781430258933_Fig02-48.jpg

    Figure 2-48. The Generate New Key dialog

  • Refresh Key: To refresh a key (Figure 2-49), you again need Administrator rights, as well as the pass phrase you set when you created the key.

    9781430258933_Fig02-49.jpg

    Figure 2-49. Enter the pass phrase to refresh a key

    image Note  Refreshing a key will be necessary if you add a new application server to the existing server farm, if you restore a secure store service database, or if you receive errors such as “Unable to get master key.”

    image Caution  Secure Store Services has its own database. Whenever you create a new key or refresh an existing key, be sure to back up the database.

  • 5.  After you have successfully created the new key, click the New button under Manage Target Applications on the Edit tab of the ribbon and provide the following information in the Target Application Settings window:
  • Target Application ID: A unique identifier that will be used in service applications as the unattended service account reference for authentication. You can’t change the Target Application ID once it is created.
  • Display Name: A name used for display only.
  • Contact E-mail: The primary e-mail for this Application ID.
  • Target Application Type: Specify Individual for individual users and Group for group credentials.
  • Target Application Page URL: Selecting Use default page will result in the sign-up page http://yoursite/_layouts/SecureStoreSetCredentials.aspx?TargetAppId=<applicationId > being used; this option is available only when you select the Individual Target Application Type. If you select Use custom page, you need to create a page first and provide its URL. This page is used to authenticate users. Choose None if you don’t want a sign-up page.
  • 6.  Enter VisioServices for the Target Application ID; SSS for Visio Services for the Display Name; <YourValidEmailAddress> for the Contact E-mail; Individual for the Target Application Type; and Use default page for the Target Application Page URL. (See Figure 2-50.) Click Next.

    9781430258933_Fig02-50.jpg

    Figure 2-50. Configuring target application settings for SSS

  • 7.  In the Add Field window (Figure 2-51), leave the defaults as they are and click on Next to continue.

    9781430258933_Fig02-51.jpg

    Figure 2-51. Secure Store Service fields

  • 8.  Add administrator users who need to have access to this Application ID on the Target Application Administrators, and click OK.
  • 9.  Return to the Secure Store Services window, and choose the Target Application ID created in the previous step. Click the Set button on the Credentials tab of the Edit tab, as shown in Figure 2-52.

    9781430258933_Fig02-52.jpg

    Figure 2-52. Set Secure Store Service Application ID credentials

  • 10.  On the Set Credentials for Secure Store Target Application screen (Figure 2-53), enter  values for Credential Owner, Windows User Name, and Windows Password (and Confirm Windows Password), and click OK. Credential owners are the members (individuals or group) of the target application that will impersonate credentials when accessing external data.

    9781430258933_Fig02-53.jpg

    Figure 2-53. Setting credentials for the target application

image Note  Because you will be using SSS for your Visio diagram to connect to the SQL Server instance, you need to enter the user credentials of those who have permissions to the VisioServices database from where you will load data. It must be credential for low-privilege users, not an administrator.

The previous step creates a new SSS Application ID that can be used to connect to SQL Server from service applications that require additional authentication to retrieve data.

Using Visio with SQL Server and SSS

Now let’s configure Visio Services to use the new Application ID:

  1. Go to Central Administration image Application Management image Service Applications image Manage Service Applications, and choose Visio Graphics Service.
  2. Click on the Global Settings in the External Data section, and enter VisioServices under Application ID (Figure 2-54). Click OK.

    9781430258933_Fig02-54.jpg

    Figure 2-54. Set the External Data Unattended Service Account Applicaion ID

    image Note  Application IDs are set for each service application, such as Visio Graphics Service. You can also have two Visio Graphics Service applications set for one Web application: one default and the other a Custom Visio Graphics Service application. For that, create a new Application ID with different credentials and set them to a new Custom Service Application. You can then add the new custom service application to the web application Service Connections.

    This sets the authorization proxy for the Visio Graphics Services to connect to the SQL Server database and retrieve data without losing the user context.

    image Note  Other settings on Visio Graphics Services under Global Settings include the following:

    Maximum Web Drawing Size: This is the size of web drawing file that can be set, between 1 and 50 MBs. The bigger the file size, the slower the rendering and performance.

    Minimum Cache Age: This is the minimum duration in minutes each drawing is cached in memory. Set the value to zero if you need real-time data. However, setting this value to zero or too low puts a load on CPU and memory usage. The allowable range is 0 to 34560. This parameter is valid only for data-driven web drawings.

    Maximum Cache Age: This is the value in minutes after which the cached drawings are removed from memory. You need to set this to zero (in addition to setting the Minimum Cache Age value to zero) to get real-time data. Setting this value too high increases memory consumption, but it decreases file I/O and load on the CPU. This parameter is valid only for static web drawings.

    Maximum Recalc Duration: This is the value in seconds of the period before an operation times out before a data refresh. The allowable range is between 10 and 120.

  3. Open your SharePoint site, and click on Mall.vsdx in the Visio Library document library to open the Visio diagram in full-screen mode.
  4. Because you have set the SSS, data should display accurately from the database, with the data graphics populating the correct information on the shapes.
  5. On SQL Server, go to the tblLandmarks table and change the data in the rows.
  6. Return to the SharePoint site, and refresh the Visio diagram to view the real-time changes in the diagram for the shapes, as shown in Figure 2-55.

9781430258933_Fig02-55.jpg

Figure 2-55. Visio drawing connected to a SQL Server data source and published to SharePoint

You can also interact with these Visio diagrams and shapes. For example, suppose you want to get more information by clicking on a shape or to pass the information from a shape to another web part. You can achieve these scenarios by using the JavaScript API with Visio Services.

Visio Services JavaScript Mashup API

The Visio Services JavaScript Mashup API provides great functionality for accessing or manipulating the shapes of published diagrams. Using the API, you can alter data, shapes, and pages to make the diagrams more interactive. There are many operations you can perform on the drawings, some of which are discussed here:

  • At the Control level, you can retrieve the version, display mode (Silverlight or Image), active page, and events such as shape selection changed, diagram render complete, etc.
  • At the Page level, you can get the available shapes, selected shape, shape, position, and other details.
  • At the Shape Collection level, you can get the count, items, and metadata, etc.
  • At the Shape level, you can get the shape data and hyperlink and set highlighting to the shape, overlays, etc.

The Visio Services JavaScript Mashup API lets you create a rich user interface that combines shapes, data, and events.

The API consists of a hierarchy of classes, methods, and events as shown in Figure 2-56. To obtain the reference of the Visio Web Access web part on a page you need to get the corresponding object, which can be accessed via the Vwa.VwaControl object. The next level would be the Page object.

9781430258933_Fig02-56.jpg

Figure 2-56. Visio Services JavaScript Mashup API

image Note  It is very important to understand that the Page object in this context is the active web drawing page that is inside the VWA web part—not the .aspx page.

On the page, you can have one or more shapes that can be retrieved using the ShapeCollection object. And, finally, you can access the individual shape from the shape collection and its properties.

To use the JavaScript Mashup API and understand it more clearly, let’s begin with a simple exercise.

PROBLEM CASE

Using the previously created Mall.vsdx, display the details of each monument by clicking the shape.

Solution

  1. Create a new page under the site pages, and name it Mall.aspx.
  2. Insert a Visio Web Access web part, from the Business Data Categories, on the page.
  3. After you add the web part, make sure the page is in edit mode and click the link that says Click here to open the tool pane.
  4. From the Visio Web Access configuration window, choose Mall.vsdx from the Visio Library document library and click OK.
  5. Click OK on the configuration window.
  6. Save and close the page to view the Visio diagram rendered on the web page.
  7. Right-click on the browser, click View Source on the context menu, and search for the text class=“VisioWebAccess.”
  8. Find the corresponding id of the td that you should find just above the div. Usually, it will be WebPartWPQ2 on a freshly created site page.
  9. Open Notepad, and paste the code in Listing 2-1 into it. Save this as the file assets.js.

    Listing 2-1.  Listing 2-1. Assets.js

    <script language="javascript">
    var _application = Sys.Application;
    var _visioWebPart;
    var onShapeSelectionChanged = null;
    _application.add_load(onApplicationLoad);
    function onApplicationLoad()
    {
        // Change the control id based on the code on your page
        _visioWebPart= new Vwa.VwaControl("WebPartWPQ2");
        _visioWebPart.addHandler("diagramcomplete", onDiagramComplete);
        _visioWebPart.addHandler("shapeselectionchanged", onShapeSelectionChanged);
    }
    function onDiagramComplete()
    {
        var _page = _visioWebPart.getActivePage();
        _page.setZoom(85);
    }
    onShapeSelectionChanged = function(source, args)
    {
        var _activePage = _visioWebPart.getActivePage();
        var _shape = _activePage.getShapes();
        var _shapeItem = _shape.getItemById(args);
        var _shapeData = _shapeItem.getShapeData();
        var _description = "";
         
        for (var j = 0; j < _shapeData.length; j++)
        {
            if (_shapeData[j].label == "Details")
            {
                _description = _shapeData[j].value;
                continue;
            }
        }
        document.getElementById('landmarkDetails').firstChild.data = _description;
    }
    </SCRIPT>
    <div id="landmarkDetails" style="font-family: Verdana; font-style: bold; font-size:14pt; color:red;">landmark details...</div>
  10. Upload the assets.js file into the Visio Library document library.
  11. Right-click on assets.js, and by using the Copy Shortcut menu, copy the URL to the clipboard.
  12. Open the Mall.aspx site page in edit mode, and add the Content Editor Web part from the Media and Content category as shown in Figure 2-57.

    9781430258933_Fig02-57.jpg

    Figure 2-57. Adding the Content Editor web part to the page

  13. Edit the Content Editor web part, and paste the link to assets.js in the Content Link text box.
  14. Verify the link by clicking on Test link URL below the text box. If the URL is accurate, the assets.js file will be downloaded to your disk.
  15. Click Apply and OK on the editor part pane to return the page to normal mode.
  16. Save and close the page.
  17. You should now see that the Content Editor web part displays the text “landmark details…” in red, as shown in Figure 2-58.

    9781430258933_Fig02-58.jpg

    Figure 2-58. The Content Editor web part with the Visio Web Access web part

  18. Click on any shape—for instance, on the White House—and see that the text on the Content Editor web part changes to the White House details, as shown in Figure 2-59. Try clicking on other shapes. Notice that the text changes on the Content Editor web part instantly without a page refresh.

    9781430258933_Fig02-59.jpg

    Figure 2-59. Interacting with the VWA web part and the drawing using the JavaScript Mashup API

Now that you have successfully created a simple JavaScript mashup with a Visio diagram, try to understand the code. One of the major reasons JavaScript was chosen to build the API is because of its simplicity.

Understanding the assets.js Code

First you need to get to the application object and create the event handler for the application load:

_application.add_load(onApplicationLoad);

Once the application loads, you get the instance of the Visio web access from the page and add two more event handlers: one when the diagram completes loading, and the other when the shape selection is changed. In the life cycle of these events, the onDiagramComplete event fires first, and onShapeSelectionChanged is the last event.

_visioWebPart= new Vwa.VwaControl("WebPartWPQ2");
_visioWebPart.addHandler("diagramcomplete", onDiagramComplete);
_visioWebPart.addHandler("shapeselectionchanged", onShapeSelectionChanged);

After the diagram loads, all the objects are available and the diagram is rendered to the browser. This means that the diagram is completely available on the page and you can get to the page-level properties and methods. For example, you can set the diagram’s current page zoom value percentage:

var _page = _visioWebPart.getActivePage();
_page.setZoom(85);

Alright, once any shape is selected or changed on the active page, you need the corresponding shape and the shape data. You need to get to Shape Data to get the column values. Use the method getItemById() that’s submitted through the event arguments:

var _activePage = _visioWebPart.getActivePage();
var _shape = _activePage.getShapes();
var _shapeItem = _shape.getItemById(args);
var _shapeData = _shapeItem.getShapeData();
var _description = "";
for (var j = 0; j < _shapeData.length; j++)
    {
     if (_shapeData[j].label == "Details"){
            _description = _shapeData[j].value;
            continue;
        }
    }

Finally, you get the description and assign it to the div text, like so:

document.getElementById('landmarkDetails').firstChild.data = _description;

Now, suppose your business analyst wants to create a simple workflow using a Visio diagram? Is there a way to connect this diagram to one of the available workflows easily? The answer is yes, and as you’ll see in the next section, you can use a Visio diagram to create a workflow and, by using SharePoint Designer, you can enable the workflow and deploy (attach) it to a list.

Working with SharePoint Designer 2013

This scenario can be achieved using Visio 2013 diagrams with SharePoint Designer 2013, which also allows importing and exporting Visio diagrams, attaching workflows to them, and then publishing to a SharePoint environment.

PROBLEM CASE

One of the leading fast-food chains (let’s call it  “Tasty Foods”) wants to collect feedback from its customers on various food items. The feedback form must be filled out by the customer using an online web application. Customers must enter their full name, food item, and e-mail address, and they must leave comments. If the customer doesn’t enter a comment, the workflow status will be rejected; if she does, the status will be approved.

There are three major components that will be used in this case:

  • A SharePoint list, used as the feedback form (responsibility of the developer).
  • A Visio diagram to create the workflow design (responsibility of the business analyst).
  • SharePoint Designer to enable the workflow and deploy (attach) it to the list (responsibility of the developer).

Solution

  1. Create a custom list, add a few columns as shown in Figure 2-60, and save it as Tasty Foods Feedback.

    9781430258933_Fig02-60.jpg

    Figure 2-60. The Tasty Foods custom list

    The Fooditem Choice column can contain items such as sandwiches, chicken, breakfast, salads, snacks and sides, beverages, coffee, desserts, shakes, etc.

  2. Open Visio 2013, and create a new Visio diagram using Microsoft SharePoint 2013 Workflow (US units). You’ll find this in the Flowchart section.
  3. Create a simple workflow as shown in Figure 2-61, using shapes that compare two values, send e-mail, and set the workflow status.

    9781430258933_Fig02-61.jpg

    Figure 2-61. Simple workflow designed in Visio using SharePoint templates

    image Note  A new SharePoint 2013 workflow starts with an empty container called Stage, instead of a blank canvas (as was the case with SharePoint 2010). A stage acts as a container for logically related sections of the workflow. Stages allow simplification of complex workflows. Simple workflows, like the one in our example, are generally single-stage workflows.

  4. From the File menu, save the diagram (as a .vsdx file) to your local file system.
  5. Close Visio, and open the SharePoint Designer 2013 client.
  6. Open the SharePoint site where you created the Tasty Foods Feedback custom list, as shown in Figure 2-62.

    9781430258933_Fig02-62.jpg

    Figure 2-62. Site containing Tasty Foods Feedback list opened in SharePoint Designer 2013

  7. From the menu, click on File and select Import Visio 2013 Workflow, as shown in Figure 2-63.

    9781430258933_Fig02-63.jpg

    Figure 2-63. Importing a Visio 2013 workflow in SharePoint Designer

  8. Provide a name for the workflow, and select Tasty Foods Feedback as the SharePoint list to which the workflow is to be associated, as shown in Figure 2-64.

    9781430258933_Fig02-64.jpg

    Figure 2-64. Specifying the workflow name and SharePoint list association

  9. This opens the workflow in Visual Designer view. From the Views menu on the Workflow tab on the ribbon, select Text-Based Designer to switch to text based designer mode, as shown in the Figure 2-65.

    9781430258933_Fig02-65.jpg

    Figure 2-65. Visio workflow imported in the SharePoint Designer workflow editor

  10. As you can see in Figure 2-65, two conditions are automatically created under the editor because there are two flows when comparing the data. (Refer to Figure 2-61.) This includes the send an email process step, set the workflow status, and the end the process step for both flows.
  11. Modify each of the conditions to meet the requirements. For instance, under the If condition (Figure 2-65), set the value to look up from the custom list datasource and choose the field (Comments) for looking up the value. Change the equals operator to is empty.
  12. If this condition is true, set the Email “these users” to Current Item:Email Address. Configure Subject and message, and then Set workflow status to Rejected from the look-up values.
  13. Under the “Else” condition, set Email “these users” to Current Item:Email Address. Configure Subject and message, and then Set workflow to Approved.
  14. Finally, set the Title of the Stage as “Tasty Foods Feedback Workflow” as shown in Figure 2-66.

    9781430258933_Fig02-66.jpg

    Figure 2-66. Setting up the workflow conditions in SharePoint Designer

  15. From the Workflow tab on the ribbon, select Workflow Settings. From the Start Options, you can choose to start the workflow automatically either when the item is created or when it is changed. (See Figure 2-67.)

    9781430258933_Fig02-67.jpg

    Figure 2-67. Setting workflow start-up options in SharePoint Designer

  16. From the Workflow tab on the ribbon, click the Check for Errors button and then save the workflow (Figure 2-68).

    9781430258933_Fig02-68.jpg

    Figure 2-68. Save and Publish the workflow to the SharePoint list

  17. Publish this workflow to the list using the Publish button on the Workflow tab.

    These steps will validate and publish the workflow to the corresponding list.

  18. Open the SharePoint site and the Tasty Foods Feedback list.
  19. Go to List image List Settings, and click on the Workflow Settings in the Permissions and Management section. You can also access the Workflow settings from List image Workflow Settings (Settings section on the ribbon) image Workflow Settings (from the drop down).

    Locate the Workflow you just submitted. If the workflow is published more than once, a new version is created.

  20. Return to the list, and click new item, which brings up the New Item screen as shown in Figure 2-69.

    9781430258933_Fig02-69.jpg

    Figure 2-69. Adding a new item to the feedback form

  21. Create two items: one with comments and one without comments. Because the workflow hasn’t been set to start automatically, you’ll have to start it manually after any item is created. Choose the item on which you’d like to run the Workflow, and click the Workflows button on the Items tab, as shown in Figure 2-70.

    9781430258933_Fig02-70.jpg

    Figure 2-70. Starting a workflow for the list item

  22. This opens the Start a New Workflow window, displaying the available workflows, as Figure 2-71 shows.

    9781430258933_Fig02-71.jpg

    Figure 2-71. Starting a new workflow

  23. Click on the Tasty Foods Feedback Workflow link. This will execute the rules underlying the workflow and apply any changes to the respective columns.
  24. Notice that under the Tasty Foods Feedback column (Figure 2-72), the status is set based the on the comments provided by customer. The status is Approved when the customer fills in the Comments field and Rejected when the customer doesn’t add any comments.

    9781430258933_Fig02-72.jpg

    Figure 2-72. Workflow status after items are added

In some instances, the requirement might not be as simple as just connecting to an Excel file or SharePoint list or even using a SQL Server database. A more interesting scenario would be consuming data from a web service or from a different data source that Visio Services doesn’t support natively. In such cases, you would have to write a custom data provider.

Creating Your Own Custom Data Providers

The Visio Services API provides features to build custom data modules or custom data providers. Using the API, you can create custom data sources and refresh the data on the Visio diagrams that are deployed to a SharePoint site.

Let’s take a look now at how to support non-natively supported data sources by designing a custom data provider.

PROBLEM CASE

Display the status of the test environment servers whether they are online or offline. Note that current status information is in a SQL Server database and can be retrieved using Windows Communication Foundation (WCF) services. You will need to get the data and connect to the shapes.

Solution

The major components in this scenario are SQL Server, WCF Service, Visio, and Security:

  • We’ll begin with a SQL Server database and then write a WCF Service to retrieve data from the database table.
  • We’ll write a custom data provider and configure its settings in the Central Administration site of the SharePoint environment.
  • We’ll write a VBA script to create the data source and connect the data source to the shapes in the Visio diagram.
  • We’ll deploy the .vdw file to a SharePoint environment and view the output.

Retrieving server status information stored in a database table

  1. Create a table named tblServerStatus with columns as shown in Figure 2-73 in the VisioServices database you created earlier.

    9781430258933_Fig02-73.jpg

    Figure 2-73. Server Status Table in SQL Server

  2. Populate a few rows of this table with information as shown in Figure 2-74.

    9781430258933_Fig02-74.jpg

    Figure 2-74. Populating rows with data for the server status table in SQL Server

  3. Create a stored procedure named uspGetServerDetails that will execute the SQL query to retrieve the values from the table in Figure 2-74. Listing 2-2 shows the code.

    Listing 2-2.  The uspGetServerDetails Stored Procedure

    USE [VisioServices]
    GO
    CREATE PROCEDURE [dbo].[uspGetServerDetails]
    AS
    BEGIN
           -- SET NOCOUNT ON added to prevent extra result sets from
           -- interfering with SELECT statements.
           SET NOCOUNT ON;
           -- Insert statements for procedure here
           SELECT ServerName, ServerIP, ServerStatus from tblServerStatus
    END

    image Note  The stored procedure code is explained toward the end of this chapter in the section “Understanding the Custom Data Provider Code.”

    Writing the WCF Service library and Hosting it in IIS

  4. Open Microsoft Visual Studio 2012, choose to create a new project, and from the available templates select Visual C# image WCF image WCF Service Application. Then provide a proper Name and Location. Make sure you pick .NET Framework 4.5. This creates a service class (Service1.svc) and an interface (IService1.cs).
  5. Rename the default Service1.svc file and the interface class to ServerStatus.svc and IServerStatus.cs, respectively. Ensure that all the references under the project reflect this name change.
  6. After completing these steps, your project should look like the one in Figure 2-75.

    9781430258933_Fig02-75.jpg

    Figure 2-75. Setting up a WCF service application project in Visual Studio 2012

  7. Open the Web.config file, and add an entry under the connectionStrings section (connection string to the VisioServices SQL server database) as follows:
    <connectionStrings>
        <add name="VisioServicesConnectionString" connectionString="Data Source=ServerName;
    Initial Catalog=VisioServices;Integrated Security=SSPI;User Id=userId;Password=pwd"
    providerName="System.Data.SqlClient"/>

      </connectionStrings>

    image Note  The code in Listing 2-3 is explained toward the end of this chapter in the section “Understanding the Custom Data Provider Code.”

  8. Open the ServerStatus.svc.cs file, and paste the code from Listing 2-3 in it.

    Listing 2-3.  WCF Service Library Class to Retrieve Server Status

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.Data;
    using System.Data.Sql;
    using System.Data.SqlClient;
    using System.Configuration;
    namespace WcfDataProvider
    {

        public class ServerStatus : IServerStatus
        {
            [OperationBehavior]
            public DataTable GetServerStatusDetails()
            {
                DataSet dataSet = new DataSet();
                SqlConnection connection = new SqlConnection
    (ConfigurationManager.ConnectionStrings["VisioServicesConnectionString"].ConnectionString);

                SqlCommand command = new SqlCommand("uspGetServerDetails", connection);
                command.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter dataAdapter = new SqlDataAdapter(command);

                dataAdapter.Fill(dataSet);
                connection.Close();
                return dataSet.Tables[0];
            }
        }
    }

    image Note  It is a good practice to add a Test Project for any projects you create because this would perform the first level of unit testing for your projects.

  9. Now copy the code in Listing 2-4, open the IServerStatus.cs file, and paste the code in it.

    Listing 2-4.  WCF Service Library Interface Class

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.Data;
    namespace WcfDataProvider
    {
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the
        // interface name "IServerStatus" in both the code and config file together.
        [ServiceContract]
        public interface IServerStatus
        {
            [OperationContract]
            DataTable GetServerStatusDetails();
        }
    }
  10. Build the WCF project in release mode, and make sure you have no errors.
  11. Create a local folder in your file system under C:, and name it wcfServicehost.
  12. Make a folder called bin.
  13. Copy the WcfDataProvider.dll file to the bin folder.
  14. Make sure Network Service and IIS_IUSRS users have Read & Execute permissions on the root folder.
  15. Create a file named VisioWcfServices.svc under the wcfServicehost folder, and add the following text:
    <% @ServiceHost Service="WcfDataProvider.ServerStatus" %>
  16. Create a Web.config file in the same folder, and copy the code from Listing 2-5 to it.

    Listing 2-5.  WCF Data Provider Web.config File Settings

    <?xml version="1.0" encoding="utf-8"?>
      <configuration>
        <system.serviceModel>
          <services>
            <service behaviorConfiguration="WcfDataProvider.ServerStatusBehavior"
                           name="WcfDataProvider.ServerStatus">
              <endpoint address="" binding="basicHttpBinding"
                           contract="WcfDataProvider.IServerStatus" />

              <host>
                <baseAddresses>
                  <add baseAddress=" http://localhost:<portnumber>/visiowcfservices.svc " />
                </baseAddresses>
              </host>
            </service>
          </services>
          <behaviors>
            <serviceBehaviors>
              <behavior name="WcfDataProvider.ServerStatusBehavior">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="false" />
               </behavior>
            </serviceBehaviors>
          </behaviors>
        </system.serviceModel>
       <connectionStrings>
          <add name="VisioServicesConnectionString" connectionString="Data Source=localhost;Initial Catalog=VisioServices;Integrated Security=SSPI;User Id=uid;Password=pwd"
    providerName="System.Data.SqlClient"/>

        </connectionStrings>
      </configuration>

    After completing the preceding steps, your folder structure and files should look similar to those in Figure 2-76.

    9781430258933_Fig02-76.jpg

    Figure 2-76. WCF service host folder

  17. Open IIS, and create an application pool by providing a Name, .NET Framework version, and pipeline mode.
  18. Create a new web site. Choose the app pool you just created, provide a site name, and choose the local folder where you copied the .dll file as the physical path. Under binding, provide a Port number that’s not in use.
  19. Open the browser, and type the URL http://localhost:<portnumber >/ VisioWcfServices.svc; to see the output shown in Figure 2-77.

    9781430258933_Fig02-77.jpg

    Figure 2-77. Accessing the WCF service

    image Note  For more information on how to create WCF services, go to http://blah.winsmarts.com/2008-4-Host_a_WCF_Service_in_IIS_7_-and-amp;_Windows_2008_-_The_right_way.aspx.

    Creating the custom data provider project

  20. Open Microsoft Visual Studio 2012, create a new project, and from the available templates pick Visual C# image Office/SharePoint image SharePoint Solutions image SharePoint 2013 - Empty Project. Make sure you choose .NET Framework 4.5. Provide a Name, Location, and Solution Name, and click OK. Create the project name as VisioDataService.
  21. In the next screen, enter the SharePoint site URL for debugging and choose Deploy as a farm solution for the trust level. Click on Finish.
  22. Right-click on the project, select the properties, and make sure the Assembly name and default namespace fit your situation.
  23. Right-click on the project, and choose Add Service Reference.
  24. From the wizard, click Discover and make sure there’s a reference to the WCF service you built earlier. Alternatively, you can enter the WCF URL (http://localhost:<portnumber>/VisioWcfServices.svc) in the Address text box. Provide the namespace as WcfDataService and click OK.
  25. Right-click on the project, and choose Add Reference. From the Add Reference window .NET tab, choose the System.Web component and click OK.
  26. Right-click on the project again, and choose Add Reference. From the Add Reference window Browse tab, browse to the folder C:WindowsMicrosoft.NETassemblyGAC_MSILMicrosoft.Office.Visio.Serverv4.0_15.0.0.0__71e9bce111e9429c, choose the file Microsoft.Office.Visio.Server.dll, and click OK.

    At this stage, the project structure should resemble the one in Figure 2-78.

    9781430258933_Fig02-78.jpg

    Figure 2-78. WCF consumer project structure

    image Note  The code in Listing 2-6 is explained toward the end of this chapter in the section “Understanding the Custom Data Provider Code.”

  27. Add the VisioDataProviderService.cs class file to the project, and copy the code in Listing 2-6 into the file. Make sure you have the correct namespaces as per your project settings.

    Listing 2-6.  Visio Custom Data Provider Service Class Code

    using System;
    using System.Data;
    using System.Threading;
    using System.Xml;
    using System.Web;
    using Microsoft.Office.Visio.Server;
    using VisioDataService.WcfDataService;
    namespace DataModules
    {
        public class VisioDataProviderService: AddonDataHandler, IAsyncResult
        {
            private object _asyncState;
            private bool _completeStatus;
              
            WaitHandle IAsyncResult.AsyncWaitHandle
            {
                get { return null; }
            }
            object IAsyncResult.AsyncState
            {
                get { return _asyncState; }
            }
            bool IAsyncResult.IsCompleted
            {
                get { return this._completeStatus; }
            }
            bool IAsyncResult.CompletedSynchronously
            {
                get { return false; }
            }
            public override IAsyncResult BeginGetData
                                    (HttpContext httpContext, AsyncCallback callback, object asyncState)
            {
                _asyncState = asyncState;
                ThreadPool.QueueUserWorkItem(new WaitCallback(GetData), callback);
                return this;
            }
            public override DataSet EndGetData(IAsyncResult asyncResult)
            {
                return this.Data;
            }
            public override void Cancel()
            {
                // Not implemented
            }
            private void GetData(object state)
            {
                AsyncCallback asyncCallback = (AsyncCallback)state;
                try
                {
                    ServerStatusClient oServerStatus = new ServerStatusClient();
                    DataTable dt = oServerStatus.GetServerStatusDetails();
                    this.Data.Reset();
                    this.Data.Tables.Add(dt);
                    this.Data.AcceptChanges();
                }
                catch (Exception ex)
                {
                    this.Error = new AddonDataHandlerException(ex.Message);
                }
                asyncCallback(this);
                _completeStatus = true;
                  
            }
        }
    }
  28. Now build the project. Once the build is successful, right-click on the VisioDataService project, and then click on Publish and select a folder to create the WSP file in the selected folder.

    image Tip  If you are performing this step on your local development machine, try the Deploy option from the project properties.

  29. Deploy the WSP using either STSADM or Windows PowerShell commands to add the solution to your SharePoint site.
  30. Open Central Administration image Application Management image Manage Service Applications image Visio Graphics Service.
  31. Click on Trusted Data Providers and then on Add a new Trusted Data Provider.
  32. Under Trusted Data Provider ID, enter the class name and fully qualified assembly name separated by a comma (in my case, it is DataModules.VisioDataProviderService,VisioDataProviderService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=<public key token>).
  33. Under Trusted Data Provider Type, enter the value 6 (for Visio Custom Data Providers).
  34. Under Trusted Data Provider Description, enter a valid description, such as Visio Custom Data Services Provider, and click OK.
  35. Your service provider is now ready and will display in the available service provider list.
  36. Open the Web.config file that belongs to your SharePoint web application, and paste the settings in Listing 2-7 under the system.serviceModel section.

    Listing 2-7.  Service Model Section Setting Values Under the web.config File

    <bindings>
          <basicHttpBinding>
            <binding name="BasicHttpBinding_IServerStatus" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                useDefaultWebProxy="true">
              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                  maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              <security mode="None">
                <transport clientCredentialType="None" proxyCredentialType="None"
                    realm="" />
                <message clientCredentialType="UserName" algorithmSuite="Default" />
              </security>
            </binding>
          </basicHttpBinding>
        </bindings>
        <client>
          <endpoint address=" http://localhost:<portnumber>/VisioWcfServices.svc "
              binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IServerStatus"
              contract="WcfDataService.IServerStatus" name="BasicHttpBinding_IServerStatus" />
        </client>

    Designing the Visio Diagram

  37. Open Visio 2013, and create a blank diagram. Choose the Network image Servers - 3D (US units) stencil from More Shapes image Network.
  38. From the Insert tab, Add a Container block. From the diagram parts (under Servers-3d), and add three servers: Web Server, Database Server, and Application Server. Name the Container block as Test Servers, as shown in Figure 2-79.

    9781430258933_Fig02-79.jpg

    Figure 2-79. Designing a Visio diagram for test servers

    Right now, there is no data source configured. While your Visio diagram is open, press Alt+F11 to open Microsoft Visual Basic for Applications. In the Project window, double-click on ThisDocument under Visio Objects to open the code view. Paste the code in Listing 2-8 into the code area.

    Listing 2-8.  Using Visual Basic for Applications to Retreive Data from a SQL Server Data Source

    Sub LoadData()
        Dim diagramServices As Integer
        Dim vsoDataRecordset As Visio.dataRecordset
          
        Dim connectionString As String
        Dim commandText As String
         
        diagramServices = ActiveDocument.DiagramServicesEnabled
        ActiveDocument.DiagramServicesEnabled = visServiceVersion140
        Application.ActiveWindow.Windows.ItemFromID(visWinIDExternalData).Visible = True
            
        commandText = "SELECT ServerName, ServerIP, ServerStatus FROM tblServerStatus"
        connectionString = "Provider=SQLOLEDB;Data Source=<YourDataSourceName>;Initial Catalog=VisioServices;Integrated Security=SSPI;"
        Set vsoDataRecordset = ActiveDocument.DataRecordsets.Add(
                                                connectionString, commandText, 0, "Server Status Details")
        vsoDataRecordset.DataConnection.connectionString =
                       "DataModule=DataModules.VisioDataProviderService,VisioDataProviderService;"
          
        ActiveDocument.DiagramServicesEnabled = diagramServices
    End Sub

    image Note  The following code is explained toward the end of this chapter in the section “Understanding the Custom Data Provider Code.” You need to customize the connection string and the Data module assembly details in the following code.

  39. The Microsoft Visual Basic for Applications window should look like the one in Figure 2-80.

    9781430258933_Fig02-80.jpg

    Figure 2-80. Microsoft Visual Basic for Applications

  40. Press F5 or click on the Run button on the menu to execute the LoadData(  ) subroutine. Pressing Alt+F11 will toggle back to the Visio diagram. Under the External Data tab, the data will be loaded as shown in Figure 2-81.

    9781430258933_Fig02-81.jpg

    Figure 2-81. The Visio diagram loading external data using VBA code

  41. Save the file as TestServers.vdw. Macros are not supported in vsdx file format, hence we will be using vdw format for this example.
  42. Drag and drop row data to the respective shapes, or set the Text property to the shapes that match the ServerName column and use the option Automatically Link all.
  43. Set the data graphics to display ServerIP and ServerName as Text, and ServerStatus as Color by Value (Figure 2-82), such that if the value is 0 (server is down) the server shows red and if the value is 1 (server is live), it shows green.

    9781430258933_Fig02-82.jpg

    Figure 2-82. Setting up data graphics for the Visio diagram

    Your final Visio diagram should look like the one in Figure 2-83.

    9781430258933_Fig02-83.jpg

    Figure 2-83. Visio diagram after applying data and data graphics

  44. Save the Visio diagram.
  45. Open the SharePoint site, and open the Visio Library Document library. Click on Add document, browse to the saved .vdw file, and click OK.
  46. Click on the .vdw file to open the diagram in the browser to display the results from the database.
  47. Change the values in the database, and notice the server status. If the cache age values on the general settings of the Visio Graphics Service are set to zero, the values reflect instantly on the diagram (Figure 2-84).

    9781430258933_Fig02-84.jpg

    Figure 2-84. Visio diagram loaded using a custom data provider

    Make sure the following are correct to avoid the error shown in Figure 2-85:

    9781430258933_Fig02-85.jpg

    Figure 2-85. External data connection refresh error

  48. Assembly details are accurate when you add the custom data providers in the Central Administration.
  49. The WCF services are properly hosted and can communicate with the Custom Data Providers.
  50. Your configuration files (Web.config) have the right binding settings for the WCF.
  51. As discussed earlier, you might encounter the double-hop issue while connecting to data sources via WCF. If so, you might need to set the credentials under the Secure Store Service.

At first glance, the process of creating a Custom Data Provider might sound a bit complicated. However, in reality it’s just a matter of practice and getting used to the process. Summarized next are the important steps you just followed to create and consume the custom data provider:

  1. We started off by creating a simple stored procedure (uspGetServerDetails) to fetch the server status from the tblServerStatus table.
  2. Next, we created a WCF service, which invoked the aforementioned stored procedure to retrieve the server status data from the database.
  3. Then we created the custom data provider, to consume the WCF service.
  4. Finally, we designed the Visio Diagram and wrote a VBA script to create the data source and connect it to the shapes in the diagram.

The following section walks you through the code for the stored procedure (step 1 above), WCF service (step 2), Custom Data Provider class (step 3), and VBA Code (step 4).

UNDERSTANDING THE CUSTOM DATA PROVIDER CODE

uspGetServerDetails Stored Procedure (Listing 2-2)

This stored procedure contains a simple T-SQL statement that retrieves all rows of data from the table tblServerStatus.

SELECT ServerName, ServerIP, ServerStatus from tblServerStatus

WCF Service Library (and Interface) Class (Listings 2-3 and 2-4)

Consider this a data –access-layer class that calls the uspGetServerDetails stored procedure and returns the output as a data table.

When the WCF application project is created, a service class and corresponding interface template are added to the project. Declare the Service Contract and Operation Contract (as shown next) interface classes that will be implemented in your derived class. Because the intention is to retrieve a data table from this service, the data contract method will be of type DataTable.

[ServiceContract]
    public interface IServerStatus
    {
        [OperationContract]
        DataTable GetServerStatusDetails();
    }

Under the derived class in the implemented method GetServerStatusDetails, create the data objects needed for the output:

DataSet dataSet = new DataSet();

Next, create the SQL Connection using the connection string from Web.config:

SqlConnection connection = new SqlConnection(
    ConfigurationManager.ConnectionStrings["VisioServicesConnectionString"].ConnectionString);

Create the command object by calling the stored procedure with the help of the SQL Connection, and set the command type to StoredProcedure:

SqlCommand command = new SqlCommand("uspGetServerDetails", connection);
command.CommandType = CommandType.StoredProcedure;

Finally, create the data adapter, load the command, and fill the data set using the data adapter:

SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
dataAdapter.Fill(dataSet);

Close the connection, and return the output:

connection.Close();
return dataSet.Tables[0];

image Tip  If you are a novice WCF developer, simply start from here: http://blah.winsmarts.com/2008-4-Writing_the_WCF_Hello_World_App.aspx.

Custom Data Provider Class (Listing 2-6)

Before beginning, it is important to understand some of the key concepts. First, prepare to query data from data sources that are not natively supported. Second, these operations must be asynchronous in order to perform the tasks in a timely fashion. And most importantly, the methods used must be thread safe.

Microsoft.Office.Visio.Server assembly provides these functionalities with its abstract class AddonDataHandler and its abstract methods that deal with all the necessary data-module implementations.

Add a reference to Microsoft.Office.Visio.Server because the derived class will be inheriting the AddonDataHandler abstract class. It needs to also inherit the IAsyncResult interface from the System namespace to get the result of the asynchronous operation. Though there are many methods to override, the most important to understand are BeginGetData and EndGetData.

Visio Services calls the custom data provider’s BeginGetData() method as soon as the request begins. Under the BeginData() method, create a thread and delegate a method to it. Create a callback method to be aware of when the thread completes its job:

ThreadPool.QueueUserWorkItem(new WaitCallback(GetData), callback);

In the GetData() method, create an instance to the WCF service object and call the GetServerStatusDetails method to retrieve the Server Status details:

ServerStatusClient oServerStatus = new ServerStatusClient();
DataTable dt = oServerStatus.GetServerStatusDetails();
this.Data.Reset();
this.Data.Tables.Add(dt);
this.Data.AcceptChanges();

After the set operation completes its job by retrieving the data, Visio Services calls the EndGetData() and returns the Data object as DataSet:

return this.Data;

VBA Code (Listing 2-8)

The VBA code is used it to create and populate a data source that can be used by the Visio diagrams. This is similar to creating a data source using macros.

The code is very simple. It begins by initializing the data objects such as recordset, connection strings, command text, etc.

Dim diagramServices As Integer
Dim vsoDataRecordset As Visio.dataRecordset
Dim dataRecordset As Visio.dataRecordset
Dim connectionString As String
Dim commandText As String

First, get to the instance of the diagram services of the active document, which is the page. Set the Visio Services Version and the visibility of the external data sources window to true:

diagramServices = ActiveDocument.DiagramServicesEnabled
ActiveDocument.DiagramServicesEnabled = visServiceVersion140
Application.ActiveWindow.Windows.ItemFromID(visWinIDExternalData).Visible = True

The following steps are optional here. They are to populate the external data source with values to facilitate a designer’s choice to bind the row data to the shapes in design mode. Connect to the SQL store, retrieve the recordset, and add the recordset to the active document data record set collection:

commandText = "SELECT ServerName, ServerIP, ServerStatus FROM tblServerStatus"
connectionString = "Provider=SQLOLEDB;Data Source=<YourDataSourceName>;Initial Catalog=VisioServices;Integrated Security=SSPI; "
Set vsoDataRecordset = ActiveDocument.DataRecordsets.Add(
                                                 connectionString, commandText, 0, "Server Status Details")

Set the custom data-provider assembly details to the recordset command string. Set and enable the diagram services to the active document:

vsoDataRecordset.DataConnection.connectionString =
"DataModule=Altsis.VisioDataService,VisioDataService;"
ActiveDocument.DiagramServicesEnabled = diagramServices

So far, you’ve seen a lot of information on Visio and Visio Services. Now it’s time to get to know some more references and information. You have seen the administration of Visio Services using the UI in Central Administration. Now, you will learn more options for administering Visio Services using both CA and Windows PowerShell.

Administration of Visio Services

Administering Visio Services can be done using either Central Administration (CA) or PowerShell (PS). To access PowerShell, simply click on Start image All programs image Microsoft SharePoint 2013 Products image SharePoint 2013 Management Shell.

Before administering Visio Services, be sure to follow these two steps:

  1. Set up an application pool and a managed account. Most of the settings and configurations require both application pool accounts and managed accounts, and you really don’t want to go back to create them in the middle of an operation. Plan ahead, and make a list of all these accounts before you begin setting up your farm/application.
  2. Make sure you are member of the Administrators group. Again, you definitely need to be the local administrator for many obvious reasons. You don’t want to start your application with a low-privilege account and have your access denied for an administration job.

Creating a New Visio Graphics Service Application

From CA: From Application Management image Manage Service Applications, click New and choose Visio Graphics Service. Provide the application name, choose an application pool or create a new one, choose whether or not to create an application proxy (add to default group), and click OK.

Using PS: At the PS prompt, type the following:

New-SPVisioServiceApplication <ServiceApplicationName> - serviceapplicationpool <ServiceApplicationPoolName> -AddToDefaultGroup

Deleting an Existing Visio Graphics Service Application

From CA: From Application Management image Manage Service Applications, choose the Visio Graphics Service application name, and then click on the Delete button on the ribbon.

Using PS: At the PS prompt, type the following:

Remove-SPServiceApplication <VisioServiceApplicationName>

List all Existing Visio Graphics Service Applications

From CA: From Application Management image Click on Manage Service Applications to view all Visio Services Service applications.

Using PS: At the PS prompt, type the following:

Get-SPVisioServiceApplication

Creating a New Visio Graphics Service Application Proxy

From CA: You can create an application proxy only when creating a new Service application.

Using PS: At the PS prompt, type the following:

New-SPVisioServiceApplicationProxy <ServiceApplicationName>

image Note  Service application proxies stand as the gateway or channel for connecting with service applications. They are deployed along with the service applications, and they encapsulate the components used to execute the calls on the service application.

Delete an Existing Visio Graphics Service Application Proxy

From CA: From Application Management image Manage Service Applications, from the available Visio Service Proxies, select the proxy from the list, and click the Delete button on the ribbon.

Using PS: At the PS prompt, type the following:

Remove-SPServiceApplicationProxy <ProxyID>

List All Existing Visio Graphics Service Application Proxies

From CA: From Application Management image Click on Manage Service Applications to view all available Visio Service Application Proxies under the selected Service application.

Using PS: At the PS Prompt, type the following:

Get-SPVisioServiceApplicationProxy

Setting Up Visio Graphics Service Global Settings

From CA: From Application Management image Manage Service Application, choose Visio Graphics Service image Global Settings. You can now set Maximum Diagram Size, Minimum Cache Age, Maximum Cache Age, Maximum Recalc Duration, and External Data.

Using PS: To set the performance parameters, at the PS Prompt type the following:

Set-SPVisioPeformance –MaxDiagramCacheAge <InMinutes> -MaxDiagramSize <SizeInMB> -MaxRecalcDuration <InSeconds> -MinDiagramCacheAge <InMinutes> - VisioServiceApplication <VisioServiceApplicationName>

To set the data configuration, at the PS Prompt type

Set-SPVisioExternalData –VisioServiceApplication <VisioServiceApplicationName> -UnattendedServiceAccountApplicationID <ApplicationID>

Setting Up a Graphics Service Trusted Data Provider

From CA: From Application Management image Manage Service Application, choose Visio Graphics Service image Trusted Data Providers. Now add a new Trusted Data Provider, or edit or delete an existing one. (For the how-to steps, refer to the  “Secure Store Service” section of this chapter.)

Using PS: To create a new Trusted Data Provider, at the PS Prompt type

New-SPVisioSafeDataProvider –DataProviderId <ProviderID> -DataProviderType <Int32> -VIsioServiceApplication <VisioServiceApplication>

To edit an existing Trusted Data Provider, at the PS prompt type

Set-SPVisioSafeDataProvider –DataProviderId <ProviderId> -DataProviderType <Int32> -Description <String> -VisioServiceApplication <VisioServiceAPplicationName>

To delete an existing Trusted Data Provider, at the PS prompt type

Remove-SPVisioSafeDataProvider –DataProviderId <ProviderId> -DataProviderType <Int32> -VisioServiceApplication <VisioServiceApplicationName>

Factors Affecting the Performance of Visio Services

Many factors are involved in the performance of Visio Services. One of the key factors is often the infrastructure itself. If the following items don’t help you achieve optimum performance, keep in mind that the weakest link might well be your infrastructure:

  • Complexity of the drawing: This involves the number of shapes, data sources, pages used, and so forth.
  • Number of users accessing the drawing: The number of end users accessing a drawing simultaneously, especially during peak load hours, affect performance.
  • Size of the drawing: The size of the drawing itself can be a factor; the more complex the drawing, the greater the size, and this takes more time to render.
  • Data source performance: External data sources connectivity, access, and performance all influence performance.
  • Data refresh settings: As we discussed earlier, when you have a smaller data-refresh interval, you get more real-time access and less from the cache, which can hit performance badly.

image Note  For more information, read the TechNet article “Plan Visio Services deployment in SharePoint Server 2013” at http://technet.microsoft.com/en-us/library/ff356849.aspx.

Summary

In this chapter, we looked at the following (as summarized in Figure 2-86):

  • Why you should use Visio and what the Visio Services in SharePoint Server 2013 are.
  • The Visio client and its new features.
  • Integrating Visio with SharePoint using a Visio Web Access (VWA) web part and the JavaScript Mashup API.
  • Implementing Secure Store Services and using it in conjunction with Visio, SQL Server, and SharePoint.
  • Designing custom data providers with Visio Services.
  • Administering Visio Services.

9781430258933_Fig02-86.jpg

Figure 2-86. Visio Services in SharePoint 2013

What’s Next?

In the next chapter, you will learn about Reporting Services in SQL Server 2012, architecture and installation, the Reporting Services add-in, data source management, report-authoring tools, and the integration of Reporting Services with SharePoint. You will also learn about publishing reports in native and SharePoint mode, Access Services, and managing Reporting Services.

1 Connecting data to shapes is explained in the “The Visio 2013 Client’s Data Tab” section.

2 Data graphics are explained in the “The Visio 2013 Client’s Data Tab” section.

3 Explained in the “Using a SQL Server Data Source” section.

4 Explained in the “Secure Store Services” section.

5 Explained in the “Shape Data Window” section.

6 The .odc file can be repurposed to create a new data source connection from the Data Selector window by choosing the option Previously created connection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset