public async Task <DraftProject> CheckOutAsync(PublishedProject publishedProject)
        {
            if (publishedProject == null)
            {
                throw new ArgumentNullException(nameof(publishedProject));
            }

            DraftProject draftProject = null;

            try
            {
                await System.Threading.Tasks.Task.Run(() =>
                {
                    draftProject = publishedProject.CheckOut();
                });
            }
            catch (Exception ex)
            {
                // TODO: LOG ERROR!

                throw new CsomClientException($"Unexcepted error checking out a project. " +
                                              $"project id is {publishedProject.Id}. " +
                                              $"Project context url is {_projectContext.Url}.", ex);
            }

            return(draftProject);
        }
示例#2
0
    static void Main(string[] args)
    {
        SecureString secpassword = new SecureString();

        foreach (char c in password.ToCharArray())
        {
            secpassword.AppendChar(c);
        }


        ProjectContext pc = new ProjectContext(pwaPath);

        pc.Credentials = new SharePointOnlineCredentials(username, secpassword);

        //now you can query
        pc.Load(pc.Projects);
        pc.ExecuteQuery();
        foreach (var p in pc.Projects)
        {
            Console.WriteLine(p.Name);
        }

        //Or Create a new project
        ProjectCreationInformation newProj = new ProjectCreationInformation()
        {
            Id    = Guid.NewGuid(),
            Name  = "[your project name]",
            Start = DateTime.Today.Date
        };
        PublishedProject newPublishedProj = pc.Projects.Add(newProj);
        QueueJob         qJob             = pc.Projects.Update();

        JobState jobState = pc.WaitForQueue(qJob, /*timeout for wait*/ 10);
    }
        public async Task <bool> CheckInAsync(PublishedProject publishedProject)
        {
            if (publishedProject == null)
            {
                throw new ArgumentNullException(nameof(publishedProject));
            }

            bool result = false;

            try
            {
                if (publishedProject.IsCheckedOut)
                {
                    await System.Threading.Tasks.Task.Run(() =>
                    {
                        var queuedJob = publishedProject.Draft.CheckIn(true);
                        WaitForQueuedJobToComplete(queuedJob, $"adding a checking in a project with name {publishedProject.Name}");
                    });
                }

                result = true;
            }
            catch (Exception ex)
            {
                // TODO: LOG ERROR!

                throw new CsomClientException($"Unexcepted error removing a project. " +
                                              $"project id is {publishedProject.Id}. " +
                                              $"Project context url is {_projectContext.Url}.", ex);
            }

            return(result);
        }
示例#4
0
 public PublishedProject CreateProject(string prName, string description, DateTime startDate)
 {
     try
     {
         System.Console.Write("\nCreating project: {0} ...", prName);
         ProjectCreationInformation newProj = new ProjectCreationInformation();
         newProj.Id                      = Guid.NewGuid();
         newProj.Name                    = prName;
         newProj.Description             = description;
         newProj.Start                   = startDate;
         newProj.EnterpriseProjectTypeId = GetEptUid(basicEpt);
         PublishedProject newPublishedProj = _context.Projects.Add(newProj);
         QueueJob         qJob             = _context.Projects.Update();
         JobState         jobState         = _context.WaitForQueue(qJob, timeoutSeconds);
         if (jobState == JobState.Success)
         {
             return(newPublishedProj);
         }
         else
         {
             return(null);
         }
     }
     catch (Exception ex)
     {
         System.Console.ForegroundColor = ConsoleColor.Red;
         System.Console.WriteLine("\nError: {0}", ex.Message);
         System.Console.ResetColor();
         return(null);
     }
 }
        private void RemoveResources()
        {
            PublishedProject            publishedProject = null;
            DraftProject                draftProject;
            List <DraftProjectResource> draftProjectResourceresList = new List <DraftProjectResource>();

            LV_Projects.InvokeIfRequired(s => publishedProject = (PublishedProject)s.SelectedItems[0].Tag);

            LV_ProjectResources.InvokeIfRequired(s =>
            {
                ListView.SelectedListViewItemCollection selectedItems = s.SelectedItems;
                draftProjectResourceresList.AddRange(selectedItems.Cast <ListViewItem>().Select(selectedItem => (DraftProjectResource)selectedItem.Tag));
            });

            if (draftProjectResourceresList.Any())
            {
                draftProject = publishedProject.IsCheckedOut ? publishedProject.Draft : publishedProject.CheckOut();

                draftProjectResourceresList.ForEach(r =>
                {
                    Log.WriteVerbose(new SourceInfo(), TB_Status, "Removing Resource:{0} from Project:{1}.", r.Name, publishedProject.Draft.Name);
                    draftProject.ProjectResources.Remove(r);
                });
                QueueJob queueJob = draftProject.Update();
                Log.WriteVerbose(new SourceInfo(), TB_Status, _bgeRemoveProjectResources, "Waiting for the Project Update job to complete.");
                CsomHelper.ExecuteAndWait(queueJob, TB_Status);
            }
            Log.WriteVerbose(new SourceInfo(), TB_Status, _bgeRemoveProjectResources, "Refreshing Project resources.");
            GetDraftTeamForSelectedProject();
        }
        public void RenameTasks()
        {
            DateTime dateTimeControl = new DateTime(2018, 9, 26);
            var      list            = _dbPortal.RenameTasksKBM.ToList();
            var      projCollection  = projContext.LoadQuery(projContext.Projects.Where(d => d.CreatedDate > dateTimeControl));

            projContext.ExecuteQuery();
            foreach (var prj in projCollection)
            {
                PublishedProject project = prj;
                DraftProject     draft   = project.CheckOut();
                projContext.Load(draft, p => p.Tasks);
                projContext.ExecuteQuery();
                if (draft.Tasks.Count > 0)
                {
                    foreach (var task in draft.Tasks.ToList())
                    {
                        foreach (var baseTask in list)
                        {
                            if (baseTask.@base == task.Name)
                            {
                                task.Name = baseTask.@this;
                            }
                        }
                    }
                }
                draft.Update();
                Console.WriteLine(prj.Name);
                JobState jobState = projContext.WaitForQueue(draft.Publish(true), 20);
            }
        }
 public Task <PublishedProject> LinkToEnterpriseResource(PublishedProject publishedProject, EnterpriseResource enterpriseResource)
 {
     return(LinkToEnterpriseResources(publishedProject, new List <EnterpriseResource>()
     {
         enterpriseResource
     }));
 }
示例#8
0
        private static void UpdateProjectCustomField(Guid ProjectId)
        {
            DraftProject projCheckedOut = null;

            try
            {
                Dictionary <string, object> projDict = new Dictionary <string, object>();


                using (ProjectContext projContext = new ProjectContext(PWAUrl))
                {
                    projContext.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;

                    var PrjList = projContext.LoadQuery(projContext.Projects.Where(proj => proj.Name == ""));

                    projContext.ExecuteQuery();
                    Guid pGuid = PrjList.First().Id;

                    PublishedProject proj2Edit = PrjList.First();
                    projCheckedOut = proj2Edit.CheckOut().IncludeCustomFields;
                    projContext.Load(projCheckedOut);
                    projContext.ExecuteQuery();

                    var cflist = projContext.LoadQuery(projContext.CustomFields.Where(cf => cf.Name == "Testcol"));
                    projContext.ExecuteQuery();
                    projCheckedOut.SetCustomFieldValue(cflist.FirstOrDefault().InternalName, "Entry_c8f0abff70f5e51180cc00155dd45b0a");

                    QueueJob qJob     = projCheckedOut.Publish(true);
                    JobState jobState = projContext.WaitForQueue(qJob, 70);
                }
            }
            catch (Exception ex)
            {
            }
        }
示例#9
0
        private async Task <bool> RequirementsAreMet(PublishedProject publishedProject, IEnumerable <AssignmentModel> assignmentModels)
        {
            bool result = false;

            // Ensure task id belongs to project
            if (publishedProject != null)
            {
                // Ensure resource ids exist
                var resourceTasks = assignmentModels.Select(async(am) => await _resourceClient.GetByIdAsync(am.ResourceId));
                var resoures      = await System.Threading.Tasks.Task.WhenAll(resourceTasks);

                if (resoures.All(r => r != null))
                {
                    // Ensure no other assignments with same ids exist
                    _projectContext.Load(publishedProject.Assignments);
                    await _projectContext.ExecuteQueryAsync();

                    var draftAssignment = publishedProject.Assignments.Where(dt => assignmentModels.Any(am => am.Id == dt.Id));
                    if (draftAssignment == null || !draftAssignment.Any())
                    {
                        result = true;
                    }
                }
            }

            return(result);
        }
        public DraftProject CheckOutProject(PublishedProject publishedProject)
        {
            logger.LogAndSendMessage(null, "CheckOutProject",
                                     publishedProject.Id, winServiceIterationUid,
                                     $"CheckOutProject START publishedProject.Id: {publishedProject.Id}",
                                     false, null);
            DraftProject draftProject = publishedProject.CheckOut();

            try
            {
                draftProject = GetDraftProject(draftProject, publishedProject.Id);
            }
            catch (Exception exception)
            {
                logger.LogAndSendMessage(null, "CheckOutProject",
                                         publishedProject.Id, winServiceIterationUid,
                                         $"CheckOutProject publishedProject.Id: {publishedProject.Id}",
                                         false, exception);
                if (draftProject != null)
                {
                    QueueJob job = draftProject.CheckIn(true);
                    JobState jobState;
                    WaitForQueue(job, publishedProject.Id, draftProject, out jobState);
                    draftProject = null;
                }
                //ExecuteQuery();
            }
            logger.LogAndSendMessage(null, "CheckOutProject",
                                     publishedProject.Id, winServiceIterationUid,
                                     $"CheckOutProject END publishedProject.Id: {publishedProject.Id}",
                                     false, null);
            return(draftProject);
        }
        public GivenAnAssignmentClientInstance()
        {
            IApplicationContext  applicationContext  = new ApplicationContext();
            IConfigurationRoot   configurationRoot   = ConfigurationRootFactory.Create(applicationContext);
            IConfigurationGetter configurationGetter = new ConfigurationGetter(configurationRoot);

            var projectContextOptions = configurationGetter.GetOptions <ProjectContextOptions>();
            var clientOptions         = configurationGetter.GetOptions <CsomClientOptions>();

            var projectContext = ProjectContextFactory.Build(projectContextOptions);

            _projectClient  = new ProjectClient(projectContext, clientOptions);
            _taskClient     = new TaskClient(projectContext, clientOptions);
            _resourceClient = new EnterpriseResourceClient(projectContext, clientOptions);

            _client = new AssignmentClient(projectContext, clientOptions);

            _publishedProject = CreateTestProject().Result;
            _publishedTask    = CreateTestTask().Result;

            _enterpriseResource  = CreateTestResource().Result;
            _enterpriseResource2 = CreateTestResource().Result;

            _publishedProject = _projectClient.LinkToEnterpriseResources(_publishedProject, new [] { _enterpriseResource, _enterpriseResource2 }).Result;
        }
示例#12
0
        public void TestConstructor_CheckLocationsExistBool()
        {
            var updatedProject = new PublishedProject(
                new User(1),
                1,
                "name",
                "description",
                1,
                "abcde1234567890",
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                DateTimeOffset.UtcNow,
                DateTimeOffset.UtcNow,
                1,
                null,
                null,
                null,
                null);
            var project = new Project
            {
                ProjectStatusId = ProjectStatus.Other.Id
            };
            var goalsExist           = true;
            var themesExist          = true;
            var pointsOfContactExist = true;
            var categoriesExist      = true;
            var objectivesExist      = true;
            var locationsExist       = false;
            var numberOfCategories   = 10;
            var numberOfObjectives   = 20;

            var instance = new ProjectServiceUpdateValidationEntity(
                updatedProject,
                project,
                new List <int>(),
                goalsExist,
                themesExist,
                pointsOfContactExist,
                categoriesExist,
                objectivesExist,
                locationsExist,
                numberOfObjectives,
                numberOfCategories,
                new List <int>(),
                new List <int>(),
                new List <int>(),
                new OfficeSettings(),
                new List <int>(),
                new List <int>());

            Assert.AreEqual(pointsOfContactExist, instance.PointsOfContactExist);
            Assert.AreEqual(themesExist, instance.ThemesExist);
            Assert.AreEqual(goalsExist, instance.GoalsExist);
            Assert.AreEqual(locationsExist, instance.LocationsExist);
        }
示例#13
0
        void buildReleaseRecord(EnterpriseManagementObject emoReleaseRecord, EnterpriseManagementObject emoProject)
        {
            try
            {
                //get the project associated with the original change request and query project server for it.
                var projectGuid = (Guid)emoProject[null, "GUID"].Value;
                projectConnector.LoadProject(projectGuid);
                //load the first level project task data
                PublishedProject project = projectConnector.Projects.FirstOrDefault(p => p.Id == projectGuid);

                if (project == null)
                {
                    EventLog.WriteEntry(strEventLogTitle, string.Format("Project was not found on Project Server.  It may have been removed.\r\n\r\nProject Name: {0}\r\nProject GUID: {1}",
                                                                        emoProject.DisplayName, (emoProject[null, "GUID"].Value == null) ? string.Empty : emoProject[null, "GUID"].Value.ToString()), EventLogEntryType.Warning);
                }
                else
                {
                    projectConnector.LoadProjectTaskData(project, 1);

                    //get all activities in the release record
                    var lstReleaseRecordActivites = emg.EntityObjects.GetRelatedObjects <EnterpriseManagementObject>(emoReleaseRecord.Id,
                                                                                                                     mprRelationships.First(r => r.Name == "System.WorkItemContainsActivity"),
                                                                                                                     TraversalDepth.OneLevel,
                                                                                                                     ObjectQueryOptions.Default);

                    buildActivitiesList(lstReleaseRecordActivites, emoReleaseRecord, emoProject, project);

                    EventLog.WriteEntry(strEventLogTitle, string.Format("Succsesfully processed '{0}' activities list.  Any changes will be submiited to the database.", emoReleaseRecord.DisplayName));
                }
            }
            catch (SharePoint.Client.ServerException ex)
            {
                exceptionsList.Add(new BuildReleaseRecordException(string.Format("An error occured while building '{0}' activities.  The related Project is '{1}'.", emoReleaseRecord.DisplayName, emoProject.DisplayName), ex));
            }
        }
示例#14
0
        public async Task <IEnumerable <PublishedAssignment> > GetAllAsync(PublishedProject publishedProject)
        {
            if (publishedProject == null)
            {
                throw new ArgumentNullException(nameof(publishedProject));
            }

            IEnumerable <PublishedAssignment> assignments = new List <PublishedAssignment>();

            try
            {
                _projectContext.Load(publishedProject.Assignments);
                await _projectContext.ExecuteQueryAsync();

                // Force a new list to avoid returning same list than stored in context
                assignments = new List <PublishedAssignment>(publishedProject.Assignments.ToArray());
            }
            catch (Exception ex)
            {
                // TODO: LOG ERROR!

                throw new CsomClientException($"Unexcepted error getting all project assignments. " +
                                              $"Published project name is {publishedProject.Name}. " +
                                              $"Project context url is {_projectContext.Url}.", ex);
            }

            return(assignments);
        }
示例#15
0
 public bool IsCheckedOut(PublishedProject published)
 {
     projContext.Load(published.Draft, P1 => P1.IsCheckedOut, P2 => P2.Name);
     projContext.ExecuteQuery();
     Console.WriteLine("project {0} 's IsCheckedOut is {1}", published.Name, published.IsCheckedOut);
     return(published.IsCheckedOut);
 }
        public async Task <PublishedProject> GetByNameAsync(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            PublishedProject publishedProject = null;

            try
            {
                IEnumerable <PublishedProject> publishedProjects =
                    _projectContext.LoadQuery(_projectContext.Projects.Where(p => p.Name == name));
                await _projectContext.ExecuteQueryAsync();

                if (publishedProjects.Any())
                {
                    publishedProject = publishedProjects.FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                // TODO: LOG ERROR!

                throw new CsomClientException($"Unexcepted error getting a project by name. " +
                                              $"Name searched is {name}. " +
                                              $"Project context url is {_projectContext.Url}.", ex);
            }

            return(publishedProject);
        }
        public async Task <bool> RemoveAsync(PublishedProject publishedProject)
        {
            if (publishedProject == null)
            {
                throw new ArgumentNullException(nameof(publishedProject));
            }

            bool result = false;

            try
            {
                await CheckInAsync(publishedProject);

                var clientResult = _projectContext.Projects.Remove(publishedProject);
                var queuedJob    = _projectContext.Projects.Update();
                WaitForQueuedJobToComplete(queuedJob, $"adding a removing a project with name {publishedProject.Name}");
                await _projectContext.ExecuteQueryAsync();

                result = clientResult.Value;
            }
            catch (Exception ex)
            {
                // TODO: LOG ERROR!

                throw new CsomClientException($"Unexcepted error removing a project. " +
                                              $"project id is {publishedProject.Id}. " +
                                              $"Project context url is {_projectContext.Url}.", ex);
            }

            return(result);
        }
示例#18
0
        public async Task <IEnumerable <PublishedAssignment> > AddRangeAsync(PublishedProject publishedProject, IEnumerable <AssignmentModel> assignmentModels)
        {
            if (publishedProject == null)
            {
                throw new ArgumentNullException(nameof(publishedProject));
            }
            if (assignmentModels == null)
            {
                throw new ArgumentNullException(nameof(assignmentModels));
            }

            List <PublishedAssignment> result = new List <PublishedAssignment>();

            try
            {
                if ((await RequirementsAreMet(publishedProject, assignmentModels)))
                {
                    // Ensure I have it check it out
                    await _projectClient.CheckInAsync(publishedProject);

                    var draftProject = await _projectClient.CheckOutAsync(publishedProject);

                    foreach (var assignmentModel in assignmentModels)
                    {
                        var draftAssignment = draftProject.Assignments.Add(_mapper.Map <AssignmentCreationInformation>(assignmentModel));
                        draftAssignment = _mapper.Map(assignmentModel, draftAssignment);

                        //var queuedJob = draftProject.Update();
                        //WaitForQueuedJobToComplete(queuedJob, $"updating a project with name {publishedProject.Name}");
                        //_projectContext.ExecuteQuery();
                    }

                    await _projectClient.PublishAndUpdate(draftProject, publishedProject.Name);

                    await _projectClient.CheckInAsync(publishedProject);

                    // reload the project after re-publishing it
                    var _republishedProjects = _projectContext.LoadQuery(
                        _projectContext.Projects
                        .Where(p => p.Id == publishedProject.Id).IncludeWithDefaultProperties(p => p.Assignments));
                    await _projectContext.ExecuteQueryAsync();

                    result = _republishedProjects.First().Assignments
                             .Where(a => assignmentModels.Any(am => am.Id == a.Id)).ToList();
                }
            }
            catch (Exception ex)
            {
                // TODO: LOG ERROR!

                throw new CsomClientException($"Unexcepted error adding a new assignments. " +
                                              $"Published project name is {publishedProject.Name}. " +
                                              $"Project context url is {_projectContext.Url}.", ex);
            }

            return(result);
        }
示例#19
0
        public bool Create(ProjectModel model)
        {
            if (model == null)
            {
                throw new ArgumentException("The ProjectModel is null.");
            }
            else
            {
                IEnumerable <PublishedProject> projects = GetEntities();
                this.availableResources = new ResourceCSOMClient().GetEntities();
                for (int i = 0; i < model.Count; i++)
                {
                    string projectName = model.NamePrefix + i.ToString();
                    if (projects.Any(item => item.Name == projectName))
                    {
                        // No need to do anything currently
                    }
                    else
                    {
                        try
                        {
                            // Create an empty project
                            PublishedProject project = CreateEmptyProject(projectName);

                            // Check out the project
                            DraftProject draftProject = CheckOutProject(project);

                            // Get resource for project
                            List <EnterpriseResource> projectResources = new List <EnterpriseResource>();
                            int[] resourcesIndex = RandomHelper.GetRandomIndex(model.ProjectTeamCount, this.availableResources.Count() - 1);
                            foreach (int index in resourcesIndex)
                            {
                                projectResources.Add(this.availableResources.ElementAt(index));
                            }

                            // Build team
                            BuildTeam(draftProject, projectResources);

                            // Create task
                            IEnumerable <IEnumerable <TaskCreationInformation> > tasks = CreateTask(model.TaskModel);

                            // Add task
                            AddTaskToProject(draftProject, tasks, projectResources, model.TaskModel.Assignments);

                            // Publish
                            PublishProject(draftProject);
                        }
                        catch (Exception ex)
                        {
                            LoggerHelper.Instance.Fail(string.Format("Filed to create Project: {0}.\nMessage: {1}. \nMore:{2} \nRetrying...", projectName, ex.Message, ex.StackTrace));
                        }
                    }
                }
            }

            return(true);
        }
        public DraftProject CheckOutProject(PublishedProject publishedProject, string systemNames, Guid projectUid)
        {
            DraftProject draftProject = null;

            try
            {
                if (publishedProject.IsCheckedOut)
                {
                    if (isOnline)
                    {
                        if (publishedProject.IsCheckedOut && publishedProject.CheckedOutBy?.Email != null)
                        {
                            EmailSender emailSender = new EmailSender();
                            emailSender.SendNotificationEmail(publishedProject.CheckedOutBy.Email,
                                                              $"Check-in project {publishedProject.Name} request",
                                                              $"Hello, {publishedProject.CheckedOutBy.Title}. This is 60i Administrator. I've found that several tasks in project {publishedProject.Name} should be synchronized with {systemNames}. " +
                                                              "Howerver I need to change some properties of these tasks, but project is checked-out to you. Please check-in it for a little time so I can do neccessary operations.");
                            return(null);
                        }
                    }
                    return(null);
                }
                draftProject = CheckOutProject(publishedProject);
                return(draftProject);
            }
            //catch (PropertyOrFieldNotInitializedException exception)
            //{
            //    logger.LogAndSendMessage($"CheckOutProject ProjectUid: {projectUid}");
            //    logger.LogAndSendMessage(exception);
            //    if (draftProject != null)
            //    {
            //        logger.LogAndSendMessage("ForceCheckInProject");
            //        QueueJob job = draftProject.CheckIn(true);
            //        WaitForQueue(job, projectUid, draftProject);
            //        //ExecuteQuery();
            //    }
            //}
            catch (Exception exception)
            {
                logger.LogAndSendMessage(null, "CheckOutProject",
                                         projectUid, winServiceIterationUid,
                                         $"CheckOutProject ProjectUid: {projectUid}",
                                         false, exception);
                if (draftProject != null)
                {
                    logger.LogAndSendMessage(null, "ForceCheckInProject",
                                             projectUid, winServiceIterationUid,
                                             $"ForceCheckInProject {draftProject.Id}",
                                             false, null);
                    QueueJob job = draftProject.CheckIn(true);
                    JobState jobState;
                    WaitForQueue(job, projectUid, draftProject, out jobState);
                }
            }
            return(null);
        }
示例#21
0
        public void TestConstructor_UnknownProjectStatusLookupId()
        {
            var updatedProject = new PublishedProject(
                new User(1),
                projectId: 1,
                name: "name",
                description: "description",
                projectStatusId: 0,
                sevisOrgId: "abcde1234567890",
                themeIds: null,
                goalIds: null,
                pointsOfContactIds: null,
                locationIds: null,
                categoryIds: null,
                objectiveIds: null,
                regionIds: null,
                startDate: DateTimeOffset.UtcNow.AddDays(1.0),
                endDate: DateTimeOffset.UtcNow,
                visitorTypeId: 1,
                usParticipantsEst: null,
                nonUsParticipantsEst: null,
                usParticipantsActual: null,
                nonUsParticipantsActual: null);
            var project = new Project
            {
                ProjectStatusId = ProjectStatus.Other.Id
            };
            var goalsExist           = true;
            var themesExist          = true;
            var pointsOfContactExist = false;
            var categoriesExist      = true;
            var objectivesExist      = true;
            var locationsExist       = true;
            var numberOfCategories   = 10;
            var numberOfObjectives   = 20;

            var instance = new ProjectServiceUpdateValidationEntity(
                updatedProject,
                project,
                new List <int>(),
                goalsExist,
                themesExist,
                pointsOfContactExist,
                categoriesExist,
                objectivesExist,
                locationsExist,
                numberOfObjectives,
                numberOfCategories,
                new List <int>(),
                new List <int>(),
                new List <int>(),
                new OfficeSettings(),
                new List <int>(),
                new List <int>());
        }
        private void LoadProjectInfo()
        {
            DGV_Project.InvokeIfRequired(dg =>
            {
                dg.Columns.Clear();
                dg.DataSource         = null;
                dg.AllowUserToAddRows = false;
            });

            CB_ProjectList.InvokeIfRequired(cb => _publishedProject = cb.SelectedValue as PublishedProject);
            if (_publishedProject == null)
            {
                return;
            }

            if (Settings.Default.LoadAllProperties)
            {
                LoadQueryFields(_publishedProject.Draft);
            }
            else
            {
                ProjContext.Load(_publishedProject.Draft, p => p, p => p.Tasks, p => p.Assignments, p => p.ProjectResources);
            }
            ProjContext.ExecuteQuery();
            List <PropertyInfo> retrievedFields = DisplayFields(_publishedProject.Draft);
            DataTable           dt = CreateDataTableForDisplay(retrievedFields);

            dt.ExtendedProperties.Add(dt.Rows.Count, _publishedProject.Draft);
            DataRow dr = dt.NewRow();

            retrievedFields.ForEach(prop => SetPropertyValueInDataColumn(dr, prop, _publishedProject.Draft));
            dt.Rows.Add(dr);

            DGV_Project.InvokeIfRequired(dg =>
            {
                dg.DataSource = dt;
                dg.Refresh();
                TP_Tasks.Text       = $"Tasks({_publishedProject.Draft.Tasks.Count()})";
                TP_Assignments.Text = $"Assignments({_publishedProject.Draft.Assignments.Count()})";
                TP_Resources.Text   = $"Resources({_publishedProject.Draft.ProjectResources.Count()})";
                if (_publishedProject.Draft.Tasks.Any())
                {
                    LoadTasksInfo(_publishedProject.Draft.Tasks);
                }
                if (_publishedProject.Draft.Assignments.Any())
                {
                    LoadAssignments(_publishedProject.Draft.Assignments);
                }
                if (_publishedProject.Draft.ProjectResources.Any())
                {
                    LoadProjectResources(_publishedProject.Draft.ProjectResources);
                }
            });
        }
示例#23
0
        public async Task <bool> RemoveAsync(PublishedProject publishedProject, PublishedAssignment publishedAssignment)
        {
            if (publishedProject == null)
            {
                throw new ArgumentNullException(nameof(publishedProject));
            }
            if (publishedAssignment == null)
            {
                throw new ArgumentNullException(nameof(publishedAssignment));
            }

            bool result = false;

            try
            {
                _projectContext.Load(publishedProject.Assignments);
                await _projectContext.ExecuteQueryAsync();

                if (publishedProject.Assignments.Any(ass => ass.Id == publishedAssignment.Id))
                {
                    // Ensure I have it check it out
                    await _projectClient.CheckInAsync(publishedProject);

                    var draftProject = await _projectClient.CheckOutAsync(publishedProject);

                    _projectContext.Load(draftProject.Assignments);
                    var draftAssignments = _projectContext
                                           .LoadQuery(draftProject.Assignments.Where(ass => ass.Id == publishedAssignment.Id));
                    await _projectContext.ExecuteQueryAsync();

                    var draftAssignment = draftAssignments.First();
                    var clientResult    = draftProject.Assignments.Remove(draftAssignment);

                    await _projectClient.PublishAndUpdate(draftProject, publishedProject.Name);

                    await _projectClient.CheckInAsync(publishedProject);

                    result = clientResult.Value;
                }
            }
            catch (Exception ex)
            {
                // TODO: LOG ERROR!

                throw new CsomClientException($"Unexcepted error removing an assignment. " +
                                              $"Assignment id is {publishedAssignment.Id}. " +
                                              $"Published project name is {publishedProject.Name}. " +
                                              $"Project context url is {_projectContext.Url}.", ex);
            }

            return(result);
        }
示例#24
0
        public async Task <bool> RemoveAsync(PublishedProject publishedProject, PublishedTask publishedTask)
        {
            if (publishedProject == null)
            {
                throw new ArgumentNullException(nameof(publishedProject));
            }
            if (publishedTask == null)
            {
                throw new ArgumentNullException(nameof(publishedTask));
            }

            bool result = false;

            try
            {
                // Ensure the task with the same id exist
                var task = _projectContext.LoadQuery(publishedProject.Tasks.
                                                     Where(pr => pr.Id == publishedTask.Id));
                await _projectContext.ExecuteQueryAsync();

                if (task.Any())
                {
                    // Ensure I have it check it out
                    await _projectClient.CheckInAsync(publishedProject);

                    var draftProject = await _projectClient.CheckOutAsync(publishedProject);

                    _projectContext.Load(draftProject.Tasks);
                    var draftTask = _projectContext.LoadQuery(draftProject.Tasks.Where(pr => pr.Id == publishedTask.Id));
                    await _projectContext.ExecuteQueryAsync();

                    var clientResult = draftProject.Tasks.Remove(draftTask.First());

                    await _projectClient.PublishAndUpdate(draftProject, publishedProject.Name);

                    await _projectClient.CheckInAsync(publishedProject);

                    result = clientResult.Value;
                }
            }
            catch (Exception ex)
            {
                // TODO: LOG ERROR!

                throw new CsomClientException($"Unexcepted error removing a task. " +
                                              $"project id is {publishedProject.Id}. " +
                                              $"Project context url is {_projectContext.Url}.", ex);
            }

            return(result);
        }
示例#25
0
    private static void CreateNewProject()
    {
        ProjectCreationInformation newProj = new ProjectCreationInformation();

        newProj.Id                      = Guid.NewGuid();
        newProj.Name                    = "Test Project";
        newProj.Description             = "This Project is created via CSOM";
        newProj.Start                   = DateTime.Today.Date;
        newProj.EnterpriseProjectTypeId = new Guid("09fa52b4-059b-4527-926e-99f9be96437a");
        PublishedProject newPublishedProj = projectContext.Projects.Add(newProj);

        projectContext.Projects.Update();
        projectContext.ExecuteQuery();
    }
示例#26
0
        private DraftProject CheckOutProject(PublishedProject project)
        {
            DraftProject draftProject = null;

            ExcuteJobWithRetries(() =>
            {
                LoggerHelper.Instance.Comment("About to Checkout Project with Name: " + project.Name);
                draftProject = project.CheckOut();
                BaseProjectContext.Load(draftProject);
                BaseProjectContext.ExecuteQuery();
                LoggerHelper.Instance.Comment("Finish Checkout Project with Name: " + project.Name);
            },
                                 "Checkout Project");
            return(draftProject);
        }
示例#27
0
        private int CreateTasksInProject(IGrouping <Guid, ProjectServer_CreateTasks> data)
        {
            try
            {
                using (ProjectContext projectCont1 = new ProjectContext(PwaPath))
                {
                    string nameProject    = _db.PWA_EmpProject.First(d => d.ProjectUID == data.Key).ProjectName;
                    var    projCollection = projectCont1.LoadQuery(projectCont1.Projects.Where(p => p.Name == nameProject));
                    projectCont1.ExecuteQuery();
                    PublishedProject proj2Edit      = projCollection.First();
                    DraftProject     projCheckedOut = proj2Edit.CheckOut();

                    foreach (var taskInList in _db.ProjectServer_CreateTasks.Where(d => d.ProjectUID == data.Key).ToList())
                    {
                        Guid taskId = Guid.NewGuid();
                        Task task   = projCheckedOut.Tasks.Add(new TaskCreationInformation()
                        {
                            Id       = taskId,
                            Name     = taskInList.TaskName,
                            Notes    = "new Task",
                            IsManual = false,
                            Duration = "1d",
                            Start    = DateTime.Now
                        });
                        projCheckedOut.Update();
                        // Create a local resource and assign the task to him
                        projCheckedOut.Update();
                        Guid resourceGuid =
                            (Guid)_db.AspNetUsers.First(d => d.Email == taskInList.Resource).ResourceUID;
                        DraftAssignment assignment = projCheckedOut.Assignments.Add(new AssignmentCreationInformation()
                        {
                            ResourceId = resourceGuid,
                            TaskId     = taskId
                        });
                        projCheckedOut.Update();
                    }

                    projCheckedOut.Publish(true);
                    QueueJob qJob     = projectCont1.Projects.Update();
                    JobState jobState = projectCont1.WaitForQueue(qJob, 20);
                }
                return(1);
            }
            catch
            {
                return(0);
            }
        }
示例#28
0
 private int ReadAndUpdateProject()
 {
     try
     {
         var tasksList = _db.ProjectServer_UpdateMustStartOn.ToList();
         if (tasksList.Count > 0)
         {
             try
             {
                 foreach (var dataList in tasksList)
                 {
                     ProjectContext context        = new ProjectContext(PwaPath);
                     string         nameProject    = _db.PWA_EmpProject.First(d => d.ProjectUID == dataList.ProjectUID).ProjectName;
                     var            projCollection = context.LoadQuery(context.Projects.Where(p => p.Name == nameProject));
                     context.ExecuteQuery();
                     PublishedProject project = projCollection.First();
                     DraftProject     draft   = project.CheckOut();
                     context.Load(draft, p => p.StartDate,
                                  p => p.Description);
                     string taskName = _db.PWA_EmpTaskAll.First(d => d.TaskUID == dataList.TaskUID).TaskName;
                     context.Load(draft.Tasks, dt => dt.Where(t => t.Name == taskName));
                     context.Load(draft.Assignments, da => da.Where(a => a.Task.Name == taskName));
                     context.ExecuteQuery();
                     DraftTask task = draft.Tasks.First();
                     task.ConstraintType     = ConstraintType.MustStartOn;
                     task.ConstraintStartEnd = dataList.ActualStart;
                     draft.Update();
                     JobState jobState = context.WaitForQueue(draft.Publish(true), 20);
                 }
                 return(1);
             }
             catch
             {
                 return(0);
             }
         }
         else
         {
             return(0);
         }
     }
     catch
     {
         return(0);
     }
 }
        //http://projectservercode.com/add-enterprise-resource-to-project-team-using-csom/
        public async Task <PublishedProject> LinkToEnterpriseResources(PublishedProject publishedProject, IEnumerable <EnterpriseResource> enterpriseResources)
        {
            if (publishedProject == null)
            {
                throw new ArgumentNullException(nameof(publishedProject));
            }

            if (enterpriseResources == null)
            {
                throw new ArgumentNullException(nameof(enterpriseResources));
            }

            PublishedProject result = null;

            try
            {
                await CheckInAsync(publishedProject);

                var draftProject = await CheckOutAsync(publishedProject);

                foreach (var er in enterpriseResources)
                {
                    draftProject.ProjectResources.AddEnterpriseResource(er);
                }
                draftProject.Update();

                _projectContext.Load(draftProject);
                await _projectContext.ExecuteQueryAsync();

                await PublishAndUpdate(draftProject, publishedProject.Name);
                await CheckInAsync(publishedProject);

                result = await GetByIdAsync(publishedProject.Id);
            }
            catch (Exception ex)
            {
                // TODO: LOG ERROR!

                throw new CsomClientException($"Unexcepted error linking an enterprise resource to project. " +
                                              $"project id is {publishedProject.Id}. " +
                                              $"Project context url is {_projectContext.Url}.", ex);
            }

            return(result);
        }
示例#30
0
        public GivenATaskClientInstance()
        {
            IApplicationContext  applicationContext  = new ApplicationContext();
            IConfigurationRoot   configurationRoot   = ConfigurationRootFactory.Create(applicationContext);
            IConfigurationGetter configurationGetter = new ConfigurationGetter(configurationRoot);

            var projectContextOptions = configurationGetter.GetOptions <ProjectContextOptions>();
            var clientOptions         = configurationGetter.GetOptions <CsomClientOptions>();

            var projectContext = ProjectContextFactory.Build(projectContextOptions);

            _projectClient     = new ProjectClient(projectContext, clientOptions);
            _client            = new TaskClient(projectContext, clientOptions);
            _customFieldClient = new CustomFieldClient(projectContext, clientOptions);
            _entityTypeClient  = new EntityTypeClient(projectContext, clientOptions);

            _publishedProject = CreateTestProject().Result;
        }