Step 3: Create a Web Application Page to Start Conversions

Applies to: SharePoint Server 2010

In this topic you create a SharePoint Server 2010 application page that you use to start Word Automation Services document conversions.

Creating an Application Page to Start Conversions

The new document context menu item you created in Step 2 of this walkthrough opens an application page that allows users to start Word Automation Services document conversions. The following procedures demonstrate how to write code in an application page .aspx page and its associated .cs "code behind" page that allows users to perform a document conversion for a specific document.

To create the application page

  1. In the Solution Explorer window, right-click on the project, point to Add, and then click New Item…

  2. Select Application Page from the item list.

  3. Enter a name for the application page, for example, ConvertItem.aspx.

  4. Click Add to add the application page to the project.

    This page specifies three content regions inherited from the SharePoint Server 2010 master page which you override to create the customized application page.

  5. In the HTML for the ConvertItem.aspx page, locate the <asp:Content> tag with an ID attribute value of PageTitle. Add a string for the page title, for example, Convert Document.

  6. Locate the <asp:Content> tag with an ID attribute value of PageTitleInTitleArea. Add a string for this area of the page, for example, Convert Document.

  7. Locate the <asp:Content> tag with an ID attribute value of Main. Add the following HTML for the page.

    <table cellpadding="5">
    <tr><td colspan="2"><h1>Convert Document</h1></td></tr>
    <tr><td colspan="2">Choose the output location of the converted document, and the desired output file type below. By default, the converted document will be placed in the same location as the input document.</td></tr>
    <tr><td>Document to convert:</td><td></td></tr>
    <tr><td>Output location:</td><td></td></tr>
    <tr><td>Output file type:</td><td></td></tr>
    <tr><td></td></tr>
    </table>
    
    
  8. In the second cell in the third row of the table, add a Label control which will contain the name of the input file.

    <asp:Label ID="lblInputItem" runat="server"/>
    
  9. In the second cell in the fourth row of the table, add a TextBox control which will contain the name of the output file.

    <asp:TextBox ID="tbOutputItem" runat="server" Width="600"/>
    
  10. In the second cell in the fifth row of the table, add a DropDownList control which will contain file format of the output file.

    <asp:DropDownList ID="ddFileTypes" runat="server" AutoPostBack="true"><asp:ListItem Text="PDF" /><asp:ListItem Text="XPS" /><asp:ListItem Text="DOCX" /><asp:ListItem Text="DOCM" /><asp:ListItem Text="DOC" /><asp:ListItem Text="DOTX" /><asp:ListItem Text="DOTM" /><asp:ListItem Text="DOT" /><asp:ListItem Text="XML" /><asp:ListItem Text="RTF" /><asp:ListItem Text="MHT" /></asp:DropDownList>
    
  11. In the cell in the sixth row of the table, add a Button control which will start the conversion.

    <asp:Button ID="btnConvert" runat="server" Text="Convert"/>
    

Once you write the HTML code for the ConvertItem.aspx page, you need to add Visual C# code that uses the Word Automation Services to the ConvertItem.aspx.cs code behind page.

To add code to the code behind page

  1. In Solution Explorer, expand ConvertItem.aspx, and then double-click ConvertItem.aspx.cs.

  2. Add a using directive for the namespace that contains the Word Automation Services object model that you use to perform document conversions.

    using Microsoft.Office.Word.Server.Conversions;
    
  3. In the Page_Load event for the page, add code to populate the input and output file names on the page.

    // Only set up the values the first time the page is loaded
    if (!IsPostBack)
    {
        // Get the input file URL from the query string
        string itemUrl = Request.QueryString["ItemUrl"];
        string inputPath = Site.Url + itemUrl;
        lblInputItem.Text = inputPath;
    
        // Write the output file URL
        // Since the default on the drop-down is PDF, set that by default
        string outputPath = Path.ChangeExtension(inputPath, "pdf");
        tbOutputItem.Text = outputPath;
    }
    

    The previous code gets the menu item site-relative URL from the query string, which is defined as part of the UrlAction above, concatenates that with the site URL to get the full path to the file, and then stores the full path in the Label control for the input file.

    Then, the code takes the location of the input file, changes the file extension to .PDF (set as the default), and then puts that into the textbox control for the output file.

  4. Add an event handler to the ConvertItem.aspx page that automatically changes the output file extension when the drop-down list is changed. Add the following HTML code to the <asp:DropDownList> element.

    OnTextChanged="ddFileTypes_TextChanged"
    
  5. Add the code for the ddFileTypes_TextChanged event handler to the code behind page.

    protected void ddFileTypes_TextChanged(object sender, EventArgs e)
    {
        // Update the output path based on the selected item
        tbOutputItem.Text = Path.ChangeExtension(tbOutputItem.Text, ddFileTypes.SelectedValue.ToLowerInvariant());
    }
    

    This code changes the file extension on the output file to the value selected in the drop-down list.

  6. Add an event handler to the ConvertItem.aspx page that starts conversions when the button is pressed. Add the following HTML code to the <asp:Button> element.

    OnClick="btnConvert_Click"
    
  7. Add the code for the btnConvert_Click event handler to the code behind page.

    protected void btnConvert_Click(object sender, EventArgs e)
    {
        try
        {
            // Create a conversion job
            ConversionJob job = new ConversionJob("Word Automation Services"); // This is the default name of the service application
    
            // Set the settings
            job.UserToken = Site.UserToken;
            if (Site.SiteSubscription != null)
                job.SubscriptionId = Site.SiteSubscription.Id;
            job.Settings.OutputFormat = GetSaveFormat(ddFileTypes.SelectedValue);
            job.Name = "Conversion from Convert Item Menu";
    
            // Add the file
            job.AddFile(lblInputItem.Text, tbOutputItem.Text);
    
            // Start conversion
            job.Start();        
        }
        catch (Exception ex)
        {
            // Show standard SharePoint error page
            Response.Redirect("/_layouts/Error.aspx?ErrorText=" + Server.UrlEncode(ex.Message));
        }
    }
    
    private SaveFormat GetSaveFormat(string saveFormat)
    {
        switch (saveFormat.ToLowerInvariant())
        {
            case "pdf":
                return SaveFormat.PDF;
            case "xps":
                return SaveFormat.XPS;
            case "doc":
                return SaveFormat.Document97;
            case "docx":
                return SaveFormat.Document;
            case "docm":
                return SaveFormat.DocumentMacroEnabled;
            case "dot":
                return SaveFormat.Template97;
            case "dotx":
                return SaveFormat.Template;
            case "dotm":
                return SaveFormat.TemplateMacroEnabled;
            case "mht":
                return SaveFormat.MHTML;
            case "rtf":
                return SaveFormat.RTF;
            case "xml":
                return SaveFormat.XML;
            default:
                throw new InvalidCastException("unsupported file type");
        }
    }
    

    The previous code instantiates a new ConversionJob, which defines a set of conversions, supplying the name of the service application to the ConversionJob(String) constructor method.

    Note

    This example assumes the name of the service application is "Word Automation Services", which is the default name when it is created using the Farm Configuration Wizard. If you have used a different name for the service application, you use that instead.

    Then, the code sets the necessary settings for the conversion:

    • The UserToken property specifies the user credentials used to read the input file and write the output file.

    • The SubscriptionId property specifies the site subscription ID of the site.

      Note

      This parameter is only required if the SharePoint farm has been configured in partitioned mode.

    • The OutputFormat property specifies the output file format for the conversion.

    Additionally, the code specifies one optional setting:

    • The Name property specifies a friendly name for the conversion.
  8. Finally, add code immediately following the call to the Start() method to redirect the page upon successfully initiating a conversion job.

    // Redirect to the success page, including the original location as a query parameter
    SPList list = Web.Lists[new Guid(Request.QueryString["ListId"])];
    SPListItem item = list.GetItemById(int.Parse(Request.QueryString["ItemId"]));
    Response.Redirect("/_layouts/ConvertItem/ConvertStatus.aspx?url=" + Server.UrlEncode(Web.Url + "/" + item.File.ParentFolder.Url) + "&jobId=" + job.JobId.ToString(), false);
    

    This code redirects to a second web page (that you create in the next step in this walkthrough) once the conversion has started, passing two parameters: a URL pointing back to the original file location, and the ID for the conversion job (which allows the end user to monitor the status of the conversion).

See Also

Tasks

Step 4: Create a Web Application Page to Monitor Conversions

Step 5: Build and Deploy the ECB Menu Solution

Concepts

Walkthrough: Use an Edit Control Block Menu Item to Create a Conversion Job

Other Resources

Programming Word Automation Services