建立一個以 SharePoint 為主機的專案伺服器外掛

在三種可用於自動託管、提供者託管和 SharePoint 託管Project Online () 的應用程式中,SharePoint 託管應用程式是最容易建立和部署的。 SharePoint託管的應用程式不需要OAuth認證,也不需要Azure,也不需要維護本地站點來管理由提供者託管的資源。 Visual Studio 中的 SharePoint 2013 應用程式 範本是一個方便的框架,用於開發可在 Office Store 發佈與銷售的應用程式,或部署至 SharePoint 上的私人應用程式目錄。

在專案中,狀態管理是一個流程,團隊成員可以使用 Project Web App 中的任務頁面,提交分配任務的狀態,例如每週每天工作該任務的時數。 轉讓權人 (通常是專案經理) 可以批准或拒絕該狀態。 當狀態核准後,專案會重新計算排程。 QuickStatus 應用程式會顯示分配任務,使用者可以快速更新完成百分比,並將所選任務的狀態提交審核。 雖然 Project Web App 中的任務頁面功能更多,QuickStatus 應用程式就是一個提供簡化介面的例子。

QuickStatus 應用程式是開發者的範例;它並非用於生產環境。 主要目的是展示 Project Online 應用程式開發的範例,而非打造一個完整功能的狀態應用程式。 如需更好的身份管理方法,請參閱 「下一步」中的建議。

關於狀態的一般資訊,請參見 任務進度。 欲了解更多關於為 SharePoint 與 Project Server 開發外掛的資訊,請參閱 SharePoint 外掛。

為 Project Server 2013 建立應用程式的先決條件

若要開發可部署於 Project Online 或本地安裝的 Project Server 2013 的相對簡單應用程式,您可以使用 Napa,它提供線上開發環境。 對於較複雜的應用程式、修改 Project Web App 功能區,以及開發過程中更容易除錯,你可以使用 Visual Studio 2012 或 Visual Studio 2013。 例如,在本地安裝時,你可以手動檢查 Drafts datatables 中 Project Server 資料庫的變更。 這篇文章說明如何使用 Visual Studio 進行應用程式開發。

使用 Visual Studio 開發 Project Server 應用程式需要以下步驟:

  • 請確定已在本機開發電腦上安裝最新的 Service Pack 和 Windows 更新。 作業系統可為 Windows 7、Windows 8、Windows Server 2008 或 Windows Server 2012。

  • 你必須有一台安裝了 SharePoint Server 2013 和 Project Server 2013 的電腦,並且該電腦已設定為應用程式隔離和側載應用程式。 側載讓 Visual Studio 能暫時安裝應用程式以便除錯。 你可以使用本地安裝的 SharePoint 和 Project Server。 欲了解更多資訊,請參閱 「為 SharePoint 應用程式建立本地開發環境」。

    注意事項

    對於本地安裝,在建立企業應用程式目錄 前 ,先設定一個獨立的應用程式網域。

  • 開發電腦可以是遠端電腦,安裝了 Office Developer Tools for Visual Studio 2012。 請確保您安裝的是最新版本;請參閱 Office 與 SharePoint 應用程式下載中的工具區塊。

  • 請確認你將用於開發與測試的 Project Web App 實例是否在瀏覽器中可存取。

關於使用線上工具的資訊,請參閱「 在 Microsoft 365 上建立 SharePoint 外掛的開發環境」。 想了解如何使用線上工具打造一個簡單的 Project Server 應用程式,請參考 EPMSource 部落格系列《 打造你的第一個 Project Server 應用程式》。

使用 Visual Studio 來建立專案伺服器應用程式

Visual Studio 2012 的 Office 開發者工具包含可用於 SharePoint 應用程式的範本,可搭配 Project Server 2013 使用。 當你建立應用程式解決方案時,解決方案會包含以下用於自訂程式碼的檔案:

  • AppManifest.xml 包含應用程式標題、權限請求範圍及其他屬性的設定。 程序 1 包含使用 Manifest Designer 設定屬性的步驟。

  • Default.aspx 頁面資料夾裡是應用程式的主頁。 程序二展示了如何為 QuickStatus 應用程式新增 HTML5 內容。

  • App.js 在 Scripts 資料夾中是自訂 JavaScript 程式碼的主要檔案。 程序 3 說明 QuickStatus 應用程式的 JavaScript 程式碼。

    如果你加入商業控制項,例如基於 jQuery 的格子或日期選擇器,就能在 Default.aspx 檔案中加入對額外 JavaScript 檔案的參考。

  • Content 資料夾中的 App.css 是自訂 CSS3 樣式的主要檔案。 程序 2 與程序 3 包含 QuickStatus 應用程式的層疊樣式表 (CSS) 樣式的資訊。 你可以在 Default.aspx 檔案中新增對其他 CSS 檔案的參考。

  • AppIcon.png 在圖片資料夾裡,是應用程式在 Office 商店或應用程式目錄中顯示的 96 x 96 圖示。

要修改 Project Web App 功能區,你可以新增功能區自訂動作。 QuickStatus 應用程式部分的範例程式碼包含修改後的 Default.aspx、App.js、App.css、Elements.xml 和 AppManifest.xml 檔案的完整程式碼。

程序一。 在 Visual Studio 建立應用程式專案

  1. 以管理員身份執行 Visual Studio 2012,然後在開始頁面選擇 新專案 。

  2. 在 新專案 對話框中,展開 範本、 Visual C# 和 Office/SharePoint 節點,然後選擇 應用程式。 在中間窗格頂端的目標框架下拉選單中使用預設的 .NET Framework 4.5,然後選擇 SharePoint 2013 應用程式 (見圖 1) 。

  3. 在 名稱 欄位輸入 QuickStatus,瀏覽你想儲存應用程式的位置,然後選擇 確定。

    圖 1: Creating a Project Server app in Visual Studio

    Visual Studio 建立專案伺服器應用程式在

  4. 在 「SharePoint 新應用程式 」對話框中,請填寫以下三個欄位:

    • 在最上方的文字框輸入你想讓應用程式在 Project Web App 中顯示的名稱。 例如,輸入「快速狀態更新」。

    • 要讓網站用於除錯,請輸入 Project Web App 實例的網址。 例如,輸入 https://ServerName/ProjectServerName (將 ServerName 和 ProjectServerName 替換成你自己的值) ,然後選擇 Validate。 如果一切順利,Visual Studio 顯示 連線成功。 如果收到錯誤訊息,請確認 Project Web App URL 正確,且 Project Server 電腦已設定為應用程式隔離與側載應用程式。 欲了解更多資訊,請參閱「 為 Project Server 2013 建立應用程式的前置條件 」章節。

    • 在「 你想如何為 SharePoint 主機你的應用程式 」下拉選單中,選擇 SharePoint 託管。

    注意

    如果你不小心選擇了預設的 Provider-hosted 專案類型,Visual Studio 會在解決方案中建立兩個專案: 一個是 QuickStatus 專案,另一個是 QuickStatusWeb 專案。 如果你看到兩個專案,刪除那個解決方案,重新開始。

  5. 選擇 OK 以建立 QuickStatus 解決方案、 QuickStatus 專案及預設檔案。

  6. 例如打開清單Designer檢視 (,雙擊 AppManifest.xml 檔案) 。 在 「一般 」標籤中, 標題 文字框應該會顯示你在步驟 4 輸入的應用程式名稱。 選擇 權限 標籤以新增以下應用程式權限請求 (見圖2) :

    • 在 權限請求 清單的第一列, 範圍欄位, 下拉選單中選擇 狀態狀態 。 在 權限 欄位中,選擇 提交狀態。

    • 新增一 列,範圍 為 多個專案 , 權限 為 已閱讀。

    圖 2: Setting the permission scope for a statusing app

    設定狀態應用程式的權限範圍

QuickStatus 應用程式讓 Project Web App 使用者能夠閱讀該使用者來自多個專案的指派,更改分配完成百分比,並提交更新。 圖 2 下拉選單中顯示的其他權限請求範圍並非此應用程式所必需。 權限請求範圍是應用程式代表使用者請求的權限。 如果使用者在 Project Web App 中沒有這些權限,該應用程式就無法執行。 應用程式可以有多個權限請求範圍,包括其他 SharePoint 權限,但應僅包含應用程式功能所需的最低權限。 以下是與 Project Server 相關的權限請求範圍:

  • 企業資源:資源管理員權限,用於閱讀或撰寫其他 Project Web App 使用者的資訊。

  • 多個專案:讀取或寫入多個專案,使用者擁有所請求的權限。

  • Project Server:要求應用程式使用者擁有 Project Web App 的管理員權限。

  • 報告:閱讀 ProjectData OData 服務,Project Web App (只需登入權限即可取得Project Web App) 。

  • 單一專案:讀取或寫入使用者擁有所需權限的專案。

  • 狀態狀態:提交任務狀態更新,例如工作時間、完成百分比及新任務。

  • 工作流程:如果使用者有權限執行專案伺服器工作流程,應用程式就會以該工作流程的提升權限執行。

欲了解更多關於 Project Server 2013 權限請求範圍的資訊,請參閱 Project 2013 開發者匯報中的專案應用程式章節,以及 SharePoint 2013 中的應用程式權限。

為 QuickStatus 應用程式建立 HTML 內容

在開始編寫 HTML 內容之前,先設計 QuickStatus 應用程式的使用者介面與使用者體驗 (圖 3 展示了完成頁面) 的範例。 設計也可以包含與 HTML 程式碼互動的 JavaScript 函式大綱。 一般資訊請參見 SharePoint 2013 中應用程式的使用者體驗設計。

圖 3: Design of the QuickStatus app page

QuickStatus 應用程式頁面的設計

應用程式會在頂部顯示顯示名稱,也就是 AppManifest.xml 中 標題元素的 值。

預設情況下,頁面使用 HTML5。 以下是 QuickStatus 應用程式在頁面正文中包含的主要 UI 物件的標準 HTML 元素:

  • 表單元素包含所有其他 UI 元素。

  • fieldset 元素為指派表建立容器與邊界;子圖例元素為容器提供標籤。

  • 表格元素包含標題,僅包含表格標頭。 JavaScript 函式會改變表格的標題並新增指派的列。

    注意事項

    為了方便加入分頁和排序功能,生產應用程式可能會使用商業版 jQuery 的網格控制,而非表格。

    表格包含專案名稱、任務名稱(含勾選框)、實際工作、完成百分比、剩餘工作及任務完成日期的欄位。 JavaScript 函式會建立勾選框和文字輸入欄位,顯示每個任務的完成百分比。

  • 輸入元素為文字框,為所有所選作業設定完成百分比。

  • 按鈕元素負責提交狀態變更。

  • 按鈕元素會刷新頁面。

  • 按鈕元素會從應用程式中退出,並返回 Project Web App 的任務頁面。

底部的文字框和按鈕元素都位於 div 元素中,讓 CSS 能輕鬆管理 UI 物件的位置與外觀。 JavaScript 函式會在頁面底部新增一段,顯示狀態更新成功或失敗的結果。

程序二。 建立 HTML 內容

  1. 在 Visual Studio 中,打開 Default.aspx 檔案。

    該檔案包含兩個 asp:Content 元素:帶有 ContentPlaceHolderID="PlaceHolderAdditionalPageHead" 屬性的元素會加入頁面標頭,帶有屬性 ContentPlaceHolderID="PlaceHolderMain" 的元素則置於頁面 正文 元素中。

  2. 在 <asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server"> 頁面標頭控制項中,新增對 Project Server 電腦上 PS.js 檔案的參考。 測試和除錯時,你可以用 PS.debug.js。

      <script type="text/javascript" src="/_layouts/15/ps.debug.js"></script>
    

    應用程式基礎架構使用 /_layouts/15/ IIS 中 SharePoint 網站的虛擬目錄。 實體檔案為 %ProgramFiles%\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\PS.debug.js。

    注意事項

    在將應用程式部署到生產環境前,先從腳本中移除 .debug 以提升效能的參考。

  3. 在 <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server"> 頁面主體的控制項中刪除產生的 div 元素,然後加入 UI 物件的 HTML 程式碼。 表格元素僅包含一個標頭列。 任務名稱欄位包含一個核取框輸入控制項。 標題 元素的文字會被 App.js 檔案中 getUserInfo 函式的 onGetUserNameSuccess 回調取代。

    <form>
        <fieldset>
        <legend>Select assigned tasks</legend>
        <table id="assignmentsTable">
            <caption id="tableCaption">Replace caption</caption>
            <thead>
            <tr id="headerRow">
                <th>Project name</th>
                <th><input type="checkbox" id="headercheckbox" checked="checked" />Task name</th>
                <th>Actual work</th>
                <th>% complete</th>
                <th>Remaining work</th>
                <th>Due date</th>
            </tr>
            </thead>
        </table>
        </fieldset>
        <div id="inputPercentComplete" >
        Set percent complete for all selected assignments, or leave this
        <br /> field blank and set percent complete for individual assignments: 
        <input type="text" name="percentComplete" id="pctComplete" size="4"  maxlength="4" />
        </div>
        <div id="submitResult">
        <p><button id="btnSubmitUpdate" type="button" class="bottomButtons" ></button></p>
        <p id="message"></p>
        </div>
        <div id="refreshPage">
        <p><button id="btnRefresh" type="button" class="bottomButtons" >Refresh</button></p>
        </div>
        <div id="exitPage">
        <p><button id="btnExit" type="button" class="bottomButtons" >Exit</button></p>
        </div>
    </form>
    
  4. 在 App.css 檔案中,加入 CSS 程式碼,設定 UI 元素的位置與外觀。 關於 QuickStatus 應用程式的完整 CSS 程式碼,請參閱 QuickStatus 應用程式的範例程式碼 區塊。

程序 3 新增了 JavaScript 函式,用於讀取賦值、建立表格列,以及變更和更新賦值完成百分比。 實際的步驟在開發應用程式時比較反覆,交替創造部分 HTML 程式碼,新增並測試相關樣式與 JavaScript 函式,修改或新增更多 HTML 程式碼,然後重複這個過程。

為 QuickStatus 應用程式建立 JavaScript 函式

SharePoint 應用程式的 Visual Studio 範本包含 App.js 檔案,裡面包含預設初始化程式碼,能取得 SharePoint 用戶端的上下文,並示範應用程式頁面的基本取得與設定動作。 SharePoint 用戶端 SP.js 函式庫的 JavaScript 命名空間為 SP。 因為 Project Server 應用程式使用 PS.js 函式庫,應用程式會使用 PS 命名空間取得用戶端上下文並存取 Project Server 的 JSOM。

QuickStatus 應用程式中的 JavaScript 函式包括以下內容:

  • 當文件物件模型 (DOM) 實例化時,文件 就緒 事件處理程序會執行。 準備事件處理程序執行以下四個步驟:

    1. 以專案伺服器 JSOM 的用戶端上下文及 pwaWeb 全域變數初始化 projContext 全域變數。

    2. 呼叫 getUserInfo 函式來初始化 projUser 的全域變數。

    3. 呼叫 getAssignments 函式,取得使用者指定的指派資料。

    4. 將點擊事件處理器綁定到表格標頭的勾選框,以及表格每一列的勾選框。 點擊事件處理器管理使用者在表格中選擇或清除任何勾選框時,勾選框的 勾選 屬性。

  • 如果 getAssignments 函式成功,它會呼叫 onGetAssignmentsSuccess 函式。 這個函式會在表格中為每個指派插入一列,初始化每列的 HTML 控制項,然後初始化底部按鈕的屬性。

  • OnClick 事件處理器用於 Update 按鈕,呼叫 updateAssignments 函式。 該函數會取得每個選擇作業所應用的百分比完成值;如果完成度百分比的文字框為空,則該函式會取得表格中每個選擇作業的完成百分比。 updateAssignments 函式會儲存並提交狀態更新,並在頁面底部寫入結果訊息。

程序三。 建立 JavaScript 函式

  1. 在 Visual Studio 裡,打開 App.js 檔案,然後刪除檔案中的所有內容。

  2. 新增全域變數和文件 準備事件 處理器。 文件 物件是 透過 jQuery 函式存取的。

    點擊事件處理程式用於資料表標頭勾選框,會設定列勾選框的勾選狀態。 如果所有列勾選框都被選中或全部清除,列勾選方塊的點擊事件處理器會設定標頭勾選框的勾選狀態。 點擊事件處理器也會將頁面底部的結果訊息設為空字串。

     var projContext;
     var pwaWeb;
     var projUser;
     // This code runs when the DOM is ready and creates a ProjectContext object.
     // The ProjectContext object is required to use the JSOM for Project Server.
     $(document).ready(function () {
         projContext = PS.ProjectContext.get_current();
         pwaWeb = projContext.get_web();
         getUserInfo();
         getAssignments();
         // Bind a click event handler to the table header check box, which sets the row check boxes
         // to the checked state of the header check box, and sets the results message to an empty string.
         $('#headercheckbox').live('click', function (event) {
             $('input:checkbox:not(#headercheckbox)').attr('checked', this.checked);
             $get("message").innerText = "";
         });
         // Bind a click event handler to the row check boxes. If any row check box is cleared, clear
         // the header check box. If all of the row check boxes are selected, select the header check box.
         $('input:checkbox:not(#headercheckbox)').live('click', function (event) {
             var isChecked = true;
             $('input:checkbox:not(#headercheckbox)').each(function () {
                 if (this.checked == false) isChecked = false;
                 $get("message").innerText = "";
             });
             $("#headercheckbox").attr('checked', isChecked);
         });
     });
    
  3. 新增 getUserInfo 函式,當查詢成功時會呼叫 onGetUserNameSuccess 。 onGetUserNameSuccess 函式會將標題段落的內容替換成包含使用者名稱的表格標題。

         // Get information about the current user.
         function getUserInfo() {
             projUser = pwaWeb.get_currentUser();
             projContext.load(projUser);
             projContext.executeQueryAsync(onGetUserNameSuccess,
                 // Anonymous function to execute if getUserInfo fails.
                 function (sender, args) {
                     alert('Failed to get user name. Error: ' + args.get_message());
             });
         } 
         // This function is executed if the getUserInfo call is successful.
         function onGetUserNameSuccess() {
             var prefaceInfo = 'Assignments for ' + projUser.get_title();
             $('#tableCaption').text(prefaceInfo);
         }
    
  4. 新增 getAssignments 函式,呼叫 onGetAssignmentsSuccess (查看第 5 步,) 如果任務查詢成功。 Include 選項限制查詢只能回傳指定的欄位。

     // Get the collection of assignments for the current user.
     function getAssignments() {
         assignments = PS.EnterpriseResource.getSelf(projContext).get_assignments();
         // Register the request that you want to run on the server. The optional "Include" parameter 
         // requests only the specified properties for each assignment in the collection.
         projContext.load(assignments,
             'Include(Project, Name, ActualWork, ActualWorkMilliseconds, PercentComplete, RemainingWork, Finish, Task)');
         // Run the request on the server.
         projContext.executeQueryAsync(onGetAssignmentsSuccess,
             // Anonymous function to execute if getAssignments fails.
             function (sender, args) {
                 alert('Failed to get assignments. Error: ' + args.get_message());
             });
     }
    
  5. 新增 onGetAssignmentsSuccess 函式,為每個指派新增一列。 prevProjName 變數用來判斷某列是否屬於其他專案。 若有,專案名稱會以粗體顯示;若不行,專案名稱將設為空字串。

    注意事項

    JSOM 不包含 CSOM 所包含的 TimeSpan 屬性,例如 ActualWorkTimeSpan。 相反地,JSOM 使用毫秒數的屬性,例如 PS。StatusAssignment.actualWorkMilliseconds 屬性。 取得該性質的方法是 get_actualWorkMilliseconds,回傳一個整數值。 > get_actualWork 方法回傳一個字串,例如「3h」。 你可以在 QuickStatus app 中使用任一值,但顯示方式不同。 指派查詢包含這兩個屬性,所以你可以在除錯時測試這個值。 如果你移除 actualWork 變數,也可以在 assignments 查詢中移除 ActualWork 屬性。

    最後, onGetAssignmentsSuccess 函式會用點擊事件處理器初始化 更新 按鈕和 刷新 按鈕。 Update 按鈕的文字值也可以在 HTML 程式碼中設定。

         // Get the enumerator, iterate through the assignment collection, 
         // and add each assignment to the table.
         function onGetAssignmentsSuccess(sender, args) {
             if (assignments.get_count() > 0) {
                 var assignmentsEnumerator = assignments.getEnumerator();
                 var projName = "";
                 var prevProjName = "3D2A8045-4920-4B31-B3E7-9D0C5195FC70"; // Any unique name.
                 var taskNum = 0;
                 var chkTask = "";
                 var txtPctComplete = "";
                 // Constants for creating input controls in the table.
                 var INPUTCHK = '<input type="checkbox" class="chkTask" checked="checked" id="chk';
                 var LBLCHK = '<label for="chk';
                 var INPUTTXT = '<input type="text" size="4"  maxlength="4" class="txtPctComplete" id="txt';
                 while (assignmentsEnumerator.moveNext()) {
                     var statusAssignment = assignmentsEnumerator.get_current();
                     projName = statusAssignment.get_project().get_name();
                     // Get an integer, such as 3600000.
                     var actualWorkMilliseconds = statusAssignment.get_actualWorkMilliseconds(); 
                     // Get a string, such as "1h". Not used here.
                     var actualWork = statusAssignment.get_actualWork();
                     if (projName === prevProjName) {
                         projName = "";
                     }
                     prevProjName = statusAssignment.get_project().get_name();
                     // Create a row for the assignment information.
                     var row = assignmentsTable.insertRow();
                     taskNum++;
                     // Create an HTML string with a check box and task name label, for example:
                     // <input type="checkbox" class="chkTask" checked="checked" id="chk1" /> <label for="chk1">Task 1</label>
                     chkTask = INPUTCHK + taskNum + '" /> ' + LBLCHK + taskNum + '">' 
                         + statusAssignment.get_name() + '</label>';
                     txtPctComplete = INPUTTXT + taskNum + '" />';
                     // Insert cells for the assignment properties.
                     row.insertCell().innerHTML = '<strong>' + projName + '</strong>';
                     row.insertCell().innerHTML = chkTask;
                     row.insertCell().innerText = actualWorkMilliseconds / 3600000 + 'h';
                     row.insertCell().innerHTML = txtPctComplete;
                     row.insertCell().innerText = statusAssignment.get_remainingWork();
                     row.insertCell().innerText = statusAssignment.get_finish();
                     // Initialize the percent complete cell.
                     $get("txt" + taskNum).innerText = statusAssignment.get_percentComplete() + '%'
                 }
             }
             else {
                 $('p#message').attr('style', 'color: #0f3fdb');     // Blue text.
                 $get("message").innerText = projUser.get_title() + ' has no assignments'
             }
             // Initialize the button properties.
             $get("btnSubmitUpdate").onclick = function() { updateAssignments(); };
             $get("btnSubmitUpdate").innerText = 'Update';
             $get('btnRefresh').onclick = function () { window.location.reload(true); };
             $get('btnExit').onclick = function () { exitToPwa(); };
         }
    
  6. 新增 updateAssignments 的事件處理器,點擊 Update 按鈕。 當使用者更改任務完成百分比的值,或在 percentComplete 文字框中加入值時,該值可以多種格式輸入,如「60」、「60%」或「60 %」。 getNumericValue 方法回傳輸入文字的數值。

    注意事項

    在專為生產環境設計的應用程式中,數值資訊的輸入值應包含欄位驗證及額外的錯誤檢查。

    updateAssignments 範例包含一些基本的錯誤檢查,並在頁面底部的訊息段落中顯示資訊——更新查詢成功時為綠色,若有輸入錯誤或查詢失敗則為紅色。

    在使用 submitAllStatusUpdates 方法之前,應用程式必須透過 PS 將更新儲存到伺服器 。StatusAssignmentCollection.update 方法。

         // Update all checked assignments. If the bottom percent complete field is blank,
         // use the value in the % complete field of each selected row in the table.
         function updateAssignments() {
             // Get percent complete from the bottom text box.
             var pctCompleteMain = getNumericValue($('#pctComplete').val()).trim();
             var pctComplete = pctCompleteMain;
             var assignmentsEnumerator = assignments.getEnumerator();
             var taskNum = 0;
             var taskRow = "";
             var indexPercent = "";
             var doSubmit = true;
             while (assignmentsEnumerator.moveNext()) {
                 var pctCompleteRow = "";
                 taskRow = "chk" + ++taskNum;
                 if ($get(taskRow).checked) {
                     var statusAssignment = assignmentsEnumerator.get_current();
                     if (pctCompleteMain === "") {
                         // Get percent complete from the text box field in the table row.
                         pctCompleteRow = getNumericValue($('#txt' + taskNum).val());
                         pctComplete = pctCompleteRow;
                     }
                     // If both percent complete fields are empty, show an error.
                     if (pctCompleteMain === "" && pctCompleteRow === "") {
                         $('p#message').attr('style', 'color: #e11500');     // Red text.
                         $get("message").innerHTML =
                             '<b>Error:</b> Both <i>Percent complete</i> fields are empty, in row '
                             + taskNum
                             + ' and in the bottom textbox.<br/>One of those fields must have a valid percent.'
                             + '<p>Please refresh the page and try again.</p>';
                         doSubmit = false;
                         taskNum = 0;
                         break;
                     }
                     if (doSubmit) statusAssignment.set_percentComplete(pctComplete);
                 }
             } 
             // Save and submit the assignment updates.
             if (doSubmit) {
                 assignments.update();
                 assignments.submitAllStatusUpdates();
                 projContext.executeQueryAsync(function (source, args) {
                     $('p#message').attr('style', 'color: #0faa0d');     // Green text.
                     $get("message").innerText = 'Assignments have been updated.';
                 }, function (source, args) {
                     $('p#message').attr('style', 'color: #e11500');     // Red text.
                     $get("message").innerText = 'Error updating assignments: ' + args.get_message();
                 });
             }
         }
         // Get the numeric part for percent complete, from a string. For example, with "20 %", return "20".
         function getNumericValue(pctComplete) {
             pctComplete = pctComplete.trim();
             pctComplete = pctComplete.replace(/ /g, "");    // Remove interior spaces.
             indexPercent = pctComplete.indexOf('%', 0);
             if (indexPercent > -1) pctComplete = pctComplete.substring(0, indexPercent);
             return pctComplete;
         }
    
  7. 新增 exitToPwa 函式,該函式使用 SPHostUrl 查詢字串參數來定位主機 Project Web App 網站的網址。 要回到任務頁面,請附加 "/Tasks.aspx" 網址。 例如, spHostUrl 變數會被設定為 https://ServerName/ProjectServerName/Tasks.aspx。

    getQueryStringParameter 函式會將 QuickStatus 頁面的 URL 拆分,從 URL 選項中擷取並回傳指定的參數。 以下是 該文件的範例。QuickStatus 文件的 URL 值 (一行) :

     https://app-ef98082fa37e3c.servername.officeapps.selfhost.corp.microsoft.com/pwa/
         QuickStatus/Pages/Default.aspx
         ?SPHostUrl=https%3A%2F%2Fsphvm%2D85178%2Fpwa
         &SPLanguage=en%2DUS
         &SPClientTag=1
         &SPProductNumber=15%2E0%2E4420%2E1022
         &SPAppWebUrl=https%3A%2F%2Fapp%2Def98082fa37e3c%2Eservername
             %2Eofficeapps%2Eselfhost%2Ecorp%2Emicrosoft%2Ecom%2Fpwa%2FQuickStatus
    

    對於前一個 URL,getQueryStringParameter 函式回傳 SPHostUrl 查詢字串值 https://ServerName/pwa。

         // Exit the QuickStatus page and go back to the Tasks page in Project Web App.
         function exitToPwa() {
             // Get the SharePoint host URL, which is the top page of PWA, and add the Tasks page.
             var spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'))
                             + "/Tasks.aspx";
             // Set the top window for the QuickStatus IFrame to the Tasks page.
             window.top.location.href = spHostUrl;
         }
         // Get a specified query string parameter from the {StandardTokens} URL option string.
         function getQueryStringParameter(urlParameterKey) {
             var docUrl = document.URL;
             var params = docUrl.split('?')[1].split('&');
             for (var i = 0; i < params.length; i++) {
                 var theParam = params[i].split('=');
                 if (theParam[0] == urlParameterKey)
                     return decodeURIComponent(theParam[1]);
             }
         }
    

如果你在此時發布 QuickStatus 應用程式並加入 Project Web App,該應用程式可以從網站內容頁執行,但使用者不容易取得。 為了幫助使用者找到並執行該應用程式,你可以在任務頁面的色帶上新增一個按鈕。 步驟四展示了如何新增色帶自訂動作。

Adding a ribbon custom action

功能區標籤、群組和控制Project Web App項皆在安裝於執行 Project Server 的電腦目錄中的 pwaribbon.xml 檔案[Program Files]\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\FEATURES\PWARibbon\listtemplates中指定。 為了協助設計Project Web App色帶的自訂動作,Project 2013 SDK 下載中附有一份 pwaribbon.xml 的副本。

Project Web App 在任務頁面使用不同的色帶定義,取決於 Project Web App 實例是否使用單一輸入模式,允許使用者同時輸入工時表與任務狀態的數值。 如果你有 Project Web App 的管理員權限,要決定進入模式,請在頁面右上角的下拉選單中選擇 PWA 設定。 在 PWA 設定頁面,選擇 「工時表設定與預設值」,然後查看頁面底部的 單一輸入模式 勾選框。

當單一輸入模式關閉時,任務頁面的色區由 pwaribbon.xml 的「我的工作」區域定義:

   <!-- REGION My Work Ribbon-->
   <CustomAction
      Id="Ribbon.ContextualTabs.MyWork"
      . . .

當啟用單一輸入模式時,任務頁面功能區由 pwaribbon.xml 的綁定模式區域定義:

   <!-- REGION Tied Mode Ribbon-->
   <CustomAction
      Id="Ribbon.ContextualTabs.TiedMode"
      . . .

雖然每個區域的群組與控制項外觀相似,但平分模式的控制項可能呼叫與非平行模式相同的控制函式。 步驟四說明如何在單一進入模式關閉 (且單登入模式勾選框為) 時,為QuickStatus應用程式新增按鈕控制。

注意事項

關於在 SharePoint 應用程式中為功能區或選單新增自訂動作的一般資訊,請參閱「為 SharePoint 應用程式建立自訂動作以部署」。

程序四。 在任務頁面新增功能區自訂動作

  1. 請檢視 Project Web App 中任務頁面的色帶。 選擇功能區上的 「任務 」標籤,規劃如何修改它。 遊戲分為七個群組,例如 提交、 任務和 期限。 提交群組有兩個控制項,一個是儲存按鈕,另一個是「發送狀態」下拉選單。 你可以在群組中的任何位置新增控制項,或在 任務 分頁中新增有新控制項的群組,或新增一個有自訂群組和控制項的色帶標籤。 在這個範例中,我們在 提交 群組中新增第三個按鈕,該按鈕會呼叫 QuickStatus 應用程式的網址。

  2. 在 Visual Studio 的方案總管窗格中,右鍵點擊 QuickStatus 專案,然後新增一個項目。 在 新增物品 對話框中,選擇「 功能區自訂動作 」 (見圖4) 。 例如,將自訂動作命名為 RibbonQuickStatusAction,然後選擇 新增。

    圖 4: Adding a ribbon custom action

    新增色帶自訂動作

  3. 在 「為功能區建立自訂動作 」嚮導的第一頁,選擇「 主機網路 」選項,在下拉選單中選擇 「無」 以自訂動作範圍,然後選擇 「下一步 」 (見圖 5) 。 下拉選單中的項目是與 SharePoint 相關,而非 Project Server。 我們將替換大部分產生的自訂動作 XML,使其適用於 Project Server。

    圖 5: Specifying properties for the ribbon custom action

    為色帶自訂動作指定屬性 為

  4. 在 「為功能區建立自訂動作 」的下一頁,保留所有預設值,然後選擇 完成 (見圖 6) 。 Visual Studio 建立 RibbonQuickStatusAction 資料夾,裡面包含一個 Elements.xml 檔案。

    圖 6: Specifying the settings for a button control

    指定按鈕控制設定設定

  5. 修改 Elements.xml 檔案中預設產生的程式碼,用於色帶自訂動作。 以下是預設的 XML 程式碼:

     <?xml version="1.0" encoding="utf-8"?>
     <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
         <CustomAction Id="21ea3aaf-79e5-4aac-9479-8eef14b4d9df.RibbonQuickStatusAction"
                     Location="CommandUI.Ribbon"
                     Sequence="10001"
                     Title="Invoke &apos;RibbonQuickStatusAction&apos; action">
         <CommandUIExtension>
             <!-- 
             Update the UI definitions below with the controls and the command actions
             that you want to enable for the custom action.
             -->
             <CommandUIDefinitions>
             <CommandUIDefinition Location="Ribbon.ListItem.Actions.Controls._children">
                 <Button Id="Ribbon.ListItem.Actions.RibbonQuickStatusActionButton"
                         Alt="Request RibbonQuickStatusAction"
                         Sequence="100"
                         Command="Invoke_RibbonQuickStatusActionButtonRequest"
                         LabelText="Request RibbonQuickStatusAction"
                         TemplateAlias="o1"
                         Image32by32="_layouts/15/images/placeholder32x32.png"
                         Image16by16="_layouts/15/images/placeholder16x16.png" />
             </CommandUIDefinition>
             </CommandUIDefinitions>
             <CommandUIHandlers>
             <CommandUIHandler Command="Invoke_RibbonQuickStatusActionButtonRequest"
                                 CommandAction="~appWebUrl/Pages/Default.aspx"/>
             </CommandUIHandlers>
         </CommandUIExtension >
         </CustomAction>
     </Elements>
    
    1. 在 CustomAction 元素中,刪除 Sequence 屬性和 Title 屬性。

    2. 要為提交群組新增控制項,請在 pwaribbon.xml 檔案中找到集合中的Ribbon.ContextualTabs.MyWork.Home.Groups第一個群組,該群組是以 為 的元素。 <Group Id="Ribbon.ContextualTabs.MyWork.Home.Page" Command="PageGroup" Sequence="10" Title="$Resources:pwafeatures,PAGE_PDP_CM_SUBMIT" 要將子控制項加入提交群組,以下程式碼顯示 Elements.xml 檔案中 CommandUIDefinition 元素的正確 Location 屬性:

        <CommandUIDefinitions>
          <CommandUIDefinition Location="Ribbon.ContextualTabs.MyWork.Home.Page.Controls._children">
             . . .
          </CommandUIDefinition>
        </CommandUIDefinitions>
      
    3. 更改子 按鈕 元素的屬性值如下:

           <Button Id="Ribbon.ContextualTabs.MyWork.Home.Page.QuickStatus"
                   Alt="Quick Status app"
                   Sequence="30"
                   Command="Invoke_QuickStatus"
                   LabelText="Quick Status"
                   TemplateAlias="o1"
                   Image16by16="_layouts/15/1033/images/ps16x16.png" 
                   Image16by16Left="-80"
                   Image16by16Top="-144"
                   Image32by32="_layouts/15/1033/images/ps32x32.png" 
                   Image32by32Left="-32"
                   Image32by32Top="-288" 
                   ToolTipTitle="QuickStatus"
                   ToolTipDescription="Run the QuickStatus app" />
      
      • 為了讓按鈕成為群組中的第三個控制項,Sequence 屬性可以是比現有 Send Status 控制 ((pwaribbon.xml) 中的 FlyoutAnchor 元素)值更高的Sequence="20"任何數字。 依慣例,群組與控制項的序列號為 10, 20, 30, …,使元素能插入中間位置。

      • Command 屬性指定要在 CommandUIHandler 元素中執行的指令, (參見以下步驟 5.d) 。 你可以簡化指令名稱,讓下一位開發者更容易操作。 例如 Command="Invoke_QuickStatus" ,比 更易閱讀 Command="Invoke_RibbonQuickStatusActionButtonRequest"。

      • 圖片屬性指定了 16 x 16 像素圖示,按鈕控制則指定 32 x 32 像素圖示。 在預設的 Elements.xml 檔案中, Image32by32="_layouts/15/images/placeholder32x32.png" 會指定一個橘色點。 你可以從安裝在 Project Server 電腦目錄中的圖片映射檔案 (ps16x16.png 和 ps32x32.png) [Program Files]\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\1033\IMAGES 中擷取圖示。 例如,32 x 32 像素圖示位於從左數第二欄的圖示中,圖示頂部往下第十行位於 ps32x32.png 影像映射的頂端 (圖示頂端位於第九列末尾之後;9 行 x 32 像素/行 = 288 像素) 。

      • 若要顯示按鈕控制項的工具提示,請新增 ToolTipTitle 屬性與 ToolTipDescription 屬性。

    4. 更改 CommandUIHandler 元素的屬性。 例如,確保 Command 屬性與 Button 元素的 Command 屬性值相符。 對於 CommandAction 屬性, ~appWebUrl 是 QuickStatus 網頁網址的佔位符。 當功能區按鈕呼叫 QuickStatus 應用程式時, {StandardTokens} 標記會被包含 SPHostUrl、 SPLanguage、 SPClientTag、 SPProductNumber 及 SPAppWebURL 等 URL 選項所取代。

          <CommandUIHandlers>
              <CommandUIHandler Command="Invoke_QuickStatus"
                                CommandAction="~appWebUrl/Pages/Default.aspx?{StandardTokens}"/>
          </CommandUIHandlers>
      
  6. 在方案總管中,打開 Feature1.feature 設計器,並將 RibbonQuickStatusAction 項目從解決方案面板的項目移到 Feature 面板中的項目。 如果你接著打開 Package.package 設計器, RibbonQuickStatusAction 項目會出現在 Package 面板的 Items 。

當你開發應用程式並加入功能區按鈕時,通常會測試應用程式並在 JavaScript 程式碼中設定除錯的中斷點。 當你按 F5 開始除錯時,Visual Studio 會編譯應用程式,部署到QuickStatus專案Site URL屬性中指定的網站,並顯示一個頁面詢問你是否信任該應用程式。 當你繼續操作並退出 QuickStatus 應用程式時,它會回到 Project Web App 的任務頁面。

注意事項

圖 7 顯示功能區「任務」標籤上的快速狀態按鈕已被禁用。 經過多次 Visual Studio 除錯部署後,當你繼續除錯或部署發佈的應用程式時,自訂功能區控制項可能會被阻擋。 要啟用按鈕,請在 Visual Studio 中刪除 RibbonQuickStatusAction 項目,然後建立一個名稱和 ID 不同的新功能區動作。 如果這樣還是沒解決,試著把應用程式從 Project Web App 測試實例移除,然後用不同的 App ID 重新建立應用程式。

圖 7: 查看已停用的快速狀態按鈕提示

查看被禁用按鈕的工具提示

程序 5 說明如何部署並安裝 QuickStatus 應用程式。 程序 6 顯示安裝後測試應用程式時的額外步驟。

部署 QuickStatus 應用程式

有多種方式可以將應用程式部署到 SharePoint 網頁應用程式,例如 Project Web App。 你使用的部署方式取決於你是想將應用程式發佈到私人 SharePoint 目錄還是公開 Office Store,以及 SharePoint 是安裝在本地還是線上租用。 程序 5 說明如何將 QuickStatus 應用程式部署到本地安裝,並建立私有應用程式目錄。 更多資訊請參閱「安裝與管理 SharePoint 應用程式」及「發布 SharePoint 應用程式」

注意事項

將應用程式加入 SharePoint 目錄需要 SharePoint 管理員權限。

程序五。 部署 QuickStatus 應用程式

  1. 在 Visual Studio 中,儲存所有檔案,然後在方案總管中右鍵點擊 QuickStatus 專案,選擇發佈。

  2. 由於 QuickStatus 應用程式是 SharePoint 主機,發佈選項非常有限 (見圖 8) 。 在 Office 與 SharePoint 發佈應用程式 對話框中,選擇 完成。

    圖 8. 發布 QuickStatus 應用程式

    使用 發佈精靈

  3. 將目錄中的 ~\QuickStatus\bin\Debug\app.publish\1.0.0.0 QuickStatus.app 檔案複製到本地電腦 (方便的目錄,或複製到 SharePoint 電腦進行本地安裝) 。

  4. 在 SharePoint 中央管理中,選擇快速啟動中的 應用程式 ,然後選擇 管理應用程式目錄。

  5. 若應用程式目錄不存在,請依照 SharePoint 2013 中「管理應用程式目錄」中「為網頁應用程式配置應用程式目錄網站」部分,建立該應用程式目錄的網站集合。

    如果有應用程式目錄,請在管理應用程式目錄頁面中導覽該網站網址。 例如,在接下來的步驟中,應用程式目錄網站為 https://ServerName/sites/TestApps。

  6. 在應用程式目錄頁面,選擇「 SharePoint 應用程式 」的快速啟動。 在 SharePoint 應用程式頁面,功能區的 FILES 標籤中,選擇 「上傳文件」。

  7. 在 「新增文件 」對話框中,瀏覽 QuickStatus.app 檔案,為版本加上註解,然後選擇 確定。

  8. 新增應用程式時,也可以加入本地應用程式描述、圖示及其他資訊。 在 SharePoint QuickStatus.app 的應用程式 對話框中,加入你想在 SharePoint 網站集合中顯示該應用程式的資訊。 例如,請補充以下資訊:

    1. 簡短說明 欄位:輸入快速狀態測試應用程式。

    2. 描述 欄位:輸入「測試應用程式」以更新多個專案任務的完成百分比。

    3. 圖示網址 欄位:將應用程式圖示的 96 x 96 像素圖片加入應用程式目錄的網站資產。 例如,請在https://ServerName/sites/TestApps設定下拉選單中選擇「網站內容」,選擇「網站資產」,然後新增 quickStatusApp.png 圖片。 右鍵點選 quickStatusApp 項目,選擇屬性,然後在屬性對話框中複製地址 (網址) 值。 例如,複製 https://ServerName/sites/TestApps/SiteAssets/QuickStatusApp.png,然後貼上該值到 圖示網址 網址欄位。 輸入圖示的描述,例如 (如圖9) ,輸入QuickStatus應用程式圖示。 測試該網址是否有效。

      Figure 9. 為 QuickStatus 應用程式新增圖示網址

      在 SharePoint 中設定應用程式的屬性 在

    4. 類別 欄位:選擇現有類別,或指定你自己的值。 例如,輸入「狀態狀態」。

      注意事項

      一個叫 做「狀態」 的分類只是用來測試。 專案伺服器應用程式的典型類別是 專案管理。

    5. 出版商名稱 欄位:輸入出版商名稱。 在這個範例中,輸入 Project SDK。

    6. 啟用欄位:若要讓 Project Web App 網站管理員看到該應用程式以便安裝,請選擇啟用的核取方塊。

    7. 額外欄位為可選。 例如,你可以為應用程式細節頁面新增支援網址和多張說明圖片。 在圖 9 中, 圖片網址 1 欄位包含應用程式截圖的網址及截圖描述。

    8. 在 SharePoint 應用程式 - QuickStatus.app 對話框中,選擇 「儲存」。 在圖 9 中,SharePoint 應用程式庫中的快速狀態更新項目已被勾選以便編輯,因此在對話框功能區的編輯標籤中,你可以選擇簽到來完成該程序 (見圖 10) 。

      Figure 10. QuickStatus 應用程式已加入 SharePoint 應用程式函式庫。

      QuickStatus 應用程式已加入 QuickStatus SharePoint

  9. 在 Project Web App 的設定下拉選單中,選擇新增應用程式。 在「你的應用程式」頁面,快速啟動時,選擇「從你的組織中」,然後選擇快速狀態更新應用程式的「應用程式詳情」。 圖 11 顯示了詳細頁面,裡面有應用程式圖示、截圖及你在前一步新增的其他資訊。

    Figure 11. 使用 Project Web App 中的快速狀態更新詳情頁面

    將 QuickStatus 應用程式加入 Project Web App

  10. 在快速狀態更新詳情頁面,選擇新增。 Project Web App會顯示一個對話框,列出 QuickStatus 應用程式可執行的操作 (見圖 12) 。 操作清單來自 AppManifest.xml 檔案中的 AppPermissionRequest 元素。

    圖 12. 驗證你是否信任快速狀態應用程式

    驗證QuickStatus應用程式的

  11. 在「 你信任快速狀態更新嗎 」對話框中,選擇 「信任它」。 該應用程式已加入Project Web App網站內容頁 (見圖13) 。

    圖 13. 在網站內容頁瀏覽快速狀態應用程式

    在網站內容中查看 QuickStatus 應用程式 在

在網站內容頁面,您可以選擇 快速狀態更新 圖示來執行該應用程式。

注意事項

如需提供應用程式相關資訊的額外指令,請在網站內容頁選擇包含快速狀態更新名稱及省略號 (...) 的區域。你可以查看該應用程式的關於頁面、查看包含應用程式錯誤資訊的應用程式細節頁面、檢視應用程式權限頁面,或是將該應用程式從 Project Web App 中移除。

在Project Web App (的任務頁面,見圖14) ,功能區上的快速狀態按鈕應該已啟用。 如果快速 狀態 按鈕被停用,請嘗試圖7備註中描述的操作。

Figure 14. Starting the QuickStatus app from the TASKS tab

從 TASKS 標籤啟動 QuickStatus 應用程式

程序6展示了一些可以用QuickStatus應用程式做的測試。

測試 QuickStatus 應用程式

使用者在 QuickStatus 應用程式中嘗試的每一項操作,都應在 Project Server 的測試安裝中進行測試,然後再部署到生產伺服器或 Project Online 的生產租戶。 測試安裝讓你可以更改和刪除使用者的指派,而不會影響實際專案。 測試也應涉及多個擁有不同權限的使用者,如管理員、專案經理和團隊成員。 徹底的測試可以發現應用程式中應該做的變更,這些在開發時測試時並不明顯。 程序6列出了 QuickStatus 應用程式的多項測試,但未包含完整的測試系列。

程序六。 測試 QuickStatus 應用程式

  1. 在沒有作業的情況下執行 QuickStatus 應用程式。 應用程式應該會在頁面底部顯示藍色訊息,例如「使用者名稱沒有指派」。

    選擇 更新,訊息會變成綠色 ,分配已更新。

    注意事項

    應用程式的行為應該改變,當沒有指派時, 更新按鈕會 被停用。

  2. 在使用者同時擁有多個專案的應用程式中,有些作業尚未完成。 請注意應用程式的外觀,並依照 (見圖15) 執行以下動作:

    1. onGetAssignmentsSuccess 函式會在表格中為當前使用者的每個指派建立一列。 每個專案的第一個作業名稱只會以粗體字顯示一次。

    2. 清除 任務名稱 欄位標頭中的勾選框。 表格標頭點擊事件處理程式會清除任務列中所有其他勾選框。

    3. 選擇所有任務。 每列的點擊事件處理器會判斷是否選取所有列,若選中,則選擇 任務名稱 欄位標頭。

    4. 再次清除所有勾選框,然後選擇一個還有剩餘作業的作業。 例如,圖15顯示頂端任務T1還有20%的工作待完成。

    5. 在 「設定百分比完成度 」文字框中,輸入 80,然後選擇 更新。 頁面底部應該會顯示綠色訊息,標題為「 作業已更新」。

      圖 15. Updating an assignment in the QuickStatus app

      在 QuickStatus 應用程式中更新作業 在

  3. 選擇 刷新 (見圖16) 。 所有任務都重新選取,頂端任務顯示完成率為 80%。

    圖 16. 重新整理快速狀態更新頁面

    重新整理快速狀態頁面

  4. 清除所有勾選框,然後選擇另一個任務。 例如,從 PWA 選擇新任務。 將 「設定完成百分比」 文字框留空,刪除所選任務「 百分比完成 度」欄位中的所有文字,然後選擇 更新。 由於兩個文字框皆為空,應用程式會顯示紅色錯誤訊息 (見圖17) 。

    Figure 17. Testing the error message

    測試錯誤訊息

  5. 將前一個任務更新為完成 80%,然後選擇 退出。 exitToPwa 功能會將瀏覽器視窗位置改為 SharePoint 主機應用程式中的任務頁面, (也就是說,URL 會改成 <https://ServerName/pwa/Tasks.aspx>) 。 圖18顯示 T1 任務與 PWA新任務 各完成80%。

    Figure 18. 在 Project Web App 中驗證任務是否已更新

    在 Project Web App 中驗證已更新的任務

  6. 在更新狀態顯示於 Project 專業版 2013 之前,變更必須先提交審核,並由專案經理批准。

測試顯示, QuickStatus 應用程式還需要做幾項調整以提升使用便利性。 例如:

  • 還應該有額外的錯誤檢查和文字框值的驗證。 目前,使用者可以輸入非數字值或負值表示完成度百分比,這會導致不友善的錯誤訊息。 例如,負值時,錯誤訊息為 Error updateing assignments: PJClientCallableException: StatusingSetDataValueInvalid。

  • 空白文字框的錯誤訊息除了列號外,還可能列出專案和任務。

  • 成功訊息可能包含已更新任務清單;或者如果 updateAssignments 功能成功,則能自動刷新頁面,並以不同顏色和粗體字型顯示更新的任務或百分比。

  • 為避免表格過大,作業表應限制於未完成 100% 的任務。 或者,加入顯示所有任務的選項。 這個問題也可以透過使用 jQuery 的網格取代表格來解決,這樣你就能輕鬆實作篩選和網格分頁。

  • 由於 QuickStatus 應用程式不會提交狀態,功能區的 TASKS 標籤上的快速狀態圖示更合理地應該是任務群組的第一個圖示,而非提交群組的最後一個。

  • 由於 onGetAssignmentsSuccess 函式初始化了 btnSubmitUpdate 按鈕的文字,但其他按鈕的文字值是以 HTML 初始化,因此在 getAssignments 函式執行時,頁面會保持部分初始化狀態。 如果文字值全部以 HTML 初始化,頁面上的按鈕看起來會更一致。

最重要的是, QuickStatus 應用程式所採用的修改作業完成百分比的方式,應該在正式版應用程式中進行修正。 欲了解更多資訊,請參閱 「下一步」 章節。

QuickStatus 應用程式的範例程式碼

Default.aspx檔案

以下程式碼出現在 Pages\Default.aspxQuickStatus 專案的檔案中:

    <%-- The following lines are ASP.NET directives needed when using SharePoint components --%>
    <%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, 
    Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>
    <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, 
    Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, 
    Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, 
    Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%-- The markup and script in the following Content element will be placed in the <head> of the page.
        For production deployment, change the .debug.js JavaScript references to .js. --%>
    <asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.debug.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.debug.js"></script>
    <script type="text/javascript" src="/_layouts/15/ps.debug.js"></script>
    <!-- CSS styles -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
    <!-- Add your JavaScript to the following file -->
    <script type="text/javascript" src="../Scripts/App.js"></script>
    </asp:Content>
    <%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
    <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <form>
        <fieldset>
        <legend>Select assigned tasks</legend>
        <table id="assignmentsTable">
            <caption id="tableCaption">Replace caption</caption>
            <thead>
            <tr id="headerRow">
                <th>Project name</th>
                <th><input type="checkbox" id="headercheckbox" checked="checked" />Task name</th>
                <th>Actual work</th>
                <th>% complete</th>
                <th>Remaining work</th>
                <th>Due date</th>
            </tr>
            </thead>
        </table>
        </fieldset>
        <div id="inputPercentComplete" >
        Set percent complete for all selected assignments, or leave this
        <br /> field blank and set percent complete for individual assignments: 
        <input type="text" name="percentComplete" id="pctComplete" size="4"  maxlength="4" />
        </div>
        <div id="submitResult">
        <p><button id="btnSubmitUpdate" type="button" class="bottomButtons" ></button></p>
        <p id="message"></p>
        </div>
        <div id="refreshPage">
        <p><button id="btnRefresh" type="button" class="bottomButtons" >Refresh</button></p>
        </div>
    <div id="exitPage">
        <p><button id="btnExit" type="button" class="bottomButtons" >Exit</button></p>
    </div>
    </form>
    </asp:Content>

App.js 檔案

以下程式碼出現在 Scripts\App.jsQuickStatus 專案的檔案中:

    var projContext;
    var pwaWeb;
    var projUser;
    // This code runs when the DOM is ready and creates a ProjectContext object.
    // The ProjectContext object is required to use the JSOM for Project Server.
    $(document).ready(function () {
        projContext = PS.ProjectContext.get_current();
        pwaWeb = projContext.get_web();
        getUserInfo();
        getAssignments();
        // Bind a click event handler to the table header check box, which sets the row check boxes
        // to the selected state of the header check box, and sets the results message to an empty string.
        $('#headercheckbox').live('click', function (event) {
            $('input:checkbox:not(#headercheckbox)').attr('checked', this.checked);
            $get("message").innerText = "";
        });
        // Bind a click event handler to the row check boxes. If any row check box is cleared, clear
        // the header check box. If all of the row check boxes are selected, select the header check box.
        $('input:checkbox:not(#headercheckbox)').live('click', function (event) {
            var isChecked = true;
            $('input:checkbox:not(#headercheckbox)').each(function () {
                if (this.checked == false) isChecked = false;
                $get("message").innerText = "";
            });
            $("#headercheckbox").attr('checked', isChecked);
        });
    });
    // Get information about the current user.
    function getUserInfo() {
        projUser = pwaWeb.get_currentUser();
        projContext.load(projUser);
        projContext.executeQueryAsync(onGetUserNameSuccess,
            // Anonymous function to execute if getUserInfo fails.
            function (sender, args) {
                alert('Failed to get user name. Error: ' + args.get_message());
        });
    }
    // This function is executed if the getUserInfo call is successful.
    // Replace the contents of the 'caption' paragraph with the project user name.
    function onGetUserNameSuccess() {
        var prefaceInfo = 'Assignments for ' + projUser.get_title();
        $('#tableCaption').text(prefaceInfo);
    }
    // Get the collection of assignments for the current user.
    function getAssignments() {
        assignments = PS.EnterpriseResource.getSelf(projContext).get_assignments();
        // Register the request that you want to run on the server. The optional "Include" parameter 
        // requests only the specified properties for each assignment in the collection.
        projContext.load(assignments,
            'Include(Project, Name, ActualWork, ActualWorkMilliseconds, PercentComplete, RemainingWork, Finish, Task)');
        // Run the request on the server.
        projContext.executeQueryAsync(onGetAssignmentsSuccess,
            // Anonymous function to execute if getAssignments fails.
            function (sender, args) {
                alert('Failed to get assignments. Error: ' + args.get_message());
            });
    }
    // Get the enumerator, iterate through the assignment collection, 
    // and add each assignment to the table.
    function onGetAssignmentsSuccess(sender, args) {
        if (assignments.get_count() > 0) {
            var assignmentsEnumerator = assignments.getEnumerator();
            var projName = "";
            var prevProjName = "3D2A8045-4920-4B31-B3E7-9D0C5195FC70"; // Any unique name.
            var taskNum = 0;
            var chkTask = "";
            var txtPctComplete = "";
            // Constants for creating input controls in the table.
            var INPUTCHK = '<input type="checkbox" class="chkTask" checked="checked" id="chk';
            var LBLCHK = '<label for="chk';
            var INPUTTXT = '<input type="text" size="4"  maxlength="4" class="txtPctComplete" id="txt';
            while (assignmentsEnumerator.moveNext()) {
                var statusAssignment = assignmentsEnumerator.get_current();
                projName = statusAssignment.get_project().get_name();
                // Get an integer value for the number of milliseconds of actual work, such as 3600000.
                var actualWorkMilliseconds = statusAssignment.get_actualWorkMilliseconds();
                // Get a string value for the assignment actual work, such as "1h". Not used here.
                var actualWork = statusAssignment.get_actualWork();                         
                if (projName === prevProjName) {
                    projName = "";
                }
                prevProjName = statusAssignment.get_project().get_name();
                // Create a row for the assignment information.
                var row = assignmentsTable.insertRow();
                taskNum++;
                // Create an HTML string with a check box and task name label, for example:
                //     <input type="checkbox" class="chkTask" checked="checked" id="chk1" /> 
                //     <label for="chk1">Task 1</label>
                chkTask = INPUTCHK + taskNum + '" /> ' + LBLCHK + taskNum + '">'
                    + statusAssignment.get_name() + '</label>';
                txtPctComplete = INPUTTXT + taskNum + '" />';
                // Insert cells for the assignment properties.
                row.insertCell().innerHTML = '<strong>' + projName + '</strong>';
                row.insertCell().innerHTML = chkTask;
                row.insertCell().innerText = actualWorkMilliseconds / 3600000 + 'h';
                row.insertCell().innerHTML = txtPctComplete;
                row.insertCell().innerText = statusAssignment.get_remainingWork();
                row.insertCell().innerText = statusAssignment.get_finish();
                // Initialize the percent complete cell.
                $get("txt" + taskNum).innerText = statusAssignment.get_percentComplete() + '%'
            }
        }
        else {
            $('p#message').attr('style', 'color: #0f3fdb');     // Blue text.
            $get("message").innerText = projUser.get_title() + ' has no assignments'
        }
        // Initialize the button properties.
        $get("btnSubmitUpdate").onclick = function() { updateAssignments(); };
        $get("btnSubmitUpdate").innerText = 'Update';
        $get('btnRefresh').onclick = function () { window.location.reload(true); };
        $get('btnExit').onclick = function () { exitToPwa(); };
    }
    // Update all selected assignments. If the bottom percent complete field is blank,
    // use the value in the % complete field of each selected row in the table.
    function updateAssignments() {
        // Get percent complete from the bottom text box.
        var pctCompleteMain = getNumericValue($('#pctComplete').val()).trim();
        var pctComplete = pctCompleteMain;
        var assignmentsEnumerator = assignments.getEnumerator();
        var taskNum = 0;
        var taskRow = "";
        var indexPercent = "";
        var doSubmit = true;
        while (assignmentsEnumerator.moveNext()) {
            var pctCompleteRow = "";
            taskRow = "chk" + ++taskNum;
            if ($get(taskRow).checked) {
                var statusAssignment = assignmentsEnumerator.get_current();
                if (pctCompleteMain === "") {
                    // Get percent complete from the text box field in the table row.
                    pctCompleteRow = getNumericValue($('#txt' + taskNum).val());
                    pctComplete = pctCompleteRow;
                }
                // If both percent complete fields are empty, show an error.
                if (pctCompleteMain === "" && pctCompleteRow === "") {
                    $('p#message').attr('style', 'color: #e11500');     // Red text.
                    $get("message").innerHTML =
                        '<b>Error:</b> Both <i>Percent complete</i> fields are empty, in row '
                        + taskNum
                        + ' and in the bottom textbox.<br/>One of those fields must have a valid percent.'
                        + '<p>Please refresh the page and try again.</p>';
                    doSubmit = false;
                    taskNum = 0;
                    break;
                }
                if (doSubmit) statusAssignment.set_percentComplete(pctComplete);
            }
        } 
        // Save and submit the assignment updates.
        if (doSubmit) {
            assignments.update();
            assignments.submitAllStatusUpdates();
            projContext.executeQueryAsync(function (source, args) {
                $('p#message').attr('style', 'color: #0faa0d');     // Green text.
                $get("message").innerText = 'Assignments have been updated.';
            }, function (source, args) {
                $('p#message').attr('style', 'color: #e11500');     // Red text.
                $get("message").innerText = 'Error updating assignments: ' + args.get_message();
            });
        }
    }
    // Get the numeric part for percent complete, from a string. 
    // For example, with "20 %", return "20".
    function getNumericValue(pctComplete) {
        pctComplete = pctComplete.trim();
        pctComplete = pctComplete.replace(/ /g, "");    // Remove interior spaces.
        indexPercent = pctComplete.indexOf('%', 0);
        if (indexPercent > -1) pctComplete = pctComplete.substring(0, indexPercent);
        return pctComplete;
    }
    // Exit the QuickStatus page and go back to the Tasks page in Project Web App.
    function exitToPwa() {
        // Get the SharePoint host URL, which is the top page of PWA, and add the Tasks page.
        var spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'))
                        + "/Tasks.aspx";
        // Set the top window for the QuickStatus IFrame to the Tasks page.
        window.top.location.href = spHostUrl;
    }
    // Get a specified query string parameter from the {StandardTokens} URL option string.
    function getQueryStringParameter(urlParameterKey) {
        var docUrl = document.URL;
        var params = docUrl.split('?')[1].split('&');
        for (var i = 0; i < params.length; i++) {
            var theParam = params[i].split('=');
            if (theParam[0] == urlParameterKey)
                return decodeURIComponent(theParam[1]);
        }
    }

App.css檔案

以下 CSS 程式碼收錄 Content\App.css 於 QuickStatus 專案檔案中:

    /* Custom styles for the QuickStatus app. */
    /*============= Table elements ========================================*/
    table {
        width: 90%;
    }
    caption {
        font-size: 16px;
        padding-bottom: 5px;
        font-weight: bold;
        color: gray;
    }
    table th {
        background-color: gray;
        color: white;
    }
    table td, th {
        width: auto;
        text-align: left;
        padding: 2px;
        border: solid 1px whitesmoke;
        color: gray;
    }
    /*=== Class for check boxes added to rows 
    */
    .chkTask {
        width: 12px;
        height: 12px;
        color: gray;
    }
    /*========== DIV id for the Percent Complete text box ================*/
    #inputPercentComplete {
        position: fixed;
        top: auto;
        height: auto;
        padding-top: 20px;
        margin-left: 30px;
    }
    /*========== DIV id for the Submit Result button ====================*/
    #submitResult {
        position: fixed;
        top: auto;
        height: auto;
        padding-top: 60px;
    }
    /*========== DIV id for the Refresh Page button ====================*/
    #refreshPage {
        position: fixed;
        top: auto;
        height: auto;
        padding-top: 60px;
        margin-left: 120px;
    }
    /*========== DIV id for the Exit Page button ====================*/
    #exitPage {
        position: fixed;
        top: auto;
        height: auto;
        padding-top: 60px;
        margin-left: 240px;
    }
    /*========== Class for the buttons at the bottom of the page =======*/
    .bottomButtons {
        color: gray;
        font-weight: bold; 
        font-size: 12px; 
        border-color: darkgreen;
        border-width: thin;
    }

Elements.xml 申請緞帶

以下 XML 定義,針對功能區 TASKS 標籤中新增按鈕,位於 RibbonQuickStatusAction\Elements.xmlQuickStatus 專案的檔案中:

    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <CustomAction Id="21ea3aaf-79e5-4aac-9479-8eef14b4d9df.RibbonQuickStatusAction"
                    Location="CommandUI.Ribbon">
        <CommandUIExtension>
        <!-- 
        Add a button that invokes the QuickStatus app. The Quick Status button is displayed as  
        the third control in the Page group (the group title is "Submit").
        -->
        <CommandUIDefinitions>
            <CommandUIDefinition Location="Ribbon.ContextualTabs.MyWork.Home.Page.Controls._children">
            <Button Id="Ribbon.ContextualTabs.MyWork.Home.Page.QuickStatus"
                    Alt="Quick Status app"
                    Sequence="30"
                    Command="Invokae_QuickStatus"
                    LabelText="Quick Status"
                    TemplateAlias="o1"
                    Image16by16="_layouts/15/1033/images/ps16x16.png" 
                    Image16by16Left="-80"
                    Image16by16Top="-144"
                    Image32by32="_layouts/15/1033/images/ps32x32.png" 
                    Image32by32Left="-32"
                    Image32by32Top="-288" 
                    ToolTipTitle="Quick Status"
                    ToolTipDescription="Run the QuickStatus app" />
            </CommandUIDefinition>
        </CommandUIDefinitions>
        <CommandUIHandlers>
            <CommandUIHandler Command="Invoke_QuickStatus"
                            CommandAction="~appWebUrl/Pages/Default.aspx?{StandardTokens}"/>
        </CommandUIHandlers>
        </CommandUIExtension >
    </CustomAction>
    </Elements>

AppManifest.xml 檔案

以下是 QuickStatus 專案應用程式清單的 XML,其中包含更新多個專案中應用程式使用者指派狀態所需的兩個權限請求範圍:

    <?xml version="1.0" encoding="utf-8" ?>
    <!--Created:cb85b80c-f585-40ff-8bfc-12ff4d0e34a9-->
    <App xmlns="http://schemas.microsoft.com/sharepoint/2012/app/manifest"
        Name="QuickStatus"
        ProductID="{bbc497e7-1221-4d7b-a0ae-141a99546008}"
        Version="1.0.0.0"
        SharePointMinVersion="15.0.0.0"
    >
    <Properties>
        <Title>Quick Status Update</Title>
        <StartPage>~appWebUrl/Pages/Default.aspx?{StandardTokens}</StartPage>
    </Properties>
    <AppPrincipal>
        <Internal />
    </AppPrincipal>
    <AppPermissionRequests>
        <AppPermissionRequest Scope="https://sharepoint/projectserver/statusing" Right="SubmitStatus" />
        <AppPermissionRequest Scope="https://sharepoint/projectserver/projects" Right="Read" />
    </AppPermissionRequests>
    </App>

AppIcon.png 檔案

QuickStatus 應用程式的完整 Visual Studio 解決方案包含自訂的 AppIcon.png 檔案。 該解決方案將包含在 Project 2013 SDK 下載中。

後續步驟

QuickStatus 應用程式是一個相對簡單的範例,說明如何撰寫可在 Project Server 2013 和 Project Online 上安裝的應用程式。 「測試 QuickStatus 應用程式」部分列出了多項可改進以提升可用性的方案。 QuickStatus 應用程式使用 JavaScript 函式來更新 Project Web App 的作業狀態。 但更改任務完成百分比並非建議的專案管理做法。 另一種方法是更新實際開始日期及分配任務的剩餘時間。 關於這些議題的討論,請參閱MPUG電子報中的 「更新更好 」。

另請參閱