Создание, извлечение, обновление и удаление проектов с помощью Project Server JavaScript

В сценариях в этой статье показано, как получить текущий экземпляр ProjectContext. получение и итерации коллекции опубликованных проектов на сервере; создайте, извлеките, проверка и удалите проект с помощью объектной модели JavaScript Project Server и измените свойства проекта.

Примечание.

Эти сценарии определяют пользовательский код в разметке страницы приложения SharePoint, но не используют файл кода программной части, создаваемый Visual Studio 2012 для страницы.

Предварительные требования для работы с проектами Project Server 2013 в объектной модели JavaScript

Чтобы выполнить описанные в этой статье сценарии, необходимо установить и настроить следующие продукты:

  • SharePoint Server 2013
  • Project Server 2013
  • Visual Studio 2012
  • Инструменты разработчика Office для Visual Studio 2012

У вас также должны быть разрешения на развертывание расширения в SharePoint Server 2013 и участие в проектах.

Примечание.

В этих инструкциях предполагается, что разработка выполняется на компьютере под управлением Project Server 2013.

Создание решения Visual Studio

Ниже описано, как создать решение Visual Studio 2012, содержащее проект SharePoint и страницу приложения. Страница содержит логику для работы с проектами.

Создание проекта SharePoint в Visual Studio

  1. На компьютере под управлением Project Server 2013 запустите Visual Studio 2012 от имени администратора.

  2. В строке меню выберите пункты Файл, Создать и Проект.

  3. В раскрывающемся списке в верхней части диалогового окна Новый проект выберите пункт .NET Framework 4.5.

  4. В категории Шаблон Office/SharePoint выберите Решения SharePoint, а затем выберите шаблон Проект SharePoint 2013 .

  5. Присвойте проекту имя ProjectsJSOM и нажмите кнопку ОК .

  6. В диалоговом окне Мастер настройки SharePoint выберите Развернуть как решение фермы и затем нажмите кнопку Готово.

  7. Измените значение свойства URL-адрес сайта для проекта ProjectsJSOM в соответствии с URL-адресом экземпляра Project Web App (например, https://ServerName/PWA).

Создание страницы приложения в Visual Studio

  1. В Обозреватель решений откройте контекстное меню проекта ProjectsJSOM, а затем добавьте сопоставленную папку SharePoint Layouts.

  2. В папке Макеты откройте контекстное меню для папки ProjectsJSOM , а затем добавьте новую страницу приложения SharePoint с именем ProjectsList.aspx.

  3. Откройте контекстное меню для страницы ProjectsList.aspx и выберите Задать в качестве элемента запуска.

  4. В разметке для страницы ProjectsList.aspx определите элементы управления пользовательского интерфейса внутри тегов asp:Content "Main" следующим образом.

     <table width="100%" id="tblProjects">
         <tr id="headerRow">
             <th width="25%" align="left">Name</th>
             <th width="25%" align="left">Description</th>
             <th width="25%" align="left">Start Date</th>
             <th width="25%" align="left">ID</th>
         </tr>
     </table>
     <textarea id="txtGuid" rows="1" cols="35">Paste the project GUID here.</textarea>
     <button id="btnSend" type="button"></button><br />
     <span id="spanMessage" style="color: #FF0000;"></span>
    

    Примечание.

    [!Примечание] Эти элементы управления не могут быть использованы в каждом сценарии. Например, в сценарии "Создание проектов" не используются элементы управления textarea и button .

  5. После закрывающего тега span добавьте тег SharePoint:ScriptLink , тег SharePoint:FormDigest и теги скриптов следующим образом.

     <SharePoint:ScriptLink id="ScriptLink" name="PS.js" runat="server" ondemand="false" localizable="false" loadafterui="true" />
     <SharePoint:FormDigest id="FormDigest" runat="server" />
     <script type="text/javascript">
         // Replace this comment with the code for your scenario.
     </script>
    

    Тег SharePoint:ScriptLink ссылается на файл PS.js, который определяет объектную модель JavaScript для Project Server 2013. Тег SharePoint:FormDigest создает сообщение дайджеста для проверки подлинности при необходимости в операции, обновлять содержимое сервера.

  6. Замените комментарий-заполнитель кодом из одной из следующих процедур:

  7. Чтобы протестировать страницу приложения, в панели меню выберите команды Отладка, Начать отладку. Если вам будет предложено изменить файл web.config, нажмите кнопку ОК.

Создание проектов Project Server 2013 с помощью объектной модели JavaScript

Процедура, описанная в этом разделе, создает проекты с помощью объектной модели JavaScript. Процедура включает в себя следующие общие шаги:

  1. Получение текущего экземпляра ProjectContext .

  2. Создайте объект ProjectCreationInformation , чтобы указать начальные свойства проекта. Укажите необходимое свойство name с помощью функции ProjectCreationInformation.set_name .

  3. Получите опубликованные проекты с сервера с помощью функции ProjectContext.get_projects . Функция get_projects возвращает объект ProjectCollection .

  4. Добавьте новый проект в коллекцию с помощью функции ProjectCollection.add и передав объект ProjectCreationInformation .

  5. Обновите коллекцию с помощью функции ProjectCollection.update и функции ProjectContext.waitForQueueAsync . Функция обновления возвращает объект QueueJob , который передается в waitForQueueAsync. Этот вызов также публикует проект.

Вставьте следующий код между тегами скрипта , добавленными на странице Создание приложения в Visual Studio .

    // Declare a global variable to store the project collection.
    var projects;
    // Ensure that the PS.js file is loaded before your custom code runs.
    SP.SOD.executeOrDelayUntilScriptLoaded(CreateProject, "PS.js");
    // Add a project the projects collection.
    function CreateProject() {
        
        // Initialize the current client context.
        var projContext = PS.ProjectContext.get_current();
        // Initialize a ProjectCreationInformation object and specify properties
        // for the new project.
        // The Name property is required and must be unique.
        var creationInfo = new PS.ProjectCreationInformation();
        creationInfo.set_name("Test Project 1");
        // Specify optional properties for the new project.
        // If not specified, the Start property uses the current date and the
        // EnterpriseProjectTypeId property uses the default EPT.
        creationInfo.set_description("Created through the JSOM.");
        creationInfo.set_start("2013-10-01 09:00:00.000");
        // Get the projects collection.
        projects = projContext.get_projects();
        // Add the new project to the projects collection.
        projects.add(creationInfo);
        // Add a second project to use in the deleting projects procedure.
        creationInfo.set_name("Test Project 2");
        projects.add(creationInfo);
        // Submit the request to update the collection on the server
        var updateJob = projects.update();
        projContext.waitForQueueAsync(updateJob, 10, GetProjects);
    }
    // Get the projects collection.
    function GetProjects(response) {
        // This call demonstrates that you can get the context from the 
        // ProjectCollection object.
        var projContext = projects.get_context();
        // Register the request for information that you want to run on the server.
        // This call includes an optional "Include" parameter to request only the Name, Description,
        // StartDate, and Id properties of the projects in the collection.
        projContext.load(projects, 'Include(Name, Description, StartDate, Id)');
        // Run the request on the server.
        projContext.executeQueryAsync(IterateThroughProjects, QueryFailed);
    }
    // Iterate through the projects collection.
    function IterateThroughProjects(response) {
        // Get the enumerator and iterate through the collection.
        var enumerator = projects.getEnumerator();
        while (enumerator.moveNext()) {
            var project = enumerator.get_current();
            // Create and populate a row with the values for the project's Name, Description,
            // StartDate, and Id properties.
            var row = tblProjects.insertRow();
            row.insertCell().innerText = project.get_name();
            row.insertCell().innerText = project.get_description();
            row.insertCell().innerText = project.get_startDate();
            row.insertCell().innerText = project.get_id();
        }
        // This scenario does not use the textarea or button controls.
        $get("txtGuid").disabled = true;
        $get("btnSend").disabled = true;
    }
    function QueryFailed(sender, args) {
        $get("spanMessage").innerText = 'Request failed: ' + args.get_message();
    }

Обновление проектов Project Server 2013 с помощью объектной модели JavaScript

Процедура в этом разделе обновляет свойство startDate проекта с помощью объектной модели JavaScript. Процедура включает в себя следующие общие шаги:

  1. Получение текущего экземпляра ProjectContext .

  2. Получите опубликованные проекты с сервера с помощью функции ProjectContext.get_projects . Функция get_projects возвращает объект ProjectCollection .

  3. Выполните запрос на сервере с помощью функции ProjectContext.load и функции ProjectContext.executeQueryAsync .

  4. Получите объект PublishedProject с помощью функции ProjectContext.getById .

  5. Извлеките целевой проект с помощью функции Project.checkOut . Функция checkOut возвращает черновую версию опубликованного проекта.

  6. Измените дату начала проекта с помощью функции DraftProject.set_startDate .

  7. Опубликуйте проект с помощью функции DraftProject.publish и функции ProjectContext.waitForQueueAsync . Функция публикации возвращает объект QueueJob , который передается в waitForQueueAsync.

Вставьте следующий код между тегами скрипта , добавленными на странице Создание приложения в Visual Studio .

    // Declare global variables.
    var projContext;
    var projects;
    // Ensure that the PS.js file is loaded before your custom code runs.
    SP.SOD.executeOrDelayUntilScriptLoaded(GetProjects, "PS.js");
    // Get the projects collection.
    function GetProjects() {
        // Initialize the current client context.
        projContext = PS.ProjectContext.get_current();
        // Get the projects collection.
        projects = projContext.get_projects();
        // Register the request for information that you want to run on the server.
        // This call includes an optional "Include" parameter to request only the Name, Description,
        // StartDate, and Id properties of the projects in the collection.
        projContext.load(projects, 'Include(Name, Description, StartDate, Id)');
        // Run the request on the server.
        projContext.executeQueryAsync(IterateThroughProjects, QueryFailed);
    }
    // Iterate through the projects collection.
    function IterateThroughProjects(response) {
        // Get the enumerator and iterate through the collection.
        var enumerator = projects.getEnumerator();
        while (enumerator.moveNext()) {
            var project = enumerator.get_current();
            // Create and populate a row with the values for the project's Name, Description,
            // StartDate, and Id properties.
            var row = tblProjects.insertRow();
            row.insertCell().innerText = project.get_name();
            row.insertCell().innerText = project.get_description();
            row.insertCell().innerText = project.get_startDate();
            row.insertCell().innerText = project.get_id();
        }
        // Initialize button properties.
        $get("btnSend").onclick = function () { ChangeProject(); };
        $get("btnSend").innerText = "Update";
    }
    // Change the project's start date.
    function ChangeProject() {
        // Get the identifier of the target project.
        var targetGuid = $get("txtGuid").innerText;
        // Get the target project and then check it out. The checkOut function
        // returns the draft version of the project.
        var project = projects.getById(targetGuid);
        var draftProject = project.checkOut();
        // Set the new property value and then publish the project.
        // Specify "true" to also check the project in.
        draftProject.set_startDate("2013-12-31 09:00:00.000");
        var publishJob = draftProject.publish(true);
        // Register the job that you want to run on the server and specify the
        // timeout duration and callback function.
        projContext.waitForQueueAsync(publishJob, 10, QueueJobSent);
    }
    // Print the JobState return code, which gives the status of the queue job.
    function QueueJobSent(response) {
        $get("spanMessage").innerText = 'JobState = ' + response + '. Wait a few seconds, then refresh the page to see your changes.';
    }
    function QueryFailed(sender, args) {
        $get("spanMessage").innerText = 'Request failed: ' + args.get_message();
    }

Удаление проектов Project Server 2013 с помощью объектной модели JavaScript

Процедура, описанная в этом разделе, удаляет проект с помощью объектной модели JavaScript. Процедура включает в себя следующие общие шаги:

  1. Получение текущего экземпляра ProjectContext .

  2. Получите опубликованные проекты с сервера с помощью функции ProjectContext.get_projects . Функция get_projects возвращает объект ProjectCollection .

  3. Выполните запрос на сервере с помощью функции ProjectContext.load и функции ProjectContext.executeQueryAsync .

  4. Получите объект PublishedProject с помощью функции ProjectCollection.getById .

  5. Удалите проект, передав его в функцию ProjectCollection.remove .

  6. Обновите коллекцию с помощью функции ProjectCollection.update и функции ProjectContext.waitForQueueAsync . Функция обновления возвращает объект QueueJob , который передается в waitForQueueAsync.

Вставьте следующий код между тегами скрипта , добавленными на странице Создание приложения в Visual Studio .

    // Declare global variables.
    var projContext;
    var projects;
    // Ensure that the PS.js file is loaded before your custom code runs.
    SP.SOD.executeOrDelayUntilScriptLoaded(GetProjects, "PS.js");
    // Get the projects collection.
    function GetProjects() {
        // Initialize the current client context.
        projContext = PS.ProjectContext.get_current();
        // Get the projects collection.
        projects = projContext.get_projects();
        // Register the request for information that you want to run on the server.
        // This call includes an optional "Include" parameter to request only the Name, Description,
        // StartDate, and Id properties of the projects in the collection.
        projContext.load(projects, 'Include(Name, Description, StartDate, Id)');
        // Run the request on the server.
        projContext.executeQueryAsync(IterateThroughProjects, QueryFailed);
    }
    // Iterate through the projects collection.
    function IterateThroughProjects(response) {
        // Get the enumerator and iterate through the collection.
        var enumerator = projects.getEnumerator();
        while (enumerator.moveNext()) {
            var project = enumerator.get_current();
            // Create and populate a row with the values for the project's Name, Description,
            // StartDate, and Id properties.
            var row = tblProjects.insertRow();
            row.insertCell().innerText = project.get_name();
            row.insertCell().innerText = project.get_description();
            row.insertCell().innerText = project.get_startDate();
            row.insertCell().innerText = project.get_id();
        }
        // Initialize button properties.
        $get("btnSend").onclick = function () { DeleteProject(); };
        $get("btnSend").innerText = "Delete";
    }
    // Delete the project.
    function DeleteProject() {
        // Get the identifier of the target project.
        var targetGuid = $get("txtGuid").innerText;
        // Get the target project and then remove it from the collection.
        var project = projects.getById(targetGuid);
        projects.remove(project);
        var removeJob = projects.update();
        // Register the job that you want to run on the server and specify the
        // timeout duration and callback function.
        projContext.waitForQueueAsync(removeJob, 10, QueueJobSent);
    }
    // Print the JobState return code, which gives the status of the queue job.
    function QueueJobSent(response) {
        $get("spanMessage").innerText = 'JobState = ' + response + '. Wait a few seconds, then refresh the page to see your changes.';
    }
    function QueryFailed(sender, args) {
        $get("spanMessage").innerText = 'Request failed: ' + args.get_message();
    }

См. также