示例#1
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));
            }
        }
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                //System.Threading.Thread.Sleep(10000); //makes debugging easier.
                if (ConnectorId == null)
                {
                    throw new ArgumentNullException("ConnectorId is null.");
                }

                startTime = DateTime.UtcNow; //set the start time.

                //setup event log access
                if (!EventLog.SourceExists(strEventLogTitle)) //check if WF account is non-admin
                {
                    EventLog.CreateEventSource(strEventLogTitle, "Operations Manager");
                }

                #region Setup connection to EMG and get objects.
                emg = new EnterpriseManagementGroup("localhost");

                setEnterpriseManagementObjects();

                //get the last run date time so we can get projects with a last modified date greater than the last run. Check for UTC on project...
                DateTime lastRun = emoStatus[null, "LastRunFinishTime"].Value == null ? DateTime.MinValue : (DateTime)emoStatus[null, "LastRunFinishTime"].Value;

                //check to see if retention is enabled.  If so, and this is the first run, change the lastRun date.
                var retentionEnabled = emoSettings[null, "IsRetentionEnabled"].Value == null ? false : (bool)emoSettings[null, "IsRetentionEnabled"].Value;
                if (retentionEnabled && DateTime.Equals(lastRun, DateTime.MinValue))
                {
                    lastRun = DateTime.Now.AddDays(-(Convert.ToDouble(emoSettings[null, "RetentionDays"].Value)));
                }

                //set the start time on the status object.
                emoStatus[null, "LastRunStartTime"].Value  = startTime;
                emoStatus[null, "LastRunFinishTime"].Value = null;
                emoStatus[null, "Status"].Value            = mpeSyncStatusEnums.First(mpe => mpe.Name == "Microsoft.SystemCenter.LinkingFramework.SyncStatusEnum.Running");
                emoStatus[null, "MinValue"].Value          = 0;
                emoStatus[null, "MaxValue"].Value          = 100;
                #endregion

                #region Get connector credentails
                NetworkCredential creds = NetworkCredentialsHelper.GetProjectCredentials(emoConnector[null, "RunAsAccount"].Value.ToString(), emoConnector[null, "Id"].ToString(), emg.Name);
                #endregion

                EventLog.WriteEntry(strEventLogTitle, string.Format("Starting Project CI sync from Project Server...\r\n\r\nProject Server: {0}\r\nUser Name: {1}", emoConnector[null, "ProjectServerURL"].Value.ToString(), creds.Domain + "\\" + creds.UserName));

                #region license check
                var licenseExpiration = checkLicense(); //method will throw an exception if no license exists.
                EventLog.WriteEntry(strEventLogTitle, string.Format("License Expiration: {0}", licenseExpiration));
                #endregion

                #region Connect to Project Server and read data
                ProjectConnector projectConnector = new ProjectConnector(emoConnector[null, "ProjectServerURL"].Value.ToString(), creds);
                projectConnector.Connect();

                #endregion

                #region Read data from Project Server

                if (lastRun == DateTime.MinValue)
                {
                    EventLog.WriteEntry(strEventLogTitle, "Querying Project Server for a full list of projects...");
                }
                else
                {
                    EventLog.WriteEntry(strEventLogTitle, string.Format("Querying Project Server for Projects created or modified since: {0} UTC...", lastRun));
                }

                projectConnector.LoadProjects(lastRun);

                #endregion

                #region Write data to the Service Manager DB.

                totalToProcess = projectConnector.Projects.Count();
                if (totalToProcess > 0)
                {
                    EventLog.WriteEntry(strEventLogTitle, string.Format("Processing {0} projects returned from Project Server...", totalToProcess), EventLogEntryType.Information, 0);

                    iddObjects = new IncrementalDiscoveryData();
                    List <Exception> exceptionsList = new List <Exception>();

                    foreach (PublishedProject project in projectConnector.Projects)
                    {
                        try
                        {
                            projectConnector.LoadProjectTaskData(project);
                            projectConnector.LoadProjectMetaData(project);

                            iddObjects.Add(buildProjectCI(project, mpcClasses.First(c => c.Name == "Cireson.ProjectAutomation.Project")));
                        }
                        catch (EnterpriseManagementException ex)
                        {
                            exceptionsList.Add(new ProjectImportException(string.Format("An error occured while importing the following project:\r\n\r\nProject Name: {0}\r\n{1}\r\n", project.Name, ex)));
                            hasImportFailure = true;
                        }
                        //catch SP exceptions
                        finally
                        {
                            totalProcessed++;
                            updateWorkflowStatus(false, ((totalProcessed * 100) / totalToProcess));
                        }
                    }//end of foreach.

                    #endregion

                    //commit the changes to the database
                    iddObjects.Overwrite(emg);

                    if (exceptionsList.Count > 0)
                    {
                        throw new AggregateException(string.Format("{0} projects failed to sync. ", (totalToProcess - exceptionsList.Count).ToString()), exceptionsList);
                    }
                    else
                    {
                        EventLog.WriteEntry(strEventLogTitle, string.Format("{0} projects successfully committed.  Elapsed Time: {1} seconds.", totalProcessed, getRunTime(startTime).Seconds), EventLogEntryType.Information, 0);
                    }
                }
                else
                {
                    EventLog.WriteEntry(strEventLogTitle, string.Format("No updated projects exist.  Project Connector workflow is exiting.  Elapsed Time: {0} seconds.", getRunTime(startTime).Seconds));
                }
            }
            catch (AggregateException ex)
            {
                TrackData(ex.Message);

                StringBuilder exceptionStrings = new StringBuilder();
                foreach (var innerEx in ex.InnerExceptions)
                {
                    exceptionStrings.AppendLine(string.Format(strExceptionMessage, innerEx.Message, innerEx.InnerException, innerEx.StackTrace, innerEx.Source));
                }

                EventLog.WriteEntry(strEventLogTitle, string.Format(ex.Message + "Elapsed Time: {0} seconds. The following projects failed to sync: \r\n\r\n{1}", getRunTime(startTime).Seconds, exceptionStrings.ToString()), EventLogEntryType.Error, 1);
                hasImportFailure = true;
            }
            catch (EnterpriseManagementException ex)
            {
                TrackData(ex.Message);
                EventLog.WriteEntry(strEventLogTitle, string.Format(strExceptionMessage, ex.Message, ex.InnerException, ex.StackTrace, ex.Source), EventLogEntryType.Error, 1);
                hasImportFailure = true;
                throw;
            }
            catch (Exception ex)
            {
                TrackData(ex.Message);
                EventLog.WriteEntry(strEventLogTitle, string.Format(strExceptionMessage, ex.Message, ex.InnerException, ex.StackTrace, ex.Source), EventLogEntryType.Error, 1);
                hasImportFailure = true;
                throw;
            }
            finally
            {
                updateWorkflowStatus(true, 100);

                if (emg != null)
                {
                    emg.Dispose();
                }
            }
            return(ActivityExecutionStatus.Closed);
        }