你可以使用 Project Server 2013 用戶端物件模型 (CSOM) ,開發 .NET Framework 4 的Project Online及本地解決方案。 本文說明如何建立一個主控台應用程式,利用 CSOM 來建立並發佈專案。 發佈專案後,應用程式會等待專案伺服器佇列服務完成發佈動作,然後列出已發佈的專案。
關於專案伺服器 CSOM 的一般介紹,請參見 Project 2013 開發者匯報。 關於 CSOM 命名空間中的參考主題,請參見 Microsoft.ProjectServer.Client。
在 Visual Studio 建立 CSOM 專案
你可以使用 Visual Studio 2010 或 Visual Studio 2012 來開發使用 Project Server CSOM 的解決方案。 專案伺服器 CSOM 包含三個組件,用於使用 .NET Framework 4 開發客戶端應用程式、Microsoft Silverlight 應用程式及 Windows Phone 8 應用程式。 CSOM 也包含一個用於網頁應用程式開發的 JavaScript 檔案,詳見 Microsoft.ProjectServer.Client。
你可以從 Project Server 電腦或 Project 2013 SDK 下載的 CSOM 組件複製到遠端開發電腦。 本主題中描述的 QueueCreateProject 主控台應用程式並非 Silverlight 應用程式或 Windows Phone 8 應用程式,因此你需要 Microsoft.ProjectServer.Client.dll 組合語言。 由於 CSOM 獨立於基於 WCF 或基於 ASMX 的專案伺服器介面 (PSI) ,因此您不必為 PSI 設定服務參考,也不必使用 Microsoft.Office.Project.Server.Library 命名空間。
QueueCreateProject 應用程式使用命令列參數來表示要建立的專案名稱及佇列逾時限制。 在程序 1 中,建立基本的主控台應用程式,新增一個解析命令列的例程,並在命令列有錯誤時加入使用訊息。
程序一。 在 Visual Studio 中建立 CSOM 專案
把資料夾裡
%ProgramFiles%\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\的 Microsoft.ProjectServer.Client.dll 組件複製到你的開發電腦。 將組裝檔複製到方便放置其他 Project Server 和 SharePoint 參考組譯套件,例如C:\Project\Assemblies。將 Microsoft.SharePoint.Client.dll 組件和 Microsoft.SharePoint.Client.Runtime.dll 組件從同一個來源資料夾複製到你的開發電腦。 Microsoft.ProjectServer.Client.dll assembly 依賴相關的 SharePoint assembly。
在 Visual Studio 建立一個 Windows 主控台應用程式,並將目標框架設為 .NET Framework 4。 例如,將應用程式命名為 QueueCreateProject。
注意事項
如果你忘了設定正確的目標,在 Visual Studio 建立專案後,請在專案選單中開啟 QueueCreateProject 屬性。 在應用程式標籤的目標框架下拉選單中,選擇 .NET Framework 4。 請勿使用 .NET Framework 4 用戶端設定檔。
在方案總管中,請設定以下組件的參考:
- Microsoft.ProjectServer.Client.dll
- Microsoft.SharePoint.Client.dll
- Microsoft.SharePoint.Client.Runtime.dll
在Program.cs檔案中,請編輯
using語句,如下。using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.ProjectServer.Client;新增解析專案名稱命令列參數、隊列逾時秒數、顯示使用資訊及退出應用程式的方法。 將 Program.cs 檔案中的主程式碼主體替換為以下程式碼。
namespace QueueCreateProject { class Program { static void Main(string[] args) { if (!ParseCommandLine(args)) { Usage(); ExitApp(); } /* Add calls to methods here to get the project context and create a project. */ ExitApp(); } // Parse the command line. Return true if there are no errors. private static bool ParseCommandLine(string[] args) { bool error = false; int argsLen = args.Length; try { for (int i = 0; i < argsLen; i++) { if (error) break; if (args[i].StartsWith("-") || args[i].StartsWith("/")) args[i] = "*" + args[i].Substring(1).ToLower(); switch (args[i]) { case "*projname": case "*n": if (++i >= argsLen) return false; projName = args[i]; break; case "*timeout": case "*t": if (++i >= argsLen) return false; timeoutSeconds = Convert.ToInt32(args[i]); break; case "*?": default: error = true; break; } } } catch (FormatException) { error = true; } if (string.IsNullOrEmpty(projName)) error = true; return !error; } private static void Usage() { string example = "Usage: QueueCreateProject -projName | -n \"New project name\" [-timeout | -t sec]"; example += "\nExample: QueueCreateProject -n \"My new project\""; example += "\nDefault timeout seconds = " + timeoutSeconds.ToString(); Console.WriteLine(example); } private static void ExitApp() { Console.Write("\nPress any key to exit... "); Console.ReadKey(true); Environment.Exit(0); } } }
了解專案背景
CSOM 開發要求 ProjectContext 物件以 Project Web App URL 初始化。 程序 2 中的程式碼使用 pwaPath 常數。 如果你打算用這個應用程式支援多個 Project Web App 實例,可以把 pwaPath 設為變數,並新增一個命令列參數。
程序二。 為了了解專案背景
新增 QueueCreateProject 應用程式會使用的程式類別常數與變數。 除了 Project Web App URL 外,應用程式還會使用預設企業專案類型名稱 (EPT) 、要建立的專案名稱,以及最大隊列逾時時間(秒數)。 在這種情況下, timeoutSeconds 變數可以讓你測試各種逾時值如何影響應用程式。 ProjectContext 物件是存取 CSOM 的主要物件。
private const string pwaPath = "https://ServerName /pwa/"; // Change the path to your Project Web App instance. private static string basicEpt = "Enterprise Project"; // Basic enterprise project type. private static string projName = string.Empty; private static int timeoutSeconds = 10; // The maximum wait time for a queue job, in seconds. private static ProjectContext projContext;請將註解替換
/* Add calls to methods here to get the project context and create a project. */成以下程式碼。 Microsoft.ProjectServer.Client.ProjectContext 物件以 Project Web App URL 初始化。 CreateTestProject 方法與 ListPublishedProjects 方法分別在程序 4 與程序 5 中展示。projContext = new ProjectContext(pwaPath); if (CreateTestProject()) ListPublishedProjects(); else Console.WriteLine("\nProject creation failed: {0}", projName);
取得企業專案類型
QueueCreateProject 範例應用程式明確選擇企業專案 EPT,以展示應用程式如何為專案選擇 EPT。 若專案建立資訊未指定 EPT GUID,應用程式將使用預設的 EPT。 GetEptUid 方法被程序 4 描述的 CreateTestProject 方法所使用。
GetEptUid 方法會查詢 ProjectContext 物件,尋找 EPT 名稱等於指定名稱的 EnterpriseProjectTypes 集合。 執行查詢後,eptUid 變數會被設定為 eptList 集合中第一個 EnterpriseProjectType 物件的 GUID。 由於 EPT 名稱是唯一的,只有一個 EnterpriseProjectType 物件擁有指定的名稱。
程序三。 要取得新專案 EPT 的 GUID
將 GetEptUid 方法加入 程式 類別。
// Get the GUID of the specified enterprise project type. private static Guid GetEptUid(string eptName) { Guid eptUid = Guid.Empty; try { // Get the list of EPTs that have the specified name. // If the EPT name exists, the list will contain only one EPT. var eptList = projContext.LoadQuery( projContext.EnterpriseProjectTypes.Where( ept => ept.Name == eptName)); projContext.ExecuteQuery(); eptUid = eptList.First().Id; } catch (Exception ex) { string msg = string.Format("GetEptUid: eptName = \"{0}\"\n\n{1}", eptName, ex.GetBaseException().ToString()); throw new ArgumentException(msg); } return eptUid; }
有幾種方法可以找到 EPT GUID。 GetEptUid 方法中顯示的查詢效率高,因為它只下載與 EPT 名稱相符的 EnterpriseProjectType 物件。 以下替代例程效率較低,因為它會將完整的 EPT 清單下載到用戶端應用程式,並遍歷清單。
foreach (EnterpriseProjectType ept in projSvr.EnterpriseProjectTypes)
{
if (ept.Name == eptName)
{
eptUid = ept.Id;
break;
}
}
以下例程使用 LINQ 查詢與 lambda 表達式來選擇 EPT 物件,但仍會下載所有 EnterpriseProjectType 物件。
var eptList = projContext.LoadQuery(projContext.EnterpriseProjectTypes);
projContext.ExecuteQuery();
eptUid = eptList.First(ept => ept.Name == eptName).Id;
設定創建資訊並發布專案
CreateTestProject 方法會建立一個 ProjectCreationInformation 物件,並指定建立專案所需的資訊。 專案 GUID 及名稱是必需的;開始日期、專案說明及EPT指南為可選。
設定新專案屬性後, Projects.Add 方法會將專案加入 專案 集合。 要儲存並發佈專案,您必須呼叫 Projects.Update 方法,將訊息傳送到專案伺服器佇列並建立專案。
程序四。 要設定新的專案屬性、建立專案並發佈專案
將 CreateTestProject 方法加入 程式 類別。 以下程式碼建立並發佈專案,但不會等待隊列工作完成。
// Create a project. private static bool CreateTestProject() { bool projCreated = false; try { Console.Write("\nCreating project: {0} ...", projName); ProjectCreationInformation newProj = new ProjectCreationInformation(); newProj.Id = Guid.NewGuid(); newProj.Name = projName; newProj.Description = "Test creating a project with CSOM"; newProj.Start = DateTime.Today.Date; // Setting the EPT GUID is optional. If no EPT is specified, Project Server // uses the default EPT. newProj.EnterpriseProjectTypeId = GetEptUid(basicEpt); PublishedProject newPublishedProj = projContext.Projects.Add(newProj); QueueJob qJob = projContext.Projects.Update(); /* Add code here to wait for the queue. */ } catch(Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\nError: {0}", ex.Message); Console.ResetColor(); } return projCreated; }將註解換
/* Add code here to wait for the queue. */成以下程式碼,等待佇列工作。 例程會等待指定的 逾時秒 數,或若排隊任務在逾時前完成,則繼續進行。 關於可能的佇列工作狀態,請參見 Microsoft.ProjectServer.Client.JobState。呼叫 QueueJob 物件的 Load 方法與 ExecuteQuery 方法是可選的。 如果你呼叫 WaitForQueue 方法時,QueueJob 物件尚未初始化,專案伺服器會先初始化它。
// Calling Load and ExecuteQuery for the queue job is optional. // projContext.Load(qJob); // projContext.ExecuteQuery(); JobState jobState = projContext.WaitForQueue(qJob, timeoutSeconds); if (jobState == JobState.Success) { projCreated = true; } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("\nThere is a problem in the queue. Timeout is {0} seconds.", timeoutSeconds); Console.WriteLine("\tQueue JobState: {0}", jobState.ToString()); Console.ResetColor(); } Console.WriteLine();
已發表計畫列表
ListPublishedProjects 方法會取得所有已發佈在 Project Web App 中的專案集合。 若在程序 4 中建立專案的佇列工作未成功完成或逾時,該新專案將不包含在 專案 集合中。
程序五。 列出已發表的專案
將 ListPublishedProjects 方法加入 程式 類別。
// List the published projects. private static void ListPublishedProjects() { // Get the list of projects on the server. projContext.Load(projContext.Projects); projContext.ExecuteQuery(); Console.WriteLine("\nProject ID : Project name : Created date"); foreach (PublishedProject pubProj in projContext.Projects) { Console.WriteLine("\n\t{0} :\n\t{1} : {2}", pubProj.Id.ToString(), pubProj.Name, pubProj.CreatedDate.ToString()); } }設定正確的 Project Web App URL 值,編譯 QueueCreateProject 應用程式,然後依照程序 6 測試該應用程式。
測試 QueueCreateProject 應用程式
當你第一次在 Project Web App 的測試實例上執行 QueueCreateProject 應用程式時,尤其是 Project Server 安裝在虛擬機器上時,該應用程式可能需要比預設的排隊逾時 10 秒還長。
程序六。 測試 QueueCreateProject 應用程式
打開 QueueCreateProject 屬性 視窗,選擇 除錯 標籤,然後在 開始選項 區塊新增以下命令列參數:
-n "Test proj 1" -t 20例如, (執行應用程式,按 F5) 。 如果逾時值夠長,應用程式會顯示以下輸出 (若Project Web App實例中存在其他已發佈專案,也會顯示) :
Creating project: Test proj 1 ... Project ID : Project name : Created date b34d7009-753f-4abb-9191-f4b15a82aac3 : Test proj 1 : 9/22/2011 11:27:57 AM Press any key to exit...再用以下命令列參數執行另一個測試,以使用預設的 10 秒隊列逾時:
-n "Test proj 1"由於測試程序 1 已經存在,應用程式會顯示以下輸出。
Creating project: Test proj 1 ... Error: PJClientCallableException: ProjectNameAlreadyExists ProjectNameAlreadyExists projName = Test proj 1 Project creation failed: Test proj 1 Press any key to exit...再用以下命令列參數執行另一個測試,以使用預設的 10 秒隊列逾時:
-n "Test proj 2"QueueCreateProject 應用程式會建立並發佈名為 Test proj 2 的專案。
再執行一次測試,使用以下命令列參數,並將逾時設定為過短以讓佇列工作無法完成:
-n "Test proj 3" -t 1因為隊列逾時時間太短,專案無法被建立。 應用程式顯示以下輸出。
Creating project: Test proj 3 ... There is a problem in the queue. Timeout is 1 seconds. Queue JobState: Unknown Project creation failed: Test proj 3 Press any key to exit...修改程式碼,使應用程式不再等待佇列工作。 例如,請註解等待排隊的程式碼,除了該行,
projCreated = true如下所示。//JobState jobState = projContext.WaitForQueue(qJob, timeoutSeconds); //if (jobState == JobState.Success) //{ projCreated = true; //} //else //{ // Console.ForegroundColor = ConsoleColor.Yellow; // Console.WriteLine("\nThere is a problem in the queue. Timeout is {0} seconds.", // timeoutSeconds); // Console.WriteLine("\tQueue JobState: {0}", jobState.ToString()); // Console.ResetColor(); //}重新編譯應用程式,並執行另一個測試,使用以下命令列參數:
-n "Test proj 4"由於 WaitForQueue 例程已被註解出,應用程式不會使用預設的逾時值。 即使應用程式不等待佇列,若專案伺服器的發佈動作足夠快,仍可能顯示測試專案 4。
Creating project: Test proj 4 ... Project ID : Project name : Created date cdd54103-082f-425c-b075-9ff52ac7d4e6 : Test proj 2 : 9/25/2011 4:28:55 PM b34d7009-753f-4abb-9191-f4b15a82aac3 : Test proj 1 : 9/22/2011 11:27:57 AM 5c0c73f2-f5dd-499b-8bd8-ebb74bf8c122 : Test proj 4 : 9/25/2011 4:39:21 PM Press any key to exit...
在) 刷新專案中心頁面,顯示已發表Project Web App (https://ServerName/ProjectServerName/Projects.aspx 專案。 下圖顯示測試專案已公布。
Checking the published projects in Project Web App
QueueCreateProject 範例應用程式展示了如何使用 ProjectCreationInformation 類別使用 CSOM 建立專案實體的典型範例,如何將專案加入已發佈的集合,如何使用 WaitForQueue 方法等待佇列工作,以及如何枚舉已發佈專案集合。
完整程式碼範例
以下是 QueueCreateProject 範例應用程式的完整程式碼。 Microsoft.ProjectServer.Client.ProjectCreationInformation 類別參考也包含本主題中的程式碼。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ProjectServer.Client;
namespace QueueCreateProject
{
class Program
{
private const string pwaPath = "https://ServerName /pwa/"; // Change the path to your Project Web App instance.
private static string basicEpt = "Enterprise Project"; // Basic enterprise project type.
private static string projName = string.Empty;
private static int timeoutSeconds = 10; // The maximum wait time for a queue job, in seconds.
private static ProjectContext projContext;
static void Main(string[] args)
{
if (!ParseCommandLine(args))
{
Usage();
ExitApp();
}
projContext = new ProjectContext(pwaPath);
if (CreateTestProject())
ListPublishedProjects();
else
Console.WriteLine("\nProject creation failed: {0}", projName);
ExitApp();
}
// Create a project.
private static bool CreateTestProject()
{
bool projCreated = false;
try
{
Console.Write("\nCreating project: {0} ...", projName);
ProjectCreationInformation newProj = new ProjectCreationInformation();
newProj.Id = Guid.NewGuid();
newProj.Name = projName;
newProj.Description = "Test creating a project with CSOM";
newProj.Start = DateTime.Today.Date;
// Setting the EPT GUID is optional. If no EPT is specified, Project Server uses
// the default EPT.
newProj.EnterpriseProjectTypeId = GetEptUid(basicEpt);
PublishedProject newPublishedProj = projContext.Projects.Add(newProj);
QueueJob qJob = projContext.Projects.Update();
// Calling Load and ExecuteQuery for the queue job is optional. If qJob is
// not initialized when you call WaitForQueue, Project Server initializes it.
// projContext.Load(qJob);
// projContext.ExecuteQuery();
JobState jobState = projContext.WaitForQueue(qJob, timeoutSeconds);
if (jobState == JobState.Success)
{
projCreated = true;
}
else
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\nThere is a problem in the queue. Timeout is {0} seconds.",
timeoutSeconds);
Console.WriteLine("\tQueue JobState: {0}", jobState.ToString());
Console.ResetColor();
}
Console.WriteLine();
}
catch(Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\nError: {0}", ex.Message);
Console.ResetColor();
}
return projCreated;
}
// Get the GUID of the specified enterprise project type.
private static Guid GetEptUid(string eptName)
{
Guid eptUid = Guid.Empty;
try
{
// Get the list of EPTs that have the specified name.
// If the EPT name exists, the list will contain only one EPT.
var eptList = projContext.LoadQuery(
projContext.EnterpriseProjectTypes.Where(
ept => ept.Name == eptName));
projContext.ExecuteQuery();
eptUid = eptList.First().Id;
// Alternate routines to find the EPT GUID. Both (a) and (b) download the entire list of EPTs.
// (a) Using a foreach block:
//foreach (EnterpriseProjectType ept in projSvr.EnterpriseProjectTypes)
//{
// if (ept.Name == eptName)
// {
// eptUid = ept.Id;
// break;
// }
//}
// (b) Querying for the EPT list, and then using a lambda expression to select the EPT:
//var eptList = projContext.LoadQuery(projContext.EnterpriseProjectTypes);
//projContext.ExecuteQuery();
//eptUid = eptList.First(ept => ept.Name == eptName).Id;
}
catch (Exception ex)
{
string msg = string.Format("GetEptUid: eptName = \"{0}\"\n\n{1}",
eptName, ex.GetBaseException().ToString());
throw new ArgumentException(msg);
}
return eptUid;
}
// List the published projects.
private static void ListPublishedProjects()
{
// Get the list of projects on the server.
projContext.Load(projContext.Projects);
projContext.ExecuteQuery();
Console.WriteLine("\nProject ID : Project name : Created date");
foreach (PublishedProject pubProj in projContext.Projects)
{
Console.WriteLine("\n\t{0} :\n\t{1} : {2}", pubProj.Id.ToString(), pubProj.Name,
pubProj.CreatedDate.ToString());
}
}
// Parse the command line. Return true if there are no errors.
private static bool ParseCommandLine(string[] args)
{
bool error = false;
int argsLen = args.Length;
try
{
for (int i = 0; i < argsLen; i++)
{
if (error) break;
if (args[i].StartsWith("-") || args[i].StartsWith("/"))
args[i] = "*" + args[i].Substring(1).ToLower();
switch (args[i])
{
case "*projname":
case "*n":
if (++i >= argsLen) return false;
projName = args[i];
break;
case "*timeout":
case "*t":
if (++i >= argsLen) return false;
timeoutSeconds = Convert.ToInt32(args[i]);
break;
case "*?":
default:
error = true;
break;
}
}
}
catch (FormatException)
{
error = true;
}
if (string.IsNullOrEmpty(projName)) error = true;
return !error;
}
private static void Usage()
{
string example = "Usage: QueueCreateProject -projName | -n \"New project name\" [-timeout | -t sec]";
example += "\nExample: QueueCreateProject -n \"My new project\"";
example += "\nDefault timeout seconds = " + timeoutSeconds.ToString();
Console.WriteLine(example);
}
private static void ExitApp()
{
Console.Write("\nPress any key to exit... ");
Console.ReadKey(true);
Environment.Exit(0);
}
}
}