Exemplo n.º 1
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)
            {
            }
        }
Exemplo n.º 2
0
        public static EnterpriseResource LoadMe()
        {
            string currentUserName = UserPrincipal.Current.DisplayName;

            Log.WriteVerbose(new SourceInfo(), "Loading current user:[{0}] info.", currentUserName);
            User user = ProjContext.Web.CurrentUser;
            IEnumerable <EnterpriseResource> resources =
                ProjContext.LoadQuery(ProjContext.EnterpriseResources.Where(r => r.Name == user.Title).IncludeWithDefaultProperties(r => r.User));

            ProjContext.ExecuteQuery();
            return(resources.FirstOrDefault());
        }
Exemplo n.º 3
0
        // Constructor. Will connect to Project Online with mandratory credentials.
        public UserProps(string site, string username, string password)
        {
            try
            {
                if (site == "" || username == "" || password == "")
                {
                    throw (new Exception("Must supply site, username and password!"));
                }

                Console.WriteLine("Connecting to Project Online @ " + site + "...");

                var securePassword = new SecureString();
                foreach (var ch in password.ToCharArray())
                {
                    securePassword.AppendChar(ch);
                }

                context             = new ProjectContext(site);
                context.Credentials = new SharePointOnlineCredentials(username, securePassword);
                context.Load(context.Web);
                context.ExecuteQuery();
                Console.WriteLine("   Connected to '" + context.Web.Title + "'");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
Exemplo n.º 4
0
        // Constructor. Will connect to Project Online with mandratory credentials.
        public UserProps(string site, string username, string password)
        {
            try
            {
                if (site == "" || username == "" || password == "")
                {
                    throw (new Exception("Must supply site, username and password!"));
                }

                Console.WriteLine("Connecting to Project Online @ " + site + "...");

                var securePassword = new SecureString();
                foreach (var ch in password.ToCharArray())
                {
                    securePassword.AppendChar(ch);
                }

                context = new ProjectContext(site);
                context.Credentials = new SharePointOnlineCredentials(username, securePassword);
                context.Load(context.Web);
                context.ExecuteQuery();
                Console.WriteLine("   Connected to '" + context.Web.Title + "'");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
Exemplo n.º 5
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);
    }
Exemplo n.º 6
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);
     }
 }
Exemplo n.º 7
0
        static public IEnumerable <dynamic> GetActiveProjects(string pwaUrl)
        {
            var projContext = new ProjectContext(pwaUrl);

            projContext.Load(projContext.Projects, items => items.IncludeWithDefaultProperties(item => item.ProjectSiteUrl, item => item.Id));

            projContext.ExecuteQuery();

            foreach (PublishedProject pubProj in projContext.Projects)
            {
                yield return(new { Url = pubProj.ProjectSiteUrl, Guid = pubProj.Id.ToString() });
            }
        }
Exemplo n.º 8
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);
            }
        }
Exemplo n.º 9
0
 public void Connect()
 {
     projContext = new ProjectContext(url);
     if (credentials != null)
     {
         projContext.Credentials = credentials;
     }
     else
     {
         projContext.Credentials               = o365credentials;
         projContext.AuthenticationMode        = ClientAuthenticationMode.Anonymous;
         projContext.FormDigestHandlingEnabled = false;
     }
     projContext.Load(projContext.Web, w => w.RegionalSettings.TimeZone);
     projContext.ExecuteQuery();
 }
Exemplo n.º 10
0
    public Guid GetEptUid(string eptName)
    {
        Guid eptUid = Guid.Empty;

        try
        {
            var eptList = _context.LoadQuery(_context.EnterpriseProjectTypes.Where(ept => ept.Name == eptName));
            _context.ExecuteQuery();
            eptUid = eptList.First().Id;
        }
        catch (Exception ex)
        {
            string msg = string.Format("GetEptUid: eptName = \"{0}\"\n\n{1}", eptName, ex.GetBaseException().ToString());
            throw new ArgumentException(msg);
        }
        return(eptUid);
    }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            int    id     = 0;
            string nombre = null;
            string fecha  = null;

            using (ProjectContext projContext = new ProjectContext("https://aigpanama.sharepoint.com/sites/Proyectos-TI/"))
            {
                SecureString password = new SecureString();
                foreach (char c in "Coco.1961".ToCharArray())
                {
                    password.AppendChar(c);
                }
                //Using SharePoint method to load Credentials
                projContext.Credentials = new SharePointOnlineCredentials("*****@*****.**", password);


                var projects = projContext.Projects;


                projContext.Load(projects);


                int j = 1;
                projContext.ExecuteQuery();

                string mensaje  = "";
                string filePath = @"c:\temp" + @"\proyectos.txt";

                foreach (PublishedProject pubProj in projContext.Projects)
                {
                    // Console.WriteLine("\n{0}. {1}   {2} \t{3} \n", j++, pubProj.Id, pubProj.Name, pubProj.CreatedDate);

                    string[] proyecto = new string[4];
                    proyecto[0] = j++.ToString();
                    proyecto[1] = pubProj.Id.ToString();
                    proyecto[2] = pubProj.Name;
                    proyecto[3] = pubProj.CreatedDate.ToString();

                    projContext.Load(projects, c => c.Where(p => p.Id == new Guid(proyecto[1])).IncludeWithDefaultProperties(f => f.Description,
                                                                                                                             f => f.FinishDate, f => f.PercentComplete, f => f.StartDate, f => f.Id, f => f.Name,
                                                                                                                             f => f.CreatedDate, f => f.Owner.UserId, f => f.CustomFields));
                }
            }
        }
Exemplo n.º 12
0
        public bool Login(LoginInfo model)
        {
            BaseProjectContext = new ProjectContext(model.Url);
            NetworkCredential           netcred         = new NetworkCredential(model.UserName, model.Password);
            SharePointOnlineCredentials orgIDCredential = new SharePointOnlineCredentials(netcred.UserName, netcred.SecurePassword);

            BaseProjectContext.Credentials = orgIDCredential;
            try
            {
                BaseProjectContext.ExecuteQuery();
                return(true);
            }
            catch (IdcrlException e)
            {
                LoggerHelper.Instance.Error(e);
                return(false);
            }
        }
Exemplo n.º 13
0
        public void UpdateTasksInProject()
        {
            ProjectContext projContext    = new ProjectContext("http://tpserver/pwa/");
            var            projCollection = projContext.LoadQuery(projContext.Projects.Where(p => p.Name == "Test"));

            projContext.ExecuteQuery();
            foreach (PublishedProject pubProj in projCollection)
            {
                DraftProject            projCheckedOut = pubProj.CheckOut();
                TaskCreationInformation newTask        = new TaskCreationInformation();
                newTask.Name     = "Тестовая задача Андрея";
                newTask.IsManual = false;
                newTask.Duration = "3d";
                newTask.Start    = DateTime.Today;
                projCheckedOut.Tasks.Add(newTask);
                projCheckedOut.StartDate = DateTime.Now.AddYears(1);
                projCheckedOut.Publish(true);
                QueueJob qJob     = projContext.Projects.Update();
                JobState jobState = projContext.WaitForQueue(qJob, 10);
            }
        }
Exemplo n.º 14
0
        public bool LoginNew(LoginInfo model)
        {
            BaseProjectContext = new ProjectContext(model.Url);
            SecureString psw = new SecureString();

            model.Password.ToList().ForEach(item => psw.AppendChar(item));
            BaseProjectContext.Credentials = new SharePointOnlineCredentials(model.UserName, psw);
            User user = BaseProjectContext.Web.CurrentUser;

            try
            {
                BaseProjectContext.Load(user);
                BaseProjectContext.ExecuteQuery();
                return(true);
            }
            catch (IdcrlException e)
            {
                LoggerHelper.Instance.Error(e);
                return(false);
            }
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            string tenantUrl = "https://tenant.sharepoint.com";
            string siteUrl   = "/sites/pwa";
            var    creds     = CredentialManager.GetSharePointOnlineCredential(tenantUrl);

            using (ProjectContext ctx = new ProjectContext(tenantUrl + siteUrl))
            {
                ctx.Credentials = creds;

                var projects = ctx.Projects;
                ctx.Load(projects);
                ctx.ExecuteQuery();

                foreach (var project in projects)
                {
                    Console.WriteLine($"Project Name: {project.Name}");
                }

                Console.ReadLine();
            }
        }
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                Assignment assignment;

                // Loop through each assignment and update % complete
                for (int j = 0; j < chkAssignments.Items.Count; j++)
                {
                    assignment = (Assignment)chkAssignments.Items[j];

                    if (assignment.Dirty)
                    {
                        if (assignment.Done)
                        {
                            self.Assignments.GetByGuid(assignment.ID).PercentComplete = 100;
                        }
                        else
                        {
                            self.Assignments.GetByGuid(assignment.ID).PercentComplete = 0;
                        }
                    }
                }


                // Update the assignments and submit the status updates.
                self.Assignments.Update();

                self.Assignments.SubmitAllStatusUpdates("");
                projContext.ExecuteQuery();



                Cursor = Cursors.Arrow;


                // Loop through each assignment and update % complete
                for (int j = 0; j < chkAssignments.Items.Count; j++)
                {
                    assignment       = (Assignment)chkAssignments.Items[j];
                    assignment.Dirty = false;
                }


                MessageBox.Show(this, "Your updates have been submitted.", "Changes submitted", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (ClientRequestException cre)
            {
                Cursor = Cursors.Arrow;
                string msg = string.Format("Error: \n\n{1}", cre.GetBaseException().ToString());
                throw new ArgumentException(msg);
            }

            catch (Exception ex)
            {
                Cursor = Cursors.Arrow;
                string msg = string.Format("Error: \n\n{1}", ex.ToString());
                throw new ArgumentException(msg);
            }
        }
Exemplo n.º 17
0
        private static void ListPublishedProjects()
        {
            projectContext.Load(projectContext.Projects); //Load Project from PWA
            projectContext.ExecuteQuery();
            Console.WriteLine("nList of all Published Projects: n");

            foreach (PublishedProject pubProj in projectContext.Projects)
            {
                Console.WriteLine("nt{ 0}", pubProj.Name);
            }

            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            // Lists out the LCFs for a specific project in the PWA instance, consisting of the
            // field type, field name, whether a lookup table is used, and the value and description of each each LCF entry.

            // This app does the following:
            // 1. Retrieves a specific project, task(s), and custom fields associated with the tasks in the project
            // 2. Place the custom field key/value pairs in a dictionary
            // 3. Do the following for each Local Custom Field:
            //    A. Distinguish between simple values and values that use a lookup table for
            //       the friendly values.
            //    B. Filter out partial entries.
            //    C. List the friendly value for the user (simple values)
            //    D. List the friendly value for the user (lookup tables)

            using (projContext)
            {
                // Get login cookie using WebLogin
                var cookies = WebLogin.GetWebLoginCookie(new Uri(SiteUrl));

                projContext.ExecutingWebRequest += delegate(object sender, WebRequestEventArgs e)
                {
                    e.WebRequestExecutor.WebRequest.CookieContainer = new CookieContainer();
                    e.WebRequestExecutor.WebRequest.CookieContainer.SetCookies(new Uri(SiteUrl), cookies);
                };

                // 1. Retrieve the project, tasks, etc.
                var projColl = projContext.LoadQuery(projContext.Projects
                                                     .Where(p => p.Name == SampleProjectName)
                                                     .Include(
                                                         p => p.Id,
                                                         p => p.Name,
                                                         p => p.Tasks,
                                                         p => p.Tasks.Include(
                                                             t => t.Id,
                                                             t => t.Name,
                                                             t => t.CustomFields,
                                                             t => t.CustomFields.IncludeWithDefaultProperties(
                                                                 cf => cf.LookupTable,
                                                                 cf => cf.LookupEntries
                                                                 )
                                                             )
                                                         )
                                                     );

                projContext.ExecuteQuery();

                PublishedProject theProj = projColl.First();


                Console.WriteLine("Name:\t{0}", theProj.Name);
                Console.WriteLine("Id:\t{0}", theProj.Id);
                Console.WriteLine("Tasks count: {0}", theProj.Tasks.Count);
                Console.WriteLine("  -----------------------------------------------------------------------------");


                PublishedTaskCollection taskColl = theProj.Tasks;

                PublishedTask theTask = taskColl.First();

                CustomFieldCollection LCFColl = theTask.CustomFields;

                // 2. Place the task-specific custom field key/value pairs in a dictionary
                Dictionary <string, object> taskCF_Dict = theTask.FieldValues;

                if (LCFColl.Count > 0)
                {
                    Console.WriteLine("\n\tType\t   Name\t\t  L.UP   Value                  Description");
                    Console.WriteLine("\t--------   ------------   ----   --------------------   -----------");

                    // 3. For each custom field, do the follwoing:
                    foreach (CustomField cf in LCFColl)
                    {
                        // 3A. Distinguish LCF values that are simple from those that use lookup tables.
                        if (!cf.LookupTable.ServerObjectIsNull.HasValue ||
                            (cf.LookupTable.ServerObjectIsNull.HasValue && cf.LookupTable.ServerObjectIsNull.Value))
                        {
                            if (taskCF_Dict[cf.InternalName] == null)
                            {   // 3B. Partial implementation. Not usable.
                                String textValue = "is not set";
                                Console.WriteLine("\t{0} {1}  {2}", cf.FieldType, cf.Name, textValue);
                            }
                            else     // 3C. Friendly value for the user (simple).
                            {
                                String textValue = taskCF_Dict[cf.InternalName].ToString();
                                Console.WriteLine("\t{0, -8}   {1, -15}       {2}", cf.FieldType, cf.Name, textValue);
                            }
                        }
                        else         //3D. Friendly value for the user that uses a Lookup table.
                        {
                            Console.Write("\t{0, -8}   {1, -15}", cf.FieldType, cf.Name);

                            String[] entries = (String[])taskCF_Dict[cf.InternalName];

                            foreach (String entry in entries)
                            {
                                var luEntry = projContext.LoadQuery(cf.LookupTable.Entries
                                                                    .Where(e => e.InternalName == entry));

                                projContext.ExecuteQuery();

                                Console.WriteLine("Yes    {0, -22}  {1}", luEntry.First().FullValue, luEntry.First().Description);
                            }
                        }
                    }   // End foreach CustomField
                }
            }

            Console.Write("\nPress any key to exit: ");
            Console.ReadKey(false);
        }   // End of Main
Exemplo n.º 19
0
        // Public facing function to set the custom enterprise resource fields
        public void SetCustomField(string userEmail, string newValue = "")
        {
            var user = GetUserResource(userEmail);

            if (user != null)
            {
                // Get all custom fields
                LoadCustomFields();

                // Set the custom enterprise resource field
                try
                {
                    Console.WriteLine("Setting custom enterprise resource property for user...");
                    newValue = newValue.ToLower();
                    var fieldInternalName = AllCustomFields[CustomFieldGuid].InternalName;
                    var entryInternalName = AllCustomFields[CustomFieldGuid].LookupEntries[newValue].InternalName; // not that we are doing a string match here to figure out the internal name of the value in the lookup table
                    user[fieldInternalName] = new string[] { entryInternalName };                                  // note that it should be a string array
                    Console.WriteLine("\t" + AllCustomFields[CustomFieldGuid].Name + " >> " + AllCustomFields[CustomFieldGuid].LookupEntries[newValue].Value);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Could not set custom field " + CustomFieldGuid + " to " + newValue + ": " + ex.Message);
                }


                // Persist changes (note than the resource object is in the EnterpriseResources collection)
                try
                {
                    Console.WriteLine("\tSaving changes...");
                    context.EnterpriseResources.Update();
                    context.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error saving: " + ex.Message);
                }
            }
        }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            // Environment variables
            var siteUrl    = ConfigurationManager.AppSettings["pwa:SiteUrl"];
            var login      = ConfigurationManager.AppSettings["pwa:Login"];
            var password   = ConfigurationManager.AppSettings["pwa:Password"];
            var fieldId    = new Guid(ConfigurationManager.AppSettings["pwa:FieldId"]);
            var resourceId = new Guid(ConfigurationManager.AppSettings["pwa:ResourceId"]);

            // Store password in secure string
            var securePassword = new SecureString();

            foreach (var c in password)
            {
                securePassword.AppendChar(c);
            }

            // Project instance credentials
            var creds = new SharePointOnlineCredentials(login, securePassword);

            // Initiation of the client context
            using (var ctx = new ProjectContext(siteUrl))
            {
                ctx.Credentials = creds;

                // Retrieve Enterprise Custom Field
                var field = ctx.CustomFields.GetByGuid(fieldId);

                // Load InernalName property, we will use it to get the value
                ctx.Load(field,
                         x => x.InternalName);

                // Execture prepared query on server side
                ctx.ExecuteQuery();

                var fieldInternalName = field.InternalName;

                // Retrieve recource by its Id
                var resource = ctx.EnterpriseResources.GetByGuid(resourceId);

                // !
                // Load custom field value
                ctx.Load(resource,
                         x => x[fieldInternalName]);
                ctx.ExecuteQuery();


                // Update ECF value
                resource[fieldInternalName] = "Vitaly Zhukov";
                ctx.EnterpriseResources.Update();
                ctx.ExecuteQuery();

                // Get ECF value from server
                ctx.Load(resource,
                         x => x[fieldInternalName]);
                ctx.ExecuteQuery();

                Console.WriteLine("ECF value: " + resource[fieldInternalName]);

                Console.ReadLine();
            }
        }
Exemplo n.º 21
0
 public void LoadAllProjects()
 {
     projContext.Load(projContext.Projects);
     projContext.ExecuteQuery();
     Projects = projContext.Projects;
 }
Exemplo n.º 22
0
        static void SyncEngagments()
        {
            ProjectEngagement pEng     = null;
            string            res_uid  = "";
            string            proj_uid = "";
            string            err      = "";
            string            sql      = "exec [MCG_RM_GetPendingUpdates_engagements]";

            DataSet        ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(sql, cn);

            da.Fill(ds);

            foreach (DataRow r in ds.Tables[0].Rows)
            {
                res_uid  = r["resourceuid"].ToString();
                proj_uid = r["projectuid"].ToString();

                pubProj = projContext.Projects.GetByGuid(new Guid(proj_uid));
                projContext.Load(pubProj);
                projContext.ExecuteQuery();

                draftProj = pubProj.CheckOut();

                projContext.Load(draftProj.Engagements);
                projContext.ExecuteQuery();

                if (!r.IsNull("engagementuid"))
                {
                    pEng = draftProj.Engagements.GetByGuid(new Guid(r["engagementuid"].ToString()));
                }

                if (pEng == null)
                {
                    res = projContext.EnterpriseResources.GetByGuid(new Guid(res_uid));
                    projContext.Load(res);
                    projContext.ExecuteQuery();

                    ProjectEngagementCreationInformation peci = new ProjectEngagementCreationInformation();
                    peci.Id          = Guid.NewGuid();
                    peci.Start       = Convert.ToDateTime(r["start_dt"].ToString());
                    peci.Finish      = Convert.ToDateTime(r["end_dt"].ToString());
                    peci.Resource    = res;
                    peci.Work        = "0h";
                    peci.Description = "RPM_" + r["planuid"].ToString();

                    draftProj.Engagements.Add(peci).Status = EngagementStatus.Proposed;
                    draftProj.Engagements.Update();
                    pEng = draftProj.Engagements.Last();
                    projContext.Load(pEng);
                    projContext.ExecuteQuery();
                }


                DataRow[] rows = ds.Tables[1].Select("resourceuid='" + res_uid + "' and projectuid='" + proj_uid + "'");
                ProjectEngagementTimephasedCollection petpc = pEng.GetTimephased(Convert.ToDateTime(r["start_dt"]), Convert.ToDateTime(r["end_dt"]), TimeScale.Days, EngagementContourType.Draft);

                projContext.Load(petpc);
                projContext.ExecuteQuery();

                foreach (DataRow row in rows)
                {
                    petpc.GetByStart(Convert.ToDateTime(row["timebyday"].ToString())).Work = row["allocationwork"].ToString();
                }
                pEng.Status = EngagementStatus.Reproposed; //this is needed
                draftProj.Engagements.Update();

                draftProj.CheckIn(false);
                //this updates the last TBD engagement in PWA, Approved will remove Eng from PWA
                QueueJob qJob1    = projContext.Projects.Update();
                JobState jobState = projContext.WaitForQueue(qJob1, timeoutSeconds);

                {
                    //approve proposed request
                    if (res == null)
                    {
                        res = projContext.EnterpriseResources.GetByGuid(new Guid(res_uid));
                        projContext.Load(res);
                        projContext.Load(res.Engagements);
                        projContext.ExecuteQuery();
                    }

                    ResourceEngagement eng = res.Engagements.GetById(pEng.Id.ToString());
                    projContext.Load(eng);
                    projContext.ExecuteQuery();  //Too many resources: 4205. You cannot load dependent objects for more than 1000 resources. Use a filter to restrict your query

                    eng.Status = EngagementStatus.Approved;
                    res.Engagements.Update();

                    QueueJob qJob = projContext.Projects.Update();
                    jobState = projContext.WaitForQueue(qJob, timeoutSeconds);
                }
            }
        }
 public void ExecuteQuery()
 {
     ProjectContext.ExecuteQuery();
 }
Exemplo n.º 24
0
        public void UpdateManpower()
        {
            projContext = new ProjectContext(pwaPath);
            projContext.Load(projContext.EnterpriseResources);
            projContext.Load(projContext.CustomFields);
            projContext.ExecuteQuery();
            if (projContext.EnterpriseResources.Count > 0)
            {
                foreach (var data in projContext.EnterpriseResources)
                {
                    Console.WriteLine(data.Name);
                    var resId = data.Id;
                    EnterpriseResource res = projContext.EnterpriseResources.GetByGuid(resId);
                    projContext.Load(res);
                    projContext.Load(res.CustomFields);
                    projContext.ExecuteQuery();

                    foreach (var dataExcel in dataInExcel)
                    {
                        if (dataExcel.UserName == res.Name)
                        {
                            if (dataExcel.Month == 1)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "Jan");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            else if (dataExcel.Month == 2)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "Feb");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            else if (dataExcel.Month == 3)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "Mar");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            else if (dataExcel.Month == 4)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "Apr");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            else if (dataExcel.Month == 5)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "May");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            else if (dataExcel.Month == 6)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "Yun");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            else if (dataExcel.Month == 7)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "Yul");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            else if (dataExcel.Month == 8)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "Aug");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            else if (dataExcel.Month == 9)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "Sen");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            else if (dataExcel.Month == 10)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "Okt");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            else if (dataExcel.Month == 11)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "Now");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            else if (dataExcel.Month == 12)
                            {
                                CustomField cField = projContext.CustomFields.First(c => c.Name == "Dec");
                                res[cField.InternalName] = dataExcel.Data * 100;
                                projContext.EnterpriseResources.Update();
                            }
                            projContext.ExecuteQuery();
                        }
                    }
                }
            }
        }
Exemplo n.º 25
0
 private int UpdateTasksInProject(IGrouping <Guid, ProjectServer_UpdateTasks> 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();
             projectCont1.Load(projCheckedOut.Tasks);
             projectCont1.ExecuteQuery();
             DraftTaskCollection catskill = projCheckedOut.Tasks;
             foreach (DraftTask task in catskill)
             {
                 try
                 {
                     if (task.Name != null && task.Id == _db.ProjectServer_UpdateTasks.First(d => d.taskUID == task.Id).taskUID)
                     {
                         ProjectServer_UpdateTasks projectServer_UpdateTasks = _db.ProjectServer_UpdateTasks.First(d => d.taskUID == task.Id);
                         var nk = projectServer_UpdateTasks.nk;
                         if (nk != null)
                         {
                             int time = (int)nk;
                             projectCont1.Load(task.CustomFields);
                             projectCont1.ExecuteQuery();
                             foreach (CustomField cus in task.CustomFields)
                             {
                                 if (cus.Name == "НК")
                                 {
                                     string intname = cus.InternalName;
                                     task[intname] = time;
                                 }
                             }
                             if (task.PercentComplete == 0)
                             {
                                 task.Work = time + "ч";
                             }
                             else
                             {
                                 int factWork = Convert.ToInt32(task.Work.Substring(0, task.Work.Length - 1)) - Convert.ToInt32(task.RemainingWork.Substring(0, task.RemainingWork.Length - 1));
                                 if (factWork < time)
                                 {
                                     task.Work = time - factWork + "ч";
                                 }
                             }
                             QueueJob qJob1     = projCheckedOut.Update();
                             JobState jobState1 = projectCont1.WaitForQueue(qJob1, 10);
                         }
                         else
                         {
                             ProjectServer_UpdateTasks pTask = _db.ProjectServer_UpdateTasks.First(d => d.taskUID == task.Id);
                             if (pTask.percentComplited != null)
                             {
                                 task.PercentComplete = (int)pTask.percentComplited;
                             }
                             if (pTask.finishDate != null)
                             {
                                 task.Finish = (DateTime)pTask.finishDate;
                             }
                             if (task.IsMilestone == true)
                             {
                                 task.Start = (DateTime)pTask.finishDate;
                             }
                             QueueJob qJob1     = projCheckedOut.Update();
                             JobState jobState1 = projectCont1.WaitForQueue(qJob1, 10);
                         }
                     }
                 }
                 catch
                 {
                 }
             }
             projCheckedOut.Publish(true);
             QueueJob qJob     = projectCont1.Projects.Update();
             JobState jobState = projectCont1.WaitForQueue(qJob, 20);
         }
         return(1);
     }
     catch
     {
         return(0);
     }
 }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            using (projContext)
            {
                // Get login cookie using WebLogin
                var cookies = WebLogin.GetWebLoginCookie(new Uri(SiteUrl));

                projContext.ExecutingWebRequest += delegate(object sender, WebRequestEventArgs e)
                {
                    e.WebRequestExecutor.WebRequest.CookieContainer = new CookieContainer();
                    e.WebRequestExecutor.WebRequest.CookieContainer.SetCookies(new Uri(SiteUrl), cookies);
                };

                // 1. List the defined Enterprise Custom Fields in the PWA instance.
                ListPWACustomFields();

                // 2. Get project list with minimal information
                projContext.Load(projContext.Projects, qp => qp.Include(qr => qr.Id));
                projContext.ExecuteQuery();

                var allIds = projContext.Projects.Select(p => p.Id).ToArray();

                int numBlocks = allIds.Length / PROJECT_BLOCK_SIZE + 1;

                // Query all the child objects in blocks of PROJECT_BLOCK_SIZE
                for (int i = 0; i < numBlocks; i++)
                {
                    var    idBlock = allIds.Skip(i * PROJECT_BLOCK_SIZE).Take(PROJECT_BLOCK_SIZE);
                    Guid[] block   = new Guid[PROJECT_BLOCK_SIZE];
                    Array.Copy(idBlock.ToArray(), block, idBlock.Count());

                    // 2. Retrieve and save project basic and custom field properties in an IEnumerable collection.
                    var projBlk = projContext.LoadQuery(
                        projContext.Projects
                        .Where(p =>   // some elements will be Zero'd guids at the end
                               p.Id == block[0] || p.Id == block[1] ||
                               p.Id == block[2] || p.Id == block[3] ||
                               p.Id == block[4] || p.Id == block[5] ||
                               p.Id == block[6] || p.Id == block[7] ||
                               p.Id == block[8] || p.Id == block[9] ||
                               p.Id == block[10] || p.Id == block[11] ||
                               p.Id == block[12] || p.Id == block[13] ||
                               p.Id == block[14] || p.Id == block[15] ||
                               p.Id == block[16] || p.Id == block[17] ||
                               p.Id == block[18] || p.Id == block[19]
                               )
                        .Include(p => p.Id,
                                 p => p.Name,
                                 p => p.IncludeCustomFields,
                                 p => p.IncludeCustomFields.CustomFields,
                                 P => P.IncludeCustomFields.CustomFields.IncludeWithDefaultProperties(
                                     lu => lu.LookupTable,
                                     lu => lu.LookupEntries
                                     )
                                 )
                        );

                    projContext.ExecuteQuery();

                    foreach (PublishedProject pubProj in projBlk)
                    {
                        // Set up access to custom field collection of published project
                        var projECFs = pubProj.IncludeCustomFields.CustomFields;

                        // Set up access to custom field values of published project
                        Dictionary <string, object> ECFValues = pubProj.IncludeCustomFields.FieldValues;

                        Console.WriteLine("Name:\t{0}", pubProj.Name);
                        Console.WriteLine("Id:\t{0}", pubProj.Id);
                        Console.WriteLine("ECF count: {0}\n", ECFValues.Count);

                        Console.WriteLine("\n\tType\t   Name\t\t       L.UP   Value                  Description");
                        Console.WriteLine("\t--------   ----------------    ----   --------------------   -----------");

                        foreach (CustomField cf in projECFs)
                        {
                            // 3A. Distinguish CF values that are simple from those that use entries in lookup tables.
                            if (!cf.LookupTable.ServerObjectIsNull.HasValue ||
                                (cf.LookupTable.ServerObjectIsNull.HasValue && cf.LookupTable.ServerObjectIsNull.Value))
                            {
                                if (ECFValues[cf.InternalName] == null)
                                {   // 3B. Partial implementation. Not usable.
                                    String textValue = "is not set";
                                    Console.WriteLine("\t{0, -8}   {1, -20}        ***{2}",
                                                      cf.FieldType, cf.Name, textValue);
                                }
                                else   // 3C. Simple, friendly value for the user
                                {
                                    // CustomFieldType is a CSOM enumeration of ECF types.
                                    switch (cf.FieldType)
                                    {
                                    case CustomFieldType.COST:
                                        decimal costValue = (decimal)ECFValues[cf.InternalName];
                                        Console.WriteLine("\t{0, -8}   {1, -20}        {2, -22}",
                                                          cf.FieldType, cf.Name, costValue.ToString("C"));
                                        break;

                                    case CustomFieldType.DATE:
                                    case CustomFieldType.FINISHDATE:
                                    case CustomFieldType.DURATION:
                                    case CustomFieldType.FLAG:
                                    case CustomFieldType.NUMBER:
                                    case CustomFieldType.TEXT:
                                        Console.WriteLine("\t{0, -8}   {1, -20}        {2, -22}",
                                                          cf.FieldType, cf.Name, ECFValues[cf.InternalName]);
                                        break;
                                    }
                                }
                            }
                            else         //3D. The ECF uses a Lookup table to store the values.
                            {
                                Console.Write("\t{0, -8}   {1, -20}", cf.FieldType, cf.Name);

                                String[] entries = (String[])ECFValues[cf.InternalName];

                                if (entries != null)
                                {
                                    foreach (String entry in entries)
                                    {
                                        var luEntry = projContext.LoadQuery(cf.LookupTable.Entries
                                                                            .Where(e => e.InternalName == entry));

                                        projContext.ExecuteQuery();

                                        Console.WriteLine(" Yes    {0, -22}  {1}", luEntry.First().FullValue, luEntry.First().Description);
                                    }
                                }
                            }
                        }

                        Console.WriteLine("     ------------------------------------------------------------------------\n");
                    }
                }
            }    //end of using


            Console.Write("\nPress any key to exit: ");
            Console.ReadKey(false);
        } //end of Main
Exemplo n.º 27
0
 public void LoadPublishedProject()
 {
     projContext.Load(projContext.Projects);
     projContext.ExecuteQuery();
 }
Exemplo n.º 28
0
        // For applications that access both the Project Server CSOM and the SharePoint CSOM, you could
        // use the ProjectServer object. Those statements are commented out in this application.
        // However, it is not necessary to instantiate a ProjectServer object, because the the
        // ProjectContext object inherits from ClientContext in SharePoint.
        static void Main(string[] args)
        {
            projContext = new ProjectContext(pwaPath);
                //context = new ClientContext(pwaPath);
                //projSvr = new ProjectServer(context);
               // string userName = "******";
            //GUID for reshmee auckloo
            Guid resUID = new Guid("02C5EE34-5CE8-E411-80C1-00155D640C06");
            string customFieldName = "Staff Number";

            // Get the list of resources from Project Web App.
            projContext.Load(projContext.EnterpriseResources);
            projContext.Load(projContext.CustomFields);

            projContext.ExecuteQuery();

            Console.WriteLine("\nResource ID : Resource name ");

            int numResInCollection = projContext.EnterpriseResources.Count();
              var usrs = projContext.Web.SiteUsers;

            if (numResInCollection > 0)
            {
                projContext.Load(projContext.EnterpriseResources.GetByGuid(resUID));
                projContext.Load(projContext.EntityTypes.ResourceEntity);
                projContext.ExecuteQuery();

                var entRes2Edit = projContext.EnterpriseResources.GetByGuid(resUID);

                var userCustomFields = entRes2Edit.CustomFields;

                Guid ResourceEntityUID = projContext.EntityTypes.ResourceEntity.ID;

               var customfield = projContext.CustomFields.Where(x => x.Name == customFieldName);

               entRes2Edit[customfield.First().InternalName] = "3456";

                Console.WriteLine("\nEditing resource : GUID : Can Level");
                Console.WriteLine("\n{0} : {1} : {2}", entRes2Edit.Name, entRes2Edit.Id.ToString(),
                    entRes2Edit.CanLevel.ToString());

                // Toggle the CanLevel property.
                entRes2Edit.CanLevel = !entRes2Edit.CanLevel;

                // The entRes2Edit object is in the EnterpriseResources collection.
                projContext.EnterpriseResources.Update();

                // Save the change.
                projContext.ExecuteQuery();

                // Check that the change was made.
                projContext.Load(projContext.EnterpriseResources.GetByGuid(resUID));
                projContext.ExecuteQuery();

                entRes2Edit = projContext.EnterpriseResources.GetByGuid(resUID);

                Console.WriteLine("\n\nChanged resource : GUID : Can Level");
                Console.WriteLine("\n{0} : {1} : {2}", entRes2Edit.Name, entRes2Edit.Id.ToString(),
                    entRes2Edit.CanLevel.ToString());
            }

            Console.Write("\nPress any key to exit: ");
            Console.ReadKey(false);
        }