Поделиться через


Метод Resource.ReadResourceAssignments

Получает назначения ресурсов.

Пространство имен:  WebSvcResource
Сборка:  ProjectServerServices (в ProjectServerServices.dll)

Синтаксис

'Декларация
<SoapDocumentMethodAttribute("https://schemas.microsoft.com/office/project/server/webservices/Resource/ReadResourceAssignments", RequestNamespace := "https://schemas.microsoft.com/office/project/server/webservices/Resource/",  _
    ResponseNamespace := "https://schemas.microsoft.com/office/project/server/webservices/Resource/",  _
    Use := SoapBindingUse.Literal, ParameterStyle := SoapParameterStyle.Wrapped)> _
Public Function ReadResourceAssignments ( _
    filter As String _
) As ResourceAssignmentDataSet
'Применение
Dim instance As Resource
Dim filter As String
Dim returnValue As ResourceAssignmentDataSet

returnValue = instance.ReadResourceAssignments(filter)
[SoapDocumentMethodAttribute("https://schemas.microsoft.com/office/project/server/webservices/Resource/ReadResourceAssignments", RequestNamespace = "https://schemas.microsoft.com/office/project/server/webservices/Resource/", 
    ResponseNamespace = "https://schemas.microsoft.com/office/project/server/webservices/Resource/", 
    Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
public ResourceAssignmentDataSet ReadResourceAssignments(
    string filter
)

Параметры

  • filter
    Тип: System.String

    Фильтрация XML-строка, возвращаемого Filter. Фильтр необходим из-за возможных большое число возвращаемых назначений. String.Empty возвращает ошибку.

Возвращаемое значение

Тип: WebSvcResource.ResourceAssignmentDataSet
ResourceAssignmentDataSet заполненный данными назначения ресурсов.

Замечания

Ресурсы должны быть опубликованы, перед их возвратом метода ReadResourceAssignments .

Примечание

Параметр filter для работы с Criteria операторы для фильтрации строк только в основной ResourceAssignmentDataTable. Например нельзя использовать filter с помощью метода ReadResourceAssignments для фильтрации строк в ResourceAssignmentCustomFieldsDataTable. При попытке фильтрации строк в дополнительного DataTablePSI возвращает исключение FilterInvalid .

However, you can use the Fields.Add method to filter columns in the secondary ResourceAssignmentCustomFieldsDataTable of the ResourceAssignmentDataSet. For more information, see How to: Use a Filter Parameter with PSI Methods.

Извлечение данных ResourceAssignmentCustomFields

Чтобы получить данные для настраиваемого поля назначения ресурсов с помощью метода ReadResourceAssignments , параметр filter необходимо включить поля PROJ_UID и ASSN_UID для ResourceAssignmentCustomFields имя таблицы.

Например следующее значение filter приводит к System.Data.ConstraintExceptionиз-за отсутствия для имя таблицы ResourceAssignmentCustomFieldsPROJ_UID поля:

 <?xml version="1.0" encoding="utf-8"?>
 <Filter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
         filterTableName="ResourceAssignment" 
         xmlns="https://microsoft.com/ProjectServer/FilterSchema.xsd">
   <Fields>
     <Field tableName="ResourceAssignment" fieldName="PROJ_UID" />
     <Field tableName="ResourceAssignment" fieldName="PROJ_NAME" />
     <Field tableName="ResourceAssignment" fieldName="TASK_UID" />
     <Field tableName="ResourceAssignment" fieldName="ASSN_UID" />
     <Field tableName="ResourceAssignment" fieldName="RES_UID" />
     <Field tableName="ResourceAssignment" fieldName="TASK_IS_SUMMARY" />
     <Field tableName="ResourceAssignmentCustomFields" fieldName="ASSN_UID" />
     <Field tableName="ResourceAssignmentCustomFields" fieldName="MD_PROP_UID" />
     <Field tableName="ResourceAssignmentCustomFields" fieldName="FIELD_TYPE_ENUM" />
     <Field tableName="ResourceAssignmentCustomFields" fieldName="TEXT_VALUE" />
     <Field tableName="ResourceAssignmentCustomFields" fieldName="CODE_VALUE" />
     <Field tableName="ResourceAssignmentCustomFields" fieldName="NUM_VALUE" /> 
  </Fields>
   <Criteria />
 </Filter>

Для фильтра добавьте следующие поля:

<Field tableName="ResourceAssignmentCustomFields" fieldName="PROJ_UID" />

Разрешения Project Server

Разрешение

Описание

ViewResourceAssignmentsInAssignmentViews

Позволяет пользователю просматривать назначения. Разрешение категории.

Примеры

В этом примере извлекается корпоративный ресурс или создается несколько ресурсов, если они не существуют, создает два проекта, назначения ресурсов в проекты и наконец считывает назначений, с помощью фильтра.

Please see Необходимые условия для образцов кода на основе ASMX в Project 2013 for critical information on running this code sample.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Net;
using System.Web.Services.Protocols;
using System.Threading;
using PSLibrary = Microsoft.Office.Project.Server.Library;

namespace Microsoft.SDK.Project.Samples.ReadResourceAssignments
{
    class Program
    {
        [STAThread]
        static void Main()
        {
            try
            {
                #region Setup
                const string PROJECT_SERVER_URI = "https://ServerName/ProjectServerName/";
                const string RESOURCE_SERVICE_PATH = "_vti_bin/psi/resource.asmx";
                const string PROJECT_SERVICE_PATH = "_vti_bin/psi/project.asmx";
                const string QUEUE_SYSTEM_SERVICE_PATH = "_vti_bin/psi/queuesystem.asmx";
                const string RESOURCE_PLAN_SERVICE_PATH = "_vti_bin/psi/resourceplan.asmx";
                const string SESSION_DESCRIPTION = "ReadResourceAssignments Utility";
                Guid sessionUid = Guid.NewGuid();
                Guid jobUid;

                // Initialize the Web service objects.
                SvcResource.Resource resourceSvc = new SvcResource.Resource();
                resourceSvc.Url = PROJECT_SERVER_URI + RESOURCE_SERVICE_PATH;
                resourceSvc.UseDefaultCredentials = true;

                SvcProject.Project projectSvc = new SvcProject.Project();
                projectSvc.Url = PROJECT_SERVER_URI + PROJECT_SERVICE_PATH;
                projectSvc.UseDefaultCredentials = true;

                SvcQueueSystem.QueueSystem q = new SvcQueueSystem.QueueSystem();
                q.Url = PROJECT_SERVER_URI + QUEUE_SYSTEM_SERVICE_PATH;
                q.UseDefaultCredentials = true;

                SvcResourcePlan.ResourcePlan resourcePlanSvc = 
                    new SvcResourcePlan.ResourcePlan();
                resourcePlanSvc.Url = PROJECT_SERVER_URI + RESOURCE_PLAN_SERVICE_PATH;
                resourcePlanSvc.UseDefaultCredentials = true;

                // Create the resources.
                Console.WriteLine("Setting up enterprise resources");
                Guid[] resourceUids = EnsureEnterpriseResources(resourceSvc);
                PSLibrary.Filter resourceFilter = GetResourceFilter(resourceUids);
                string resourceFilterXml = resourceFilter.GetXml();
                SvcResource.ResourceDataSet resourceDs = 
                    resourceSvc.ReadResources(resourceFilterXml, false);

                // Create the projects.
                Console.WriteLine("Creating Projects");
                const int NUM_PROJS = 2;
                Guid[] projectUids = new Guid[NUM_PROJS];
                for (int i = 0; i < NUM_PROJS; i++)
                {
                    // Create the project
                    Console.WriteLine("Cr.eating Project {0}:", i);
                    projectUids[i] = CreateSampleProject(projectSvc, q);

                    // Check out the project.
                    projectSvc.CheckOutProject(projectUids[i], sessionUid, SESSION_DESCRIPTION);

                    // Add the enterprise resources.
                    Console.WriteLine("...Adding Enterprise Resources");
                    AddResourcesToProjectTeam(projectUids[i], resourceUids, q, projectSvc, 
                        sessionUid, SESSION_DESCRIPTION);

                    // Give the enterprise resources some work to do.
                    Console.WriteLine("...Assigning Work");
                    AddResourcesToAssignments(projectUids[i], resourceUids, projectSvc, q, 
                        sessionUid, SESSION_DESCRIPTION);

                    // Check in the project.
                    Console.WriteLine("...Check in project");
                    jobUid = Guid.NewGuid();
                    projectSvc.QueueCheckInProject(jobUid, projectUids[i], false, sessionUid, 
                        SESSION_DESCRIPTION);
                    WaitForQueue(q, jobUid);

                    // Must publish for the resources to be booked.
                    Console.WriteLine("...Publishing the project");
                    jobUid = Guid.NewGuid();
                    projectSvc.QueuePublish(jobUid, projectUids[i], false, null);
                    WaitForQueue(q, jobUid);
                }
                #endregion

                #region Read Resource Assignments
                Console.WriteLine("Read the resource assignments");

                // Create the resource filter.
                PSLibrary.Filter resourceAssignmentFilter = 
                    GetResourceAssignmentFilter(resourceUids);
                string resourceAssignmentFilterXml = resourceAssignmentFilter.GetXml();
                Console.WriteLine("filter: ");
                Console.WriteLine(resourceAssignmentFilterXml);

                // Read the assignments.
                SvcResource.ResourceAssignmentDataSet resourceAssignDs = 
                    resourceSvc.ReadResourceAssignments(resourceAssignmentFilterXml);
                WriteTablesToConsole(resourceAssignDs.Tables);
                #endregion
            }

            #region Error Handling and Final
            catch (SoapException ex)
            {
                PSLibrary.PSClientError error = new PSLibrary.PSClientError(ex);
                PSLibrary.PSErrorInfo[] errors = error.GetAllErrors();
                string errMess = "==============================\r\nError: \r\n";
                for (int i = 0; i < errors.Length; i++)
                {
                    errMess += "\n" + ex.Message.ToString() + "\r\n";
                    errMess += "".PadRight(30, '=') + "\r\nPSCLientError Output:\r\n \r\n";
                    errMess += errors[i].ErrId.ToString() + "\n";

                    for (int j = 0; j < errors[i].ErrorAttributes.Length; j++)
                    {
                        errMess += "\r\n\t" + errors[i].ErrorAttributeNames()[j] + ": " 
                            + errors[i].ErrorAttributes[j];
                    }
                    errMess += "\r\n".PadRight(30, '=');
                }
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(errMess);
            }
            catch (WebException ex)
            {
                string errMess = ex.Message.ToString() +
                   "\n\nLog on, or check the Project Server Queuing Service";
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error: " + errMess);
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error: " + ex.Message);
            }
            finally
            {
                Console.ResetColor();
                Console.WriteLine("\r\n\r\nPress any key...");
                Console.ReadKey();
            }
            #endregion
        }
        #region Supporting Setup Functions

        // Randomly assign resources to tasks, for the sample.
        private static void AddResourcesToAssignments(Guid projectUid, Guid[] resourceUids, 
            SvcProject.Project projectSvc, SvcQueueSystem.QueueSystem q, 
            Guid sessionUid, string SESSION_DESCRIPTION)
        {
            SvcProject.ProjectDataSet projectDs = projectSvc.ReadProject(projectUid, 
                SvcProject.DataStoreEnum.WorkingStore);

            int r = 0;
            for (int i = 0; i < projectDs.Task.Count; i++)
            {
                // Can't add resources to summary tasks through the PSI.
                if (!projectDs.Task[i].TASK_IS_SUMMARY)
                {
                    CreateAssignment(projectDs, projectDs.Task[i].TASK_UID, resourceUids[r]);
                    r = (r == resourceUids.Length - 1 ? 0 : r + 1);
                    CreateAssignment(projectDs, projectDs.Task[i].TASK_UID, resourceUids[r]);
                }
            }
            Guid jobUid = Guid.NewGuid();
            projectSvc.QueueAddToProject(jobUid, sessionUid, 
                (SvcProject.ProjectDataSet)projectDs.GetChanges(DataRowState.Added), false);
            WaitForQueue(q, jobUid);
        }
        // Add the resources in the array to the specified project.
        private static void AddResourcesToProjectTeam(Guid projectUid, Guid[] resourceUids, 
            SvcQueueSystem.QueueSystem q, SvcProject.Project projectSvc, 
            Guid sessionUid, string SESSION_DESCRIPTION)
        {
            // Add the resource to the team
            SvcProject.ProjectTeamDataSet projectTeamDs = new SvcProject.ProjectTeamDataSet();
            for (int i = 0; i < resourceUids.Length; i++)
            {
                ProjectTeamAddResource(projectTeamDs, projectUid, resourceUids[i], resourceUids[i]);
            }
            // Save the team!
            Guid jobId = Guid.NewGuid();
            projectSvc.QueueUpdateProjectTeam(jobId, sessionUid, projectUid, projectTeamDs);
            WaitForQueue(q, jobId);
        }
        // Add an enterprise resource to use on the project.
        // Helper function for AddResourcesToProjectTeam.
        public static void ProjectTeamAddResource(SvcProject.ProjectTeamDataSet projTeamDataSet, 
            Guid projGuid, Guid resGuid, Guid newResGuid)
        {
            SvcProject.ProjectTeamDataSet.ProjectTeamRow projTeamRow = 
                projTeamDataSet.ProjectTeam.NewProjectTeamRow();
            projTeamRow.PROJ_UID = projGuid;
            projTeamRow.RES_UID = resGuid;
            projTeamRow.NEW_RES_UID = newResGuid;
            projTeamDataSet.ProjectTeam.AddProjectTeamRow(projTeamRow);
        }
        // Create enterprise resources for the sample.
        // Add GUIDs to name to ensure unique enterprise resources.
        private static Guid[] EnsureEnterpriseResources(SvcResource.Resource resourceSvc)
        {
            string[] resourceNames = new string[] { "Lertchai Treetawatchaiwong " 
                                                     + Guid.NewGuid().ToString(), 
                                                 "Bricks "  + Guid.NewGuid().ToString(), 
                                                 "Conference Room A " + Guid.NewGuid().ToString(),
                                                 "Rental " + Guid.NewGuid().ToString()};
            PSLibrary.Resource.Type[] resourceTypes = new PSLibrary.Resource.Type[] {
                PSLibrary.Resource.Type.WorkResource, 
                PSLibrary.Resource.Type.MaterialResource, 
                PSLibrary.Resource.Type.WorkResource, 
                PSLibrary.Resource.Type.CostResources };

            Guid[] resources = new Guid[resourceNames.Length];
            for (int i = 0; i < resourceNames.Length; i++)
            {
                resources[i] = EnsureEnterpriseResource(resourceSvc, 
                    resourceNames[i], resourceTypes[i]);
            }
            return resources;
        }
        private static Guid EnsureEnterpriseResource(SvcResource.Resource resourceSvc, 
            string resourceName, PSLibrary.Resource.Type resourceType)
        {
            SvcResource.ResourceDataSet resourceDs = new SvcResource.ResourceDataSet();

            PSLibrary.Filter resourceFilter = new Microsoft.Office.Project.Server.Library.Filter();
            resourceFilter.FilterTableName = resourceDs.Resources.TableName;
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceDs.Resources.TableName, 
                resourceDs.Resources.RES_UIDColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceDs.Resources.TableName, 
                resourceDs.Resources.RES_NAMEColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceDs.Resources.TableName, 
                resourceDs.Resources.RES_INITIALSColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceDs.Resources.TableName, 
                resourceDs.Resources.RES_TYPEColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceDs.Resources.TableName, 
                resourceDs.Resources.RES_CODEColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));

            PSLibrary.Filter.FieldOperator existingResource = new PSLibrary.Filter.FieldOperator(
                PSLibrary.Filter.FieldOperationType.Equal, 
                resourceDs.Resources.RES_NAMEColumn.ColumnName, 
                resourceName);
            resourceFilter.Criteria = existingResource;
            string filterXml = resourceFilter.GetXml();
            resourceDs = resourceSvc.ReadResources(filterXml, false);

            if (resourceDs.Resources.Count >= 1)
            {
                return resourceDs.Resources[0].RES_UID;
            }
            else
            {
                resourceDs = new SvcResource.ResourceDataSet();
                SvcResource.ResourceDataSet.ResourcesRow resourceRow = 
                    resourceDs.Resources.NewResourcesRow();
                resourceRow.RES_UID = Guid.NewGuid();
                resourceRow.RES_NAME = resourceName;
                resourceRow.RES_INITIALS = resourceName.Substring(0, 1) +
                    (resourceName.IndexOf(" ") > 0 
                     ? resourceName.Substring(resourceName.IndexOf(" ") + 1, 1) 
                     : "");
                resourceRow.RES_TYPE = (int)resourceType;
                resourceDs.Resources.AddResourcesRow(resourceRow);
                resourceSvc.CreateResources(resourceDs, false, true);
                return resourceRow.RES_UID;
            }
        }

        private static PSLibrary.Filter GetResourceAssignmentFilter(Guid[] resources)
        {
            SvcResource.ResourceAssignmentDataSet resourceAssignmentDs = 
                new SvcResource.ResourceAssignmentDataSet();
            PSLibrary.Filter resourceFilter = new PSLibrary.Filter();

            resourceFilter.FilterTableName = resourceAssignmentDs.ResourceAssignment.TableName;
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceFilter.FilterTableName, 
                resourceAssignmentDs.ResourceAssignment.RES_UIDColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceFilter.FilterTableName,
                resourceAssignmentDs.ResourceAssignment.RES_NAMEColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceFilter.FilterTableName, 
                resourceAssignmentDs.ResourceAssignment.TASK_UIDColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceFilter.FilterTableName, 
                resourceAssignmentDs.ResourceAssignment.TASK_NAMEColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceFilter.FilterTableName, 
                resourceAssignmentDs.ResourceAssignment.ASSN_UIDColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceFilter.FilterTableName, 
                resourceAssignmentDs.ResourceAssignment.ASSN_START_DATEColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceFilter.FilterTableName, 
                resourceAssignmentDs.ResourceAssignment.ASSN_FINISH_DATEColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));

            //List<PSLibrary.Filter.FieldOperator> resourceFieldOps = new List<PSLibrary.Filter.FieldOperator>();
            PSLibrary.Filter.IOperator[] fos = new PSLibrary.Filter.IOperator[resources.Length];

            for (int i = 0; i < resources.Length; i++)
            {
                fos[i] = new PSLibrary.Filter.FieldOperator(
                    PSLibrary.Filter.FieldOperationType.Equal, 
                    resourceAssignmentDs.ResourceAssignment.RES_UIDColumn.ColumnName, 
                    resources[i]);
            }

            PSLibrary.Filter.LogicalOperator lo = 
                new Microsoft.Office.Project.Server.Library.Filter.LogicalOperator(
                    PSLibrary.Filter.LogicalOperationType.Or, fos);

            resourceFilter.Criteria = lo;
            return resourceFilter;
        }
        // Writes all table contents to the console in a relatively readable way.
        private static void WriteTablesToConsole(System.Data.DataTableCollection theTables)
        {
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            foreach (System.Data.DataTable table in theTables)
            {

                int[] columnWidths = new int[table.Columns.Count];
                int tableWidth = 0;
                string dataString;
                Console.WriteLine("Table: " + table.TableName);

                // Write out the column names and get their spacing.
                StringBuilder tableRow = new StringBuilder();
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    columnWidths[i] = GetColumnWidth(table.Columns[i]);
                    tableRow.Append(table.Columns[i].ColumnName.PadRight(columnWidths[i]));

                    tableWidth += columnWidths[i];
                }
                // Add a space so it won't wrap.
                tableWidth += 1;
                // Make the console as wide as the widest table.
                Console.BufferWidth = (Console.BufferWidth > tableWidth 
                    ? Console.BufferWidth 
                    : tableWidth);
                tableRow.Append("\r\n");
                Console.Write(tableRow.ToString());

                // Write the data.
                foreach (DataRow row in table.Rows)
                {
                    tableRow = new StringBuilder();
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        dataString = row[i].ToString();

                        // Truncate output if it is wider than the desired column width.
                        if (dataString.Length >= columnWidths[i])
                        {
                            dataString = dataString.Substring(0, columnWidths[i] - 1);
                        }
                        // Add the output to the stringbuilder and pad right to fill
                        // up to the column width.
                        tableRow.Append(dataString.PadRight(columnWidths[i]));
                    }
                    tableRow.Append("\r\n");
                    Console.Write(tableRow.ToString());
                }
                Console.Write("\r\n".PadLeft(tableWidth, '-'));
            }
            Console.ResetColor();
        }
        // Helper function for WriteTablesToConsole.
        private static int GetColumnWidth(DataColumn column)
        {
            // Note: may not handle byte[]data types well.
            const int MAX_COL_WIDTH = 40;
            int dataWidth = 0;

            // Return 12 for numbers, 30 for dates, and string width for strings.
            switch (column.DataType.UnderlyingSystemType.ToString())
            {
                case "System.Boolean":
                case "System.Byte":
                case "System.Byte[]":
                case "System.Char":
                case "System.Decimal":
                case "System.Double":
                case "System.Int16":
                case "System.Int32":
                case "System.Int64":
                case "System.SByte":
                case "System.Single":
                case "System.UInt16":
                case "System.UInt32":
                case "System.UInt64":
                    dataWidth = 12;
                    break;
                case "System.DateTime":
                case "System.TimeSpan":
                    dataWidth = 30;
                    break;
                case "System.Guid":
                    dataWidth = 37;
                    break;
                case "System.String":
                    // If it has a maxlength, use it
                    if (column.MaxLength > 0)
                    {
                        dataWidth = column.MaxLength;
                    }
                    else
                    {
                        // Otherwise use the max col width
                        dataWidth = MAX_COL_WIDTH;
                    }
                    break;
                default:
                    dataWidth = column.ColumnName.Length;
                    break;
            }
            // Truncate if over the maximum length.
            if (dataWidth > MAX_COL_WIDTH)
            {
                dataWidth = MAX_COL_WIDTH;
            }
            // Always be at least as wide as the colum name.
            return (column.ColumnName.Length > (dataWidth) 
                ? column.ColumnName.Length + 1 
                : dataWidth);
        }
        // Create a sample project for use in this example.
        static private Guid CreateSampleProject(SvcProject.Project projectSvc, 
            SvcQueueSystem.QueueSystem q)
        {
            SvcProject.ProjectDataSet projectDs = new SvcProject.ProjectDataSet();
            Guid jobId;

            // Create the project
            SvcProject.ProjectDataSet.ProjectRow projectRow = 
                projectDs.Project.NewProjectRow();
            Guid projectId = Guid.NewGuid();

            projectRow.PROJ_UID = projectId;
            projectRow.PROJ_NAME = "Its a wonderful project at " 
                + DateTime.Now.ToShortDateString().Replace("/", "") 
                + " " + DateTime.Now.ToShortTimeString().Replace(":", "") + " " 
                + DateTime.Now.ToShortTimeString().Replace(":", "") + " " 
                + DateTime.Now.Millisecond.ToString();
            projectRow.PROJ_TYPE = (int)PSLibrary.Project.ProjectType.Project;
            projectDs.Project.AddProjectRow(projectRow);

            // Add some tasks.
            SvcProject.ProjectDataSet.TaskRow taskOne = projectDs.Task.NewTaskRow();
            taskOne.PROJ_UID = projectId;
            taskOne.TASK_UID = Guid.NewGuid();
            // Task Duration format must be specified.
            taskOne.TASK_DUR_FMT = (int)PSLibrary.Task.DurationFormat.Day;
            taskOne.TASK_DUR = 4800;  // 8 hours in duration units (minute/10).
            taskOne.TASK_NAME = "Task One";
            taskOne.TASK_START_DATE = System.DateTime.Now.AddDays(1);
            projectDs.Task.AddTaskRow(taskOne);

            SvcProject.ProjectDataSet.TaskRow taskTwo = projectDs.Task.NewTaskRow();
            taskTwo.PROJ_UID = projectId;
            taskTwo.TASK_UID = Guid.NewGuid();
            // Task Duration format must be specified.
            taskTwo.TASK_DUR_FMT = (int)PSLibrary.Task.DurationFormat.Day;
            taskTwo.TASK_DUR = 4800;  // 8 hours in duration units (minute/10).
            taskTwo.TASK_NAME = "Task Two";
            projectDs.Task.AddTaskRow(taskTwo);

            // Make task two dependent on task one
            SvcProject.ProjectDataSet.DependencyRow dependency = 
                projectDs.Dependency.NewDependencyRow();
            dependency.LINK_UID = Guid.NewGuid();
            dependency.PROJ_UID = projectId;
            dependency.LINK_PRED_UID = taskOne.TASK_UID;
            dependency.LINK_SUCC_UID = taskTwo.TASK_UID;
            dependency.LINK_TYPE = 1;  //Finish to Start
            dependency.LINK_LAG_FMT = (int)PSLibrary.Task.DurationFormat.Hour;
            dependency.LINK_LAG = 0;
            projectDs.Dependency.AddDependencyRow(dependency);

            // Add a summary task.
            SvcProject.ProjectDataSet.TaskRow taskOthers = projectDs.Task.NewTaskRow();
            taskOthers.PROJ_UID = projectId;
            taskOthers.TASK_UID = Guid.NewGuid();
            taskOthers.TASK_NAME = "Other Tasks";
            projectDs.Task.AddTaskRow(taskOthers);

            // Add some sub-tasks.

            SvcProject.ProjectDataSet.TaskRow taskThree = projectDs.Task.NewTaskRow();
            taskThree.PROJ_UID = projectId;
            taskThree.TASK_UID = Guid.NewGuid();
            taskThree.TASK_NAME = "Task Three";

            //Task Duration format must be specified
            taskThree.TASK_DUR_FMT = (int)PSLibrary.Task.DurationFormat.Day;
            taskThree.TASK_DUR = 4800; // 8 hours in duration units (minute/10).
            taskThree.TASK_PARENT_UID = taskOthers.TASK_UID;
            taskThree.TASK_OUTLINE_LEVEL = 2;
            projectDs.Task.AddTaskRow(taskThree);

            SvcProject.ProjectDataSet.TaskRow taskFour = projectDs.Task.NewTaskRow();
            taskFour.PROJ_UID = projectId;
            taskFour.TASK_UID = Guid.NewGuid();
            //Task Duration format must be specified
            taskFour.TASK_DUR_FMT = (int)PSLibrary.Task.DurationFormat.Day;
            taskFour.TASK_DUR = 4800;  // 8 hours in duration units (minute/10).
            taskFour.TASK_NAME = "Task Four";
            taskFour.TASK_PARENT_UID = taskOthers.TASK_UID;
            taskFour.TASK_OUTLINE_LEVEL = 2;
            projectDs.Task.AddTaskRow(taskFour);


            // Make task four dependent on task three
            dependency = projectDs.Dependency.NewDependencyRow();
            dependency.LINK_UID = Guid.NewGuid();
            dependency.PROJ_UID = projectId;
            dependency.LINK_PRED_UID = taskThree.TASK_UID;
            dependency.LINK_SUCC_UID = taskFour.TASK_UID;
            dependency.LINK_TYPE = 1;  // Finish to Start.
            dependency.LINK_LAG_FMT = (int)PSLibrary.Task.DurationFormat.Hour;
            dependency.LINK_LAG = 0;
            projectDs.Dependency.AddDependencyRow(dependency);

            // Make others task dependent on task two
            dependency = projectDs.Dependency.NewDependencyRow();
            dependency.LINK_UID = Guid.NewGuid();
            dependency.PROJ_UID = projectId;
            dependency.LINK_PRED_UID = taskTwo.TASK_UID;
            dependency.LINK_SUCC_UID = taskOthers.TASK_UID;
            dependency.LINK_TYPE = 1;//Finish to Start
            dependency.LINK_LAG_FMT = (int)PSLibrary.Task.DurationFormat.Hour;
            dependency.LINK_LAG = 0;
            projectDs.Dependency.AddDependencyRow(dependency);

            // Add Some Resources.
            SvcProject.ProjectDataSet.ProjectResourceRow resourceOne = projectDs.ProjectResource.NewProjectResourceRow();
            resourceOne.PROJ_UID = projectId;
            resourceOne.RES_UID = Guid.NewGuid();
            resourceOne.RES_NAME = "Brynja Sigrídur Blomsterberg";
            resourceOne.RES_INITIALS = "BSB";
            projectDs.ProjectResource.AddProjectResourceRow(resourceOne);
            CreateAssignment(projectDs, taskOne.TASK_UID, resourceOne.RES_UID);
            CreateAssignment(projectDs, taskTwo.TASK_UID, resourceOne.RES_UID);

            SvcProject.ProjectDataSet.ProjectResourceRow resourceTwo = 
                projectDs.ProjectResource.NewProjectResourceRow();
            resourceTwo.PROJ_UID = projectId;
            resourceTwo.RES_UID = Guid.NewGuid();
            resourceTwo.RES_NAME = "Ioannis Xylaras";
            resourceTwo.RES_INITIALS = "IX";
            projectDs.ProjectResource.AddProjectResourceRow(resourceTwo);
            CreateAssignment(projectDs, taskOne.TASK_UID, resourceTwo.RES_UID);
            CreateAssignment(projectDs, taskTwo.TASK_UID, resourceTwo.RES_UID);
            CreateAssignment(projectDs, taskThree.TASK_UID, resourceTwo.RES_UID);
            CreateAssignment(projectDs, taskFour.TASK_UID, resourceTwo.RES_UID);

            // Save the project to the database.
            jobId = Guid.NewGuid();
            projectSvc.QueueCreateProject(jobId, projectDs, false);
            WaitForQueue(q, jobId);
            return projectRow.PROJ_UID;
        }
        // Helper function for CreateSampleProject, to make simple assignments.
        private static void CreateAssignment(SvcProject.ProjectDataSet projectDs, 
            Guid taskGuid, Guid resourceGuid)
        {
            SvcProject.ProjectDataSet.AssignmentRow assnRow = 
                projectDs.Assignment.NewAssignmentRow();
            assnRow.PROJ_UID = projectDs.Project[0].PROJ_UID;
            assnRow.ASSN_UID = Guid.NewGuid();
            assnRow.TASK_UID = taskGuid;
            assnRow.RES_UID = resourceGuid;
            projectDs.Assignment.AddAssignmentRow(assnRow);
        }
        // Wait for the job to finish.
        // Output job status to the console.
        static private void WaitForQueue(SvcQueueSystem.QueueSystem q, Guid jobId)
        {
            SvcQueueSystem.JobState jobState;
            const int QUEUE_WAIT_TIME = 1; // One second.
            bool jobDone = false;
            string xmlError = string.Empty;
            int wait = 0;

            //Wait for the project to get through the queue
            // - get the estimated wait time in seconds.
            wait = q.GetJobWaitTime(jobId);

            Console.Write("Waiting on queue. Estimate: {0} seconds.\r\n ", wait);

            // Wait until the queue job is done.

            do
            {
                // Get the job state.
                jobState = q.GetJobCompletionState(jobId, out xmlError);

                if (jobState == SvcQueueSystem.JobState.Success)
                {
                    jobDone = true;
                }
                else
                {
                    if (jobState == SvcQueueSystem.JobState.Unknown
                        || jobState == SvcQueueSystem.JobState.Failed
                        || jobState == SvcQueueSystem.JobState.FailedNotBlocking
                        || jobState == SvcQueueSystem.JobState.CorrelationBlocked
                        || jobState == SvcQueueSystem.JobState.Canceled)
                    {
                        // If the job failed, error out.
                        throw (new ApplicationException("Queue request failed " 
                            + jobState + " for Job ID " + jobId + ".\r\n" + xmlError));
                    }
                    else
                    {
                        // Console.WriteLine("Job State: " + jobState + " for Job ID: " + jobId);
                        Console.Write("~");
                        Thread.Sleep(QUEUE_WAIT_TIME * 1000);
                    }
                }
            }
            while (!jobDone);

            Console.Write("\r\n");
        }

        private static PSLibrary.Filter GetResourceFilter(Guid[] resources)
        {
            SvcResource.ResourceDataSet resourceDs = new SvcResource.ResourceDataSet();
            PSLibrary.Filter resourceFilter = new PSLibrary.Filter();

            resourceFilter.FilterTableName = resourceDs.Resources.TableName;
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceDs.Resources.TableName, 
                resourceDs.Resources.RES_UIDColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceDs.Resources.TableName, 
                resourceDs.Resources.RES_NAMEColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceDs.Resources.TableName, 
                resourceDs.Resources.RES_INITIALSColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceDs.Resources.TableName, 
                resourceDs.Resources.RES_TYPEColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceDs.Resources.TableName, 
                resourceDs.Resources.RES_CODEColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));
            resourceFilter.Fields.Add(new PSLibrary.Filter.Field(resourceDs.Resources.TableName, 
                resourceDs.Resources.RES_TIMESHEET_MGR_UIDColumn.ColumnName, 
                PSLibrary.Filter.SortOrderTypeEnum.None));

            PSLibrary.Filter.IOperator[] fos = new PSLibrary.Filter.IOperator[resources.Length];

            for (int i = 0; i < resources.Length; i++)
            {
                fos[i] = new PSLibrary.Filter.FieldOperator(
                    PSLibrary.Filter.FieldOperationType.Equal, 
                    resourceDs.Resources.RES_UIDColumn.ColumnName, resources[i]);
            }

            PSLibrary.Filter.LogicalOperator lo = 
                new Microsoft.Office.Project.Server.Library.Filter.LogicalOperator(
                    PSLibrary.Filter.LogicalOperationType.Or, fos);

            resourceFilter.Criteria = lo;
            return resourceFilter;
        }
        #endregion
    }
}

См. также

Справочные материалы

Resource класс

Элементы Resource

Пространство имен WebSvcResource

Другие ресурсы

How to: Use a Filter Parameter with PSI Methods