Project Programmability

This blog focuses on customizations and programming for Project Web App, Project Server, Project Professional and Project Standard. Includes User Interface (UI) customizations, Project Server Interface (PSI) and Visual Basic for Applications (VBA) Programming. It also covers Business Intelligence.

November, 2012

  • Project Programmability and Business Intelligence

    Installing the Project 2013 SDK download on Windows 8


    The Project 2013 SDK download is updated for the RTM release of Project 2013. In addition to articles, references, and code samples that are updated from the July release of Project 2013 Preview, the SDK also includes a local copy of VBA Help for Project Standard and Project Professional.

    You can install the downloaded Project2013SDK.msi file on computers that are running Windows 8, Windows 7 (and a couple of earlier Windows releases), Windows Server 2008 R2, and Windows Server 2012. When you install the SDK on a Windows 7 machine, the SDK contents are accessible from the Start menu. Figure 1 shows, for example, that the Microsoft SDKs folder contains the Project 2013 SDK folder, which contains links to three files. From the hierarchical context of the Start menu, it is clear that the Documentation node is contained in the Project 2013 SDK folder.

    Similarly, if you install the SharePoint 2013 SDK download and the Apps for Office and SharePoint SDK download, they each create a folder in Microsoft SDKs, and each SDK has a Documentation node within its folder.

    Figure 1. Using the Project 2013 SDK from the Windows 7 Start menu


    The problem

    Windows 8 does not have a Start menu, it has two related Start screens. After you install the Project 2013 SDK download, and scroll the main Start screen to the links for the installed files, you can see the same three links as in Windows 7. (To see the Welcome Guide on the Start screen, you can search for Welcome.rtf, open it in Internet Explorer, and then pin Welcome Guide to the Start screen.) But, the Start screen in Windows 8 is not arranged in hierarchical folders. In Figure 2, it is not clear what the Documentation link is for.

    Figure 2. Using the Documentation link to the Project 2013 SDK, on the Windows 8 Start screen


    The problem is worse if you also install the SharePoint 2013 SDK and the Apps for Office and SharePoint 2013 SDK. You would then have three Documentation links and three Welcome Guide links, each of which goes to a different SDK.

    If you right-click one of the Start screen icons, the icon shows a check mark, and the Start screen shows options at the bottom (see Figure 2). If you choose All apps at the bottom right of the screen, Windows 8 shows lists of installed apps within top-level groups. For example, the Microsoft SDKs group contains links for all of the Office, Project, and SharePoint SDKs that you install; there are no subfolders to distinguish which links go to which SDK. In Figure 3, only the Project 2013 SDK is installed, and the links have the same names as in Figure 2.

    Figure 3. Using the Project 2013 SDK links in the Apps view, in Windows 8


    The workaround (for now)

    On a machine with Windows 8, you can install one SDK at a time, and then rename the links on the Start screen, before installing another SDK.

    To install Office, Project, and SharePoint SDKs on Windows 8

    1. Log on to Windows 8 as an administrator.
    2. Install, for example, the Project 2013 SDK.
    3. On the Start screen, right-click the Documentation icon, and then choose Open file location at the bottom of the screen.
    4. On the Windows Desktop, rename the Documentation link as Project 2013 SDK Documentation, and then choose Continue in the File Access Denied dialog box (see Figure 4).

      Figure 4. Renaming the Project 2013 SDK links in the Desktop view
    5. Similarly, rename the VBA Reference link as Project 2013 VBA Reference, and rename the Welcome Guide link as Project 2013 Welcome Guide.
    6. With the mouse pointer in the lower-left corner of the screen, choose the Start pop-up icon, and then scroll to the Project 2013 SDK icons (see Figure 5).

      Figure 5. Using the renamed links in the Start view
    7. Install the Apps for Office and SharePoint 2013 SDK, and similarly rename the Start screen links.
    8. Install the SharePoint 2013 SDK, and similarly rename the Start screen links. Figure 6 shows the Microsoft SDKs group with the renamed links in the All apps view.

    Figure 6. Using the renamed links for all three SDKs in the All apps view


    In future releases, the Office, SharePoint, and Project SDK downloads will be reconfigured so that they install with non-conflicting link names on Windows 8.


  • Project Programmability and Business Intelligence

    Creating Project Workflows using Visual Studio 2012


    In Project Server 2010, Project developers were able to create Project Workflows using Visual Studio 2010. In Project Server 2013, we enabled creating the workflows with SharePoint Designer, which makes it much easier and faster to create Project Workflows. In that blog post, we showed how we have simplified the workflow creation for Project using SharePoint Designer 2013.

    We are, however, still supporting creating Project Workflows with Visual Studio for the more complex set of workflows, and in fact, have also made it easier to create Project Workflows with Visual Studio 2012. Below, we are going to use a sample two-stage workflow to show how you can create workflows with Visual Studio 2012:

    1. Creating the Workflow solution: File Menu>New>Project>Office/SharePoint>SharePoint solutions > SharePoint 2013 Project. Give this project a name, and hit OK:

    In the customization wizard, enter the address of the PWA web you’d like this workflow to be published to. Then, pick the sandboxed solution option to limit this workflow to this particular PWA web:

    2. At this point, the project you’ll see the empty canvas. In the Project Menu, click on the Add New Item, and from the Office/SharePoint tab, select Workflow, enter a name, and hit Add:

    Then, in the customization wizard, pick Site workflow:

    Then, pick the history list and the workflow tasks list from that site. We recommend that you use the default lists since a number of PWA UI entry points, use these default lists. Then, hit Finish:

    3. Now, we need to set up the environment to use the Project Server activities. In the toolbox, right click and click on “add tab”, and call the new tab “project server”:

    Then, right click on the “project server” tab and click on “choose items” from the menu, and you’ll see this dialog:

    In the dialog click on Browse, and navigate to where the workflow dlls are located. They are usually located in C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\WorkflowActivities
    You’ll see two activities dll there. Open the project server one (Microsoft.Office.Project.Server.WorkflowActivities.dll), and hit OK. You are now taken back to the “toolbox items” dialog, and highlights the selected corresponding activities. Hit OK to continue.

    4. You might see a “sequence” in the canvas. Delete that, and from the toolbox, pick Flowchart and add it by dragging it into the main area. This flowchart will be the main container of all the stages of the workflow:

    In the toolbox, click on Control flow, and add the sequence inside that flowchart. Throughout this sample workflow, we will use sequence to represent workflow stages in Visual Studio. This is similar to how SharePoint Designer handles each stage, i.e. each stage is equivalent to a separate sequence in Visual Studio:

    Rename the sequence to “Create_Stage” by clicking on the “Sequence” and start typing to change the name. Drag the line from start to “Create_Stage” to connect them together:


    5. Double click on the “Create_Stage” to drill into this sequence

    a. Under project server in toolbox, add the “EnterProjectStage” and “ExitProjectStageGate” activities to the sequence. These two activities are required in any of the PWA stages in Visual Studio.

    b. In the properties of “EnterProjectStage”, change the StageID to the Stage ID of the particular stage you’d want this sequence to represent. You can find the stage ID in the URL of that stage, and is available if you navigate to that stage in PWA Settings > Workflow Stages, and then click on the particular stage. Since stageID is a string, the ID should be provided in quotation marks.

    c. Put another sequence between “EnterProjectStage” and “ExitProjectStageGate”. Essentially, everything in this sequence is what is represented in the text-based designer in SharePoint Designer stage definition.

    d. From project server item in the toolbox, drop the “waitForProjEvent” activity in that sequence:

    e. Change the EventName property to “OnProjectSubmit”. The other supported Event Names are “OnProjectCommit” and “OnProjectCheckIn”

    6. In the breadcrumb, click on Flowchart to go one level up. Add another sequence after Create_Stage and call it Finished_Stage, and connect the wire from Create_Stage to the Finished_Stage:

    7. Similar to the Create_Stage, add the EnterProectStage and ExitProjectStageGate activities to the sequence as well as the WaitForProjectEvent activity in the middle, and set the properties accordingly:



    8. This completes building the workflow in Visual Studio. However, in order to make sure that the workflow can be properly published to the PWA, we need to make a few more changes in the xaml files of the project: From solution explorer, pick “Elements.xaml” under the workflow node

    a. Replace the WSEventSourceGUID with the following so that the workflow is correctly identifies as a project workflow:
    <Property Name="WSEventSourceGUID" Value="5122D555-E672-4E5D-A7C4-8084E694A257" />

    b. Inject the following properties under the “Url = WorkflowStartAssociation”:
          <Property Name="Microsoft.ProjectServer.ActivationProperties.ProjectId" Value="" />
          <Property Name="Microsoft.ProjectServer.ActivationProperties.CurrentStageId" Value="" />
          <Property Name="Microsoft.ProjectServer.ActivationProperties.RequestedStageId" Value="" />
          <Property Name="WSEventContextKeys" Value="Microsoft.ProjectServer.ActivationProperties.CurrentStageId;#Instance&#xA;Microsoft.ProjectServer.ActivationProperties.ProjectId;#Instance&#xA;Microsoft.ProjectServer.ActivationProperties.RequestedStageId;#Instance&#xA;" />

    9. Now that everything is set, and the workflow is ready for publishing, click on the “Build Solution” under the Build menu, and then click on the “Deploy Solution” under the Build menu. The wsp file is now deployed to the site. You can also find a copy of the wsp file in the file system, under [project name]>bin>debug

    Now, the workflow will show up in PWA. If you navigate to PWA Settings > Enterprise Project Types, and create a new Enterprise Project Type, you will see this workflow as one of the options in the workflow dropdown list.

    For more information, see Getting started developing Project Server 2013 workflows in the Project 2013 SDK.

  • Project Programmability and Business Intelligence

    Connecting a Project Task Pane App to PWA



    Apps for Office present a great new opportunity to bring data from a variety of sources into Office applications. The new Project specifically offers a very powerful way to surface both SharePoint and Project Web App data in a task pane app in Project Professional. To connect with SharePoint or PWA from the client, we use on-the-fly OAuth flow as presented in the SharePoint 2013 SDK. The App for Project described in this article connects with the same PWA site collection that Project Professional is currently connected to, and displays data about the currently selected task that is not otherwise available from within Project Professional. This will work with all versions of Project Professional (C2R, MSI, On Demand) and with all PWA environments (Project Online, Project Server).



    Prerequisites for this project are:

    • Visual Studio 2012
    • IIS or IIS Express configured to allow applications to run on your server (at localhost)
    • Office 2013 and SharePoint 2013 tools for Visual Studio, available here
    • Project Professional 2013
    • Project Online tenant or Project Server

    The first step is to launch Visual Studio 2012. Create a new App for Office 2013 project as shown below. Let’s call it “TaskLastModifiedApp”.


    In the next dialog, make this a Task Pane App for Project.

    We need to add references, as this app will use a number of APIs across Office and SharePoint. These DLLs may be in a different location on your system. Most of these references are automatically added if you use the App for SharePoint template, so if you can’t find these on your system, create a quick App for SharePoint solution and note the reference paths to help you out. You should add:

    • C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5\Microsoft.IdentityModel.dll
    • C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.IdentityModel.Extensions\v4.0_2.0.0.0__69c3241e6f0468ca\Microsoft.IdentityModel.Extensions.dll
    • C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5\Microsoft.IdentityModel.WindowsTokenService.dll
    • C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.ProjectServer.Client.dll
    • C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll
    • C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll
    • C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.IdentityModel.dll
    • C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.IdentityModel.Selectors.dll
    • C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.ServiceModel.dll

    Additionally, you will need to add a copy of TokenHelper.cs, which is generated when creating an autohosted or provider-hosted App for SharePoint project.

    Task Pane App Manifest

    The actual task pane app is just an XML manifest. Open up TaskLastModifiedApp.xml from the TaskLastModifiedApp project in your Solution Explorer. Replace its contents with the following:

     1: <?xml version="1.0" encoding="UTF-8"?>
     2: <OfficeApp xmlns="" xmlns:xsi="" xsi:type="TaskPaneApp">
     3:   <Id>[leave this line alone]</Id>
     4:   <Version>1.0</Version>
     5:   <ProviderName>Microsoft</ProviderName>
     6:   <DefaultLocale>en-US</DefaultLocale>
     7:   <DisplayName DefaultValue="TaskLastModifiedApp" />
     8:   <Description DefaultValue="This app will show you when the selected task was last modified"/>
     9:   <AppDomains>
     10:     <AppDomain>https://localhost:44301/</AppDomain>
     11:   </AppDomains>
     12:   <Capabilities>
     13:     <Capability Name="Project" />
     14:   </Capabilities>
     15:   <DefaultSettings>
     16:     <SourceLocation DefaultValue="https://localhost:44301/pages/URLConstructor.aspx" />
     17:   </DefaultSettings>
     18:   <Permissions>ReadWriteDocument</Permissions>
     19: </OfficeApp>

    Replace the port after localhost (in both instances) with whatever port you have configured IIS to use for SSL. Make sure to toggle the “SSL Enabled” property on the TaskLastModifiedAppWeb project to true. Let whatever ID was originally set in the manifest remain.


    Next, delete the TaskLastModifiedApp.html page – we will need .aspx pages in this project. The basic architecture of the task pane app is as follows:

    • When the task pane app is launched, it loads “URLConstructor.aspx”, which pulls the PWA URL from the client and constructs a call to OAuthAuthorize with the proper tokens to request permissions for the app to access PWA data. This page loads “URLConstructor.js” to interact with the client.
    • OAuthAuthorize is launched in a new window, since we cannot predict the customer’s Project domain. After the user trusts the app, that new window is redirected to “PostOAuth.aspx”, which surfaces the auth code back to URLConstructor.aspx.
    • Once URLConstructor.aspx has the auth code, the task pane app is redirected with this as a token to “Default.aspx”, which has the functional code for the app. This page uses Project CSOM code in its code-behind page to read data from PWA, as well as “TaskLastModifiedApp.js” to interact with the client.

    Constructing the OAuthAuthorize URL

    The complete code for URLConstructor.aspx is as follows:

     1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="URLConstructor.aspx.cs" Inherits="TaskLastModifiedAppWeb.Pages.URLConstructor" %>
     3: <!DOCTYPE html>
     5: <html xmlns="">
     7: <head runat="server">
     8:     <title>TaskLastModifiedApp</title>
     9:     <meta http-equiv="X-UA-Compatible" content="IE=9" />
     10:     <script type="text/javascript" src="..\Scripts\Office\1.0\MicrosoftAjax.js"></script>
     11:     <script type="text/javascript" src="..\Scripts\Office\1.0\Office.js"></script>
     12:     <script type="text/javascript" src="..\Scripts\URLConstructor.js"></script>
     13:     <script type="text/javascript">
     14:         function getClientId() {
     15:             var clientId = '<%=ConfigurationManager.AppSettings["ClientId"].ToString() %>'; //read the clientID from web.config
     16:             getPwaUrl(clientId); //return to client code
     17:         }</script>
     18: </head>
     20: <body>
     21:     Redirecting...
     22: </body>
     24: </html>

    This page needs to be an .aspx page in order to read from web.config, but does not need anything in its code-behind. The clientId read from web.config is needed for the authorization flow. getPwaUrl() is a function within URLConstructor.js.

    The complete code for URLConstructor.js is as follows:

     1: var _projDoc;
     2: var pwaUrl;
     3: var oAuthUrl;
     5: Office.initialize = function (reason) {
     6:     _projDoc = Office.context.document;
     7:     getClientId(); //on document load, reads the ClientId from web.config first since it is server-side
     8: }
     10: function getPwaUrl(clientId) { //uses Office App API to read PWA URL
     11:     _projDoc.getProjectFieldAsync(Office.ProjectProjectFields.ProjectServerUrl,
     12:         function (asyncResult) {
     13:             if (asyncResult.status == Office.AsyncResultStatus.Succeeded) {
     14:                 pwaUrl = asyncResult.value.fieldValue;
     15:                 generateUrl(clientId); //creates the OAuthAuthorize URL with necessary parameters
     16:             }
     17:             else {
     18:                 logMethodError("getProjectFieldAsync",, asyncResult.error.message);
     19:             }
     20:         }
     21:     )
     22: };
     24: function generateUrl(clientId) {
     25:     oAuthUrl = pwaUrl + "/_layouts/15/OAuthAuthorize.aspx?IsDlg=1&client_id=" + clientId + "&scope=Projects.Read&response_type=code&redirect_uri=https://localhost:44301/pages/PostOAuth.aspx";
     26:     authWindow =;
     27:     codeListener(); //start listening for the auth code
     28: }
     30: function codeListener() {
     31:     setTimeout(function () { readCode(); }, 1000); //check for the auth code every one second
     32: }
     34: function readCode() {
     35:     try { //if we can actually reach the authCode field on PostOAuth.aspx
     36:         authCode = authWindow.document.getElementById("authCode").value;  //pull the authCode value
     37:         if (authCode != "NA") { //if it is not the default "NA"
     38:             authWindow.close(); //close the new window
     39:             document.location.href = "/Pages/Default.aspx?code=" + authCode; //redirect task pane to the app code with the authCode token
     40:         }
     41:     }
     42:     catch (e) {
     43:         codeListener(); //if we couldn't reach PostOAuth.aspx, wait another second and try again
     44:     }
     45: }

    When the task pane app loads, it first reads web.config from the aspx page, since this is server-side code. Once it has the clientId, we read the PWA URL. We then create the full OAuthAuthorize URL with the parameters specified above. scope=Projects.Read requests read permission to projects on the current PWA site. Make sure to match the SSL port here as well, as before.

    On running the app, a new window will open up outside of Project that prompts the user to login to PWA (if they have not checked “Keep me signed in” previously). They will then be presented with a “Do you trust…” page, the same as if they were installing an App for SharePoint. This is the OAuthAuthorize.aspx page. Once trusted, that new window navigates to PostOAuth.aspx, presented below:

     1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PostOAuth.aspx.cs" Inherits="TaskLastModifiedAppWeb.Pages.PostOAuth" %>
     3: <!DOCTYPE html>
     5: <html xmlns="">
     6: <head runat="server">
     7:     <title></title>
     8: </head>
     9: <body>
     10:     <form id="form1" runat="server">
     11:     <div>
     12:     <asp:HiddenField ID="authCode" runat="server" value="NA"/>
     13:         Closing...
     14:     </div>
     15:     </form>
     16: </body>
     17: </html>

    And PostOAuth.aspx.cs:

     1: using System;
     2: using System.Collections.Generic;
     3: using System.Linq;
     4: using System.Web;
     5: using System.Web.UI;
     6: using System.Web.UI.WebControls;
     8: namespace TaskLastModifiedAppWeb.Pages
     9: {
     10:     public partial class PostOAuth : System.Web.UI.Page
     11:     {
     12:         protected void Page_Load(object sender, EventArgs e)
     13:         {
     14:             var code = Request.QueryString["code"];
     15:             authCode.Value = code;
     16:         }
     17:     }
     18: }

    This page saves the auth code token in a hidden field. The task pane app, still on URLConstructor.aspx, waits for this value and then closes the new window. The app then continues on to default.aspx with the proper code token needed to finish the OAuth flow.

    Reading the Last Modified Date of the Selected Task

    The remainder of this article is an example of what you might do in your task pane app now that you have read access to PWA data. This example will show you the Last Modified date and time of the task you have selected. On launch, it shows you data for the selected task, and as you change tasks, the data is updated using an event handler.

    The complete code for Default.aspx is as follows:

     1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TaskLastModifiedAppWeb.Pages.Default" %>
     3: <!DOCTYPE html>
     5: <html xmlns="">
     6: <head runat="server">
     7:     <title>TaskLastModifiedApp</title>
     8:     <meta http-equiv="X-UA-Compatible" content="IE=9" />
     9:     <script type="text/javascript" src="..\Scripts\Office\1.0\MicrosoftAjax.js"></script>
     10:     <script type="text/javascript" src="..\Scripts\Office\1.0\Office.js"></script>
     11:     <script type="text/javascript" src="..\Scripts\TaskLastModifiedApp.js"></script>
     13: </head>
     15: <body>
     16:     <form id="form1" runat="server">
     18:         <asp:HiddenField ID="projGuidHF" runat="server" />
     19:         <asp:HiddenField ID="taskGuidHF" runat="server" />
     20:         <asp:HiddenField ID="pwaUrlHF" runat="server" />
     22:         <asp:Label ID="TaskLastModLabel" runat="server" Text="Loading..." />
     24:         <div style="display: none;">
     25:             <asp:Button ID="hiddenTaskChangedButton" runat="server" OnClick="OnTaskChanged" />
     26:         </div>
     28:     </form>
     30: </body>
     31: </html>

    This page contains three hidden fields used to pass data back and forth between the client-side code and the server-side code. It also leverages a label to surface the results to the user, and a hidden button that the client-side code uses to call a server-side function, as you will see below.

    The complete code for TaskLastModifiedApp.js is as follows:

     1: var _projDoc;
     2: var taskGuid;
     3: var projGuid;
     4: var pwaUrl;
     6: // This runs after every postback
     7: Office.initialize = function (reason) {
     8:     _projDoc = Office.context.document;
     9:     if (document.getElementById("pwaUrlHF").value == "NA") { //if this is the first run
     10:         firstRun();
     11:     }
     12:     manageTaskEventHandler('addHandlerAsync'); //need to re-register event handler after each postback
     13: }
     15: // Only need these on the first page load, not on postbacks
     16: function firstRun() {
     17:     getProjGuid();
     18:     _projDoc.getProjectFieldAsync(Office.ProjectProjectFields.ProjectServerUrl,
     19:         function (asyncResult) {
     20:             pwaUrl = asyncResult.value.fieldValue;
     21:             document.getElementById("pwaUrlHF").value = pwaUrl;
     22:         }
     23:     )
     24:     getTaskGuid();
     25: }
     27: // Get the GUID of the selected task, comes from SDK
     28: function getTaskGuid() {
     29:     var TaskLastModLabel = document.getElementById("TaskLastModLabel");
     30:     TaskLastModLabel.innerHTML = "Loading...";
     31:     _projDoc.getSelectedTaskAsync(function (asyncResult) {
     32:         taskGuid = asyncResult.value;
     33:         document.getElementById("taskGuidHF").value = taskGuid; //saves the task GUID to a hidden field to pass to the code-behind
     34:         document.getElementById("hiddenTaskChangedButton").click(); //runs the CSOM calls in the aspx.cs file
     35:     });
     36: }
     38:  // Get the GUID of the current project.
     39: function getProjGuid() {
     40:     _projDoc.getProjectFieldAsync(Office.ProjectProjectFields.GUID,
     41:         function (asyncResult) {
     42:             projGuid = asyncResult.value.fieldValue;
     43:             document.getElementById("projGuidHF").value = projGuid; //saves the project GUID to a hidden field to pass to the code-behind
     44:         }
     45:     )
     46: }
     48: // Task selection changed event handler.
     49: function onTaskSelectionChanged(eventArgs) {
     50:     getTaskGuid();
     51: }
     53: // Add or remove a task selection changed event handler.
     54: function manageTaskEventHandler(docMethod) {
     55:     manageEventHandlerAsync(
     56:         Office.EventType.TaskSelectionChanged,      // The task selection changed event.
     57:         onTaskSelectionChanged,                     // The event handler.
     58:         docMethod                // The Office.Document method to add or remove an event handler.
     59:     );
     60: }
     62: // Add or remove the specified event handler.
     63: function manageEventHandlerAsync(eventType, handler, operation, onComplete) {
     64:     _projDoc[operation]   //The operation is addHandlerAsync or removeHandlerAsync.
     65:     (
     66:         eventType,
     67:         handler,
     68:         function (asyncResult) {
     69:             // code here runs after event has been registered (or failed)
     70:         }
     71:     );
     72: }

    The first time this code runs, it pulls the PWA URL (just like we did in URLConstructor.js) and saves it to one of our hidden fields, registers a client-side event handler to capture when a new task is selected, and starts the process of connecting to PWA and pulling the data we need, which is mostly done in the code-behind file. After each postback, we do not need to recapture the PWA URL, as our ProjectContext is maintained as a static variable.

    We need to make one quick tweak to TokenHelper.cs first – change GetRealmFromTargetUrl from a private method to a public method.

    The complete code for Default.aspx.cs is as follows:

     1: using System;
     2: using System.Collections.Generic;
     3: using System.Linq;
     4: using System.Web;
     5: using System.Web.UI;
     6: using System.Web.UI.WebControls;
     7: using Microsoft.ProjectServer.Client;
     8: using Microsoft.SharePoint.Client;
     10: namespace TaskLastModifiedAppWeb.Pages
     11: {
     12:     public partial class Default : System.Web.UI.Page
     13:     {
     14:         public static ProjectContext projContext;
     15:         public static PublishedProject thisProj;
     16:         public Guid projGuid;
     18:         protected void Page_Load(object sender, EventArgs e)
     19:         {
     20:             if (!IsPostBack) //set values of hidden fields if this is the first page load
     21:             {
     22:                 projGuidHF.Value = "NA";
     23:                 taskGuidHF.Value = "NA";
     24:                 pwaUrlHF.Value = "NA";
     25:             }
     26:         }
     29:         protected void GetContexts()
     30:         {
     31:             var code = Request.QueryString["code"]; //pulls the code token from the request
     33:             string targetPwa = pwaUrlHF.Value; //pulls the PWA URL from where the Office app API stored it
     35:             Uri targetPwaUri = new Uri(targetPwa);
     37:             var tRealm = TokenHelper.GetRealmFromTargetUrl(targetPwaUri);
     39:             Uri rUri = new Uri("https://localhost:44301/pages/PostOAuth.aspx"); //hardcoded link to redirect_uri
     41:             var clientContext = TokenHelper.GetClientContextWithAuthorizationCode(targetPwa, "00000003-0000-0ff1-ce00-000000000000", code, tRealm, rUri);
     43:             projContext = GetProjectContextWithAuthorizationCode(targetPwa, "00000003-0000-0ff1-ce00-000000000000", code, tRealm, rUri);
     45:             projGuid = new Guid("{" + projGuidHF.Value + "}"); //loads the current project through CSOM
     47:             var projects = projContext.LoadQuery(projContext.Projects.Where(proj => proj.Id == projGuid));
     48:             projContext.ExecuteQuery();
     49:             thisProj = projects.First();
     50:         }
     52:         protected void OnTaskChanged(object sender, EventArgs e) //determine the selected task's last modified date
     53:         {
     54:             if (thisProj == null)
     55:             {
     56:                 GetContexts();
     57:             }
     59:             var taskGuid = new Guid(taskGuidHF.Value);
     61:             var tasks = projContext.LoadQuery(thisProj.Tasks.Where(task => task.Id == taskGuid)); //load the selected task off of the project
     62:             projContext.ExecuteQuery();
     63:             PublishedTask thisTask = tasks.First();
     64:             string dateMod = thisTask.Modified.ToString("D"); //pull out the Modified field on the task
     65:             string timeMod = thisTask.Modified.ToString("t");
     66:             TaskLastModLabel.Text = "The selected task was last modified on " + dateMod + " at " + timeMod + ".";
     67:         }
     69:         public static ProjectContext GetProjectContextWithAuthorizationCode(string targetUrl,string targetPrincipalName,string authorizationCode,string targetRealm,Uri redirectUri)
     70:         {
     71:             Uri targetUri = new Uri(targetUrl);
     73:             string accessToken =
     74:                 TokenHelper.GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
     76:             return GetProjectContextWithAccessToken(targetUrl, accessToken);
     77:         }
     79:         public static ProjectContext GetProjectContextWithAccessToken(string targetUrl, string accessToken)
     80:         {
     81:             Uri targetUri = new Uri(targetUrl);
     83:             ProjectContext projContext = new ProjectContext(targetUrl);
     85:             projContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
     86:             projContext.FormDigestHandlingEnabled = false;
     87:             projContext.ExecutingWebRequest +=
     88:                 delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
     89:                 {
     90:                     webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
     91:                         "Bearer " + accessToken;
     92:                 };
     94:             return projContext;
     95:         }
     96:     }
     97: }


    The first time the page loads, we need to initialize the hidden field values. This enables us to not set them directly in Default.aspx (and thus lose their values after a postback) and lets the client-side code distinguish between a first run load and a postback.


    This code also only runs once, assuming the current project remains loaded. This handles the last part of the OAuth flow – we use the code token from OAuthAuthorize to generate a client context and a project context using methods in TokenHelper.cs, as well as slightly modified methods GetProjectContextWithAuthorizationCode() and GetProjectContextWithAccessToken().


    This first checks to make sure we have a project loaded from which to pull data. We then read the selected task guid from the hidden field, which was updated client-side before this method was called. We use Project CSOM to load the selected task from PWA and read its Last Modified field, which is then presented to the user in a readable format using the label on Default.aspx.

    Register the App ID and App Secret

    Since we are not submitting this app to the Office Store, we need to register it on our test tenant. On your tenant, navigate to https://[your PWA site]/_layouts/15/appregnew.aspx. Generate a new App Id and App Secret, set the Title to “TaskLastModifiedApp”, set the App Domain to localhost:44301 (or wherever the app code is running), and set the Redirect URI to match the redirect_uri token value in the oAuth URL created in URLConstructor.js.


    Hit Create, and then add the App Id and App Secret to web.config in your Visual Studio solution. It should look like the following when you are done, with your values for ClientId and ClientSecret:

     1: <?xml version="1.0"?>
     3: <configuration>
     4:     <system.web>
     5:       <compilation debug="true" targetFramework="4.0" />
     6:     </system.web>
     7:   <appSettings>
     8:     <add key="ClientId" value="a9ce3d5a-bb14-4aad-9c27-41a05c473b4d" />
     9:     <add key="ClientSecret" value="hL0C8wt2PPaBYNYRMZzcUcu3C/Vv0fbm48djGzyIXOw=" />
     10:   </appSettings>
     11: </configuration>

    Time to Test!

    To run the app, just hit F5 in Visual Studio, which will launch Project Professional. Make sure to connect to a PWA profile, then load a published project (or create and publish a new one). From a task view, select the Project tab in the ribbon, hit the dropdown for Apps for Office, and click TaskLastModifiedApp.


    The app will launch in a task pane on the right side of the screen. It’ll prompt you to trust the app, quickly load, and then display the last modified date and time of the selected task.


    Select a different task, and the data will update almost instantly.



    In this blog post, you have learned how to create a task pane app in Project Professional that can display data from PWA that would not normally be visible in the client. The app uses SharePoint’s OAuthAuthorize page to request permissions from PWA and handle the authentication handshake between the app code and your online data. For more on working with OAuth, make sure to check out the relevant node in the SharePoint 2013 SDK. For more information on PWA programmability, check out the Project 2013 SDK. To learn more about writing task pane apps for the new Project, see this node in the Office 2013 SDK.

Page 1 of 1 (3 items)