Project.CreateProjectFromTemplate 方法
从指定的模板创建的项目。新的项目都有指定的项目名称。
命名空间: WebSvcProject
程序集: ProjectServerServices(位于 ProjectServerServices.dll 中)
语法
声明
<SoapDocumentMethodAttribute("https://schemas.microsoft.com/office/project/server/webservices/Project/CreateProjectFromTemplate", RequestNamespace := "https://schemas.microsoft.com/office/project/server/webservices/Project/", _
ResponseNamespace := "https://schemas.microsoft.com/office/project/server/webservices/Project/", _
Use := SoapBindingUse.Literal, ParameterStyle := SoapParameterStyle.Wrapped)> _
Public Function CreateProjectFromTemplate ( _
templateUid As Guid, _
projectName As String _
) As Guid
用法
Dim instance As Project
Dim templateUid As Guid
Dim projectName As String
Dim returnValue As Guid
returnValue = instance.CreateProjectFromTemplate(templateUid, _
projectName)
[SoapDocumentMethodAttribute("https://schemas.microsoft.com/office/project/server/webservices/Project/CreateProjectFromTemplate", RequestNamespace = "https://schemas.microsoft.com/office/project/server/webservices/Project/",
ResponseNamespace = "https://schemas.microsoft.com/office/project/server/webservices/Project/",
Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
public Guid CreateProjectFromTemplate(
Guid templateUid,
string projectName
)
参数
templateUid
类型:System.Guid项目模板的 GUID。
projectName
类型:System.String新项目的名称。
返回值
类型:System.Guid
已创建的项目的 GUID。
备注
CreateProjectFromTemplate在绘制数据表中创建新项目。当前用户必须具有这两个权限表中指定的权限。
CreateProjectFromTemplate方法 does 保持如时间刻度或字体格式的项目模板中的任何格式设置的信息。您可以设置项目的专业人员; 项目的信息的格式格式设置在中不可用的 PSI 的公共方法或数据集。CreateProjectFromTemplate获取ProjectDataSet从项目模板中的草稿数据库、 创建新ProjectDataSet,并更改项目摘要任务名称为请求的项目名称。它将所有DataTable的行添加到新ProjectDataSet,除工作分配日期,然后用不同的 GUID 创建一个新项目。
如果该模板包括任务说明,任务备注不显示当您使用CreateProjectFromTemplate创建一个新项目,然后在 Microsoft Office 项目专业中打开该项目。可以使用项目专业人员创建包含任务备注的模板和项目模板发布。在已发布的数据库中的MSP_TASKS表包括TASK_RTF_NOTES列中有数据的模板。以编程方式创建和保存基于该模板的新项目后的TASK_RTF_NOTES列包含任务注释、 不为 RTF (丰富文本格式) 数据的文本数据。
问题是该TASK_RTF_NOTES的数据类型image为 rtf 格式的数据。在 Project Server 服务应用程序中的 PSI web 服务无法处理 rtf 格式的数据。要添加在从模板以编程方式在项目服务器创建的项目的任务备注中必须直接访问MSP_TASKS表以执行下列操作:
将 rtf 格式的数据添加到特定任务的TASK_RTF_NOTES列。
将TASKS_HAS_NOTES列设置为1 (true)。
备注
目前没有一种方法是可用于以编程方式向根据该模板创建的项目模板中添加任务备注。
项目服务器接口 (PSI) 不能用于在项目中创建本地自定义域。但 PSI 不支持编辑在任务、 资源和工作分配的本地自定义域值。
查看设置,例如添加的域不会从模板复制到新项目。
Project Server 权限
权限 |
说明 |
---|---|
允许用户创建一个新项目。全局权限。 |
|
允许用户打开项目模板。全局权限。 |
示例
下面的示例创建一个模板、 按名称查找该模板并检查无效的字符的项目名称。该示例创建基于该模板的项目和再发布该项目。有必要因为 Project Server 并没有任何保证都是就地的默认模板创建模板。
通常会显示模板和各自的唯一标识号的列表并使用它来选择所需的模板。在某些情况下您可能需要按名称查找项目或模板。这里展示的了。必须要找到它的项目的确切名称。
有关运行此代码示例的关键信息,请参阅Project 2013 中基于 WCF 的代码示例的先决条件。
using System;
using System.Text;
using System.Xml;
using System.ServiceModel;
using PSLibrary = Microsoft.Office.Project.Server.Library;
namespace CreateProjectFromTemplate
{
class Program
{
private const string ENDPOINT_PROJECT = "basicHttp_Project";
private const string ENDPOINT_QUEUESYSTEM = "basicHttp_QueueSystem";
private static SvcProject.ProjectClient projectClient;
private static SvcQueueSystem.QueueSystemClient queueSystemClient;
static void Main(string[] args)
{
try
{
ConfigClientEndpoints(ENDPOINT_PROJECT);
ConfigClientEndpoints(ENDPOINT_QUEUESYSTEM);
// Create a template to use. Normally, you would already have a template
// stored in PWA that you would use, but this example creates a template.
Console.WriteLine("Creating template");
SvcProject.ProjectDataSet templateDs = new SvcProject.ProjectDataSet();
SvcProject.ProjectDataSet.ProjectRow templateRow = templateDs.Project.NewProjectRow();
templateRow.PROJ_UID = Guid.NewGuid();
templateRow.PROJ_NAME = "Its a wonderful template! "
+ DateTime.Now.ToShortTimeString().Replace(":", "-");
templateRow.WPROJ_DESCRIPTION = "Temporary template for use in CreateProjectFromTemplate example.";
templateRow.PROJ_TYPE = (int)PSLibrary.Project.ProjectType.Template;
if (IsNameValid(templateRow.PROJ_NAME))
{
templateDs.Project.AddProjectRow(templateRow);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\nThe project name contains characters that are not valid:"
+ "\n\t{0}", templateRow.PROJ_NAME);
QuitTheApp();
}
// Add two tasks to the template.
int numTasks = 2;
SvcProject.ProjectDataSet.TaskRow task = null;
for (int i = 0; i < numTasks; i++)
{
task = templateDs.Task.NewTaskRow();
task.PROJ_UID = templateRow.PROJ_UID;
task.TASK_UID = Guid.NewGuid();
task.TASK_DUR_FMT = (int)PSLibrary.Task.DurationFormat.Day;
task.TASK_DUR = 4800; // The task duration is 8 hours.
task.TASK_NAME = "T" + (i + 1).ToString() + " in template";
task.TASK_START_DATE = System.DateTime.Now.AddDays(i + 1);
templateDs.Task.AddTaskRow(task);
}
// Write the new template information to the database.
Console.WriteLine("\n\nSaving template to database");
Guid jobId = Guid.NewGuid();
DateTime startTime = DateTime.Now;
projectClient.QueueCreateProject(jobId, templateDs, false);
// Wait for the Project Server Queuing System to create the project.
if (Helpers.WaitForQueue(SvcQueueSystem.QueueMsgType.ProjectCreate,
queueSystemClient, startTime))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\nTemplate created:\n\t{0}", templateRow.PROJ_NAME);
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\nThe template was not created:\n\t{0}.\nThe queue wait time exceeded 30 seconds",
templateRow.PROJ_NAME);
Console.ResetColor();
QuitTheApp();
}
// Find the template by name.
// You could just use the GUID to create the project from a template,
// but this example shows how to get the GUID from the template name.
// Note: If you have a template on the enterprise server already, you can use
// the ReadProjectStatus method to get a list of published templates.
// projectSvc.ReadProjectStatus(Guid.Empty, SvcProject.DataStoreEnum.PublishedStore,
// String.Empty, (int) PSLibrary.Project.ProjectType.Template);
Console.WriteLine("Finding the template by name");
SvcProject.ProjectDataSet readTemplateDs = projectClient.ReadProjectStatus(Guid.Empty,
SvcProject.DataStoreEnum.WorkingStore, templateRow.PROJ_NAME,
(int)PSLibrary.Project.ProjectType.Template);
// Name the project.
string projectName = "Created from " + readTemplateDs.Project[0].PROJ_NAME
+ " at " + DateTime.Now.ToShortTimeString().Replace(":", "-");
// Create the new project on the server and get its GUID.
Console.WriteLine("Create the new project from the template");
Guid newProjectUid = projectClient.CreateProjectFromTemplate(readTemplateDs.Project[0].PROJ_UID,
projectName);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Project created:\n\t{0}\n\t{1}", newProjectUid.ToString(), projectName);
Console.ResetColor();
// Publish the project, to make it visible in PWA.
jobId = Guid.NewGuid();
projectClient.QueuePublish(jobId, newProjectUid, true, string.Empty);
startTime = DateTime.Now;
if (Helpers.WaitForQueue(SvcQueueSystem.QueueMsgType.ProjectPublish,
queueSystemClient, startTime))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Project published");
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\nThe project was not published.\nThe queue wait time exceeded 30 seconds");
Console.ResetColor();
}
}
catch (FaultException fault)
{
// Use the WCF FaultException, because the ASMX SoapException does not
// exist in a WCF-based application.
WriteFaultOutput(fault);
}
finally
{
QuitTheApp();
}
}
// Check the project name for invalid characters.
private static bool IsNameValid(string projName)
{
bool result = true;
char[] badChars = PSLibrary.Project.InvalidCharacters();
Console.WriteLine("Check project name for Project.InvalidCharacters:");
Console.ForegroundColor = ConsoleColor.Yellow;
foreach (char c in badChars)
{
Console.Write(c);
Console.Write(" ");
}
Console.ResetColor();
// The name is not valid if it is empty or contains leading or trailing white space.
if (String.IsNullOrEmpty(projName) || String.Compare(projName, projName.Trim(), StringComparison.Ordinal) != 0)
{
return false;
}
// The name is also not valid if it contains one of the invalid characters.
if (badChars != null)
{
if (projName.IndexOfAny(badChars) != -1)
{
return false;
}
}
return result;
}
// Extract a PSClientError object from the WCF FaultException object, and
// then display the exception details and each error in the PSClientError stack.
private static void WriteFaultOutput(FaultException fault)
{
string errAttributeName;
string errAttribute;
string errOut;
string errMess = "".PadRight(30, '=') + "\r\n"
+ "Error details: " + "\r\n";
PSLibrary.PSClientError error = Helpers.GetPSClientError(fault, out errOut);
errMess += errOut;
PSLibrary.PSErrorInfo[] errors = error.GetAllErrors();
PSLibrary.PSErrorInfo thisError;
for (int i = 0; i < errors.Length; i++)
{
thisError = errors[i];
errMess += "\r\n".PadRight(30, '=') + "\r\nPSClientError output:\r\n";
errMess += thisError.ErrId.ToString() + "\n";
for (int j = 0; j < thisError.ErrorAttributes.Length; j++)
{
errAttributeName = thisError.ErrorAttributeNames()[j];
errAttribute = thisError.ErrorAttributes[j];
errMess += "\r\n\t" + errAttributeName
+ ": " + errAttribute;
}
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(errMess);
Console.ResetColor();
}
// Use the endpoints defined in app.config to configure the client.
private static void ConfigClientEndpoints(string endpt)
{
if (endpt == ENDPOINT_PROJECT)
projectClient = new SvcProject.ProjectClient(endpt);
else if (endpt == ENDPOINT_QUEUESYSTEM)
queueSystemClient = new SvcQueueSystem.QueueSystemClient(endpt);
}
// Quit the application.
private static void QuitTheApp()
{
Console.ResetColor();
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey(true);
Environment.Exit(1);
}
}
// Helper methods: WaitForQueue and GetPSClientError.
class Helpers
{
// Wait for the queue jobs to complete.
public static bool WaitForQueue(SvcQueueSystem.QueueMsgType jobType,
SvcQueueSystem.QueueSystemClient queueSystemClient,
DateTime startTime)
{
const int MAX_WAIT = 30; // Maximum wait time, in seconds.
int numJobs = 1; // Number of jobs in the queue.
bool completed = false; // Queue job completed.
SvcQueueSystem.QueueStatusDataSet queueStatusDs =
new SvcQueueSystem.QueueStatusDataSet();
int timeout = 0; // Number of seconds waited.
Console.Write("Waiting for job: {0} ", jobType.ToString());
SvcQueueSystem.QueueMsgType[] messageTypes = { jobType };
SvcQueueSystem.JobState[] jobStates = { SvcQueueSystem.JobState.Success };
while (timeout < MAX_WAIT)
{
System.Threading.Thread.Sleep(1000); // Sleep one second.
queueStatusDs = queueSystemClient.ReadMyJobStatus(
messageTypes,
jobStates,
startTime,
DateTime.Now,
numJobs,
true,
SvcQueueSystem.SortColumn.QueuePosition,
SvcQueueSystem.SortOrder.LastOrder);
timeout++;
Console.Write(".");
}
Console.WriteLine();
if (queueStatusDs.Status.Count == numJobs)
completed = true;
return completed;
}
/// <summary>
/// Extract a PSClientError object from the ServiceModel.FaultException,
/// for use in output of the GetPSClientError stack of errors.
/// </summary>
/// <param name="e"></param>
/// <param name="errOut">Shows that FaultException has more information
/// about the errors than PSClientError has. FaultException can also contain
/// other types of errors, such as failure to connect to the server.</param>
/// <returns>PSClientError object, for enumerating errors.</returns>
public static PSLibrary.PSClientError GetPSClientError(FaultException e,
out string errOut)
{
const string PREFIX = "GetPSClientError() returns null: ";
errOut = string.Empty;
PSLibrary.PSClientError psClientError = null;
if (e == null)
{
errOut = PREFIX + "Null parameter (FaultException e) passed in.";
psClientError = null;
}
else
{
// Get a ServiceModel.MessageFault object.
var messageFault = e.CreateMessageFault();
if (messageFault.HasDetail)
{
using (var xmlReader = messageFault.GetReaderAtDetailContents())
{
var xml = new XmlDocument();
xml.Load(xmlReader);
var serverExecutionFault = xml["ServerExecutionFault"];
if (serverExecutionFault != null)
{
var exceptionDetails = serverExecutionFault["ExceptionDetails"];
if (exceptionDetails != null)
{
try
{
errOut = exceptionDetails.InnerXml + "\r\n";
psClientError =
new PSLibrary.PSClientError(exceptionDetails.InnerXml);
}
catch (InvalidOperationException ex)
{
errOut = PREFIX + "Unable to convert fault exception info ";
errOut += "a valid Project Server error message. Message: \n\t";
errOut += ex.Message;
psClientError = null;
}
}
else
{
errOut = PREFIX + "The FaultException e is a ServerExecutionFault, "
+ "but does not have ExceptionDetails.";
}
}
else
{
errOut = PREFIX + "The FaultException e is not a ServerExecutionFault.";
}
}
}
else // No detail in the MessageFault.
{
errOut = PREFIX + "The FaultException e does not have any detail.";
}
}
errOut += "\r\n" + e.ToString() + "\r\n";
return psClientError;
}
}
}
当您运行CreateProjectFromTemplate示例控制台窗口会显示下面的输出:
Creating template
Check project name for Project.InvalidCharacters:
' # : ; < > / | ? \ . * " ~ % & { } +
Saving template to database
Waiting for job: ProjectCreate ..............................
Template created:
Its a wonderful template! 3-50 PM
Finding the template by name
Create the new project from the template
Project created:
b9d0272e-62db-e111-b1ce-00155d146f2c
Created from Its a wonderful template! 3-50 PM at 3-50 PM
Waiting for job: ProjectPublish ..............................
Project published
Press any key to exit...
若要查看FaultException处理程序的操作,更改名称的模板和检查无效字符的代码。下面的代码引入了在名称和注释调用IsNameValid方法中的 + 字符:
templateRow.PROJ_NAME = "Its a wonderful template! "
+ DateTime.Now.ToShortTimeString().Replace(":","+");
templateRow.WPROJ_DESCRIPTION = "Temporary template for use in CreateProjectFromTemplate example.";
templateRow.PROJ_TYPE = (int)PSLibrary.Project.ProjectType.Template;
templateDs.Project.AddProjectRow(templateRow);
//if (IsNameValid(templateRow.PROJ_NAME))
//{
// templateDs.Project.AddProjectRow(templateRow);
//}
//else
//{
// Console.ForegroundColor = ConsoleColor.Red;
// Console.WriteLine("\nThe project name contains characters that are not valid:"
// + "\n\t{0}", templateRow.PROJ_NAME);
// QuitTheApp();
//}