//////////////////////////////////////////////////////////////////////// // METHOD: Execute public int Execute(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback) { // Verify whether an AOI has been defined for the current job try { // Get the current job IJTXJobManager pJobManager = m_ipDatabase.JobManager; IJTXJob2 pJob = pJobManager.GetJob(jobID) as IJTXJob2; // Check if AOI exists if (pJob.AOIExtent != null) { // AOI exists return(1); } else { // AOI does not exist return(2); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); // Close the requested job try { IJTXJobManager jobManager = this.WmxDatabase.JobManager; IJTXJob3 job = jobManager.GetJob(m_jobToClose) as IJTXJob3; IJTXConfiguration3 configMgr = this.WmxDatabase.ConfigurationManager as IJTXConfiguration3; if (job.Stage != jtxJobStage.jtxJobStageClosed && !job.CanClose()) { throw new WmauException(WmauErrorCodes.C_CANNOT_CLOSE_JOB_ERROR); } msgs.AddMessage("Closing job " + m_jobToClose + " (" + job.Name + ")"); job.Close(); // Once the job is closed, do the other things that still need to be handled // separately (status updates, notifications, ...) Common.WmauHelperFunctions.UpdateJobStatus(this.WmxDatabase, job); job.Store(); job.LogJobAction( configMgr.GetActivityType(ESRI.ArcGIS.JTX.Utilities.Constants.ACTTYPE_CLOSE_JOB), null, string.Empty); Common.WmauHelperFunctions.SendNotification( ESRI.ArcGIS.JTX.Utilities.Constants.NOTIF_JOB_CLOSED, this.WmxDatabase, job); // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_JOB_CLOSED); IGPLong outValue = new GPLongClass(); outValue.Value = m_jobToClose; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } }
//////////////////////////////////////////////////////////////////////// // METHOD: Execute public int Execute(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback) { // Verify whether the current job has a version or not // Get the current job IJTXJobManager pJobManager = m_ipDatabase.JobManager; IJTXJob2 pJob = pJobManager.GetJob(jobID) as IJTXJob2; // Check for a data workspace IJTXDataWorkspaceName pJobDataWorkspace = pJob.ActiveDatabase; if (pJobDataWorkspace == null) { MessageBox.Show("No data workspace selected for job"); return(3); } // Check if version exists if (pJob.VersionExists()) { MessageBox.Show("Job version has been defined"); return(1); } else { MessageBox.Show("No version defined for job"); return(2); } }
//////////////////////////////////////////////////////////////////////// // METHOD: Execute public int Execute(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback) { // Present form to user for choosing the data workspace // they want to work with for the current job. JTXSamples.DataWorkspaceSelectorDialog frmDataWSSelector = new JTXSamples.DataWorkspaceSelectorDialog(); frmDataWSSelector.StartPosition = FormStartPosition.CenterParent; // Populate the list of data workspaces configured for the JTX system IJTXDatabaseConnectionManager pDBConnManager = new JTXDatabaseConnectionManagerClass(); IJTXDatabaseConnection pDBConnection = pDBConnManager.GetConnection(m_ipDatabase.Alias); for (int a = 0; a < pDBConnection.DataWorkspaceCount; a++) { IJTXWorkspaceConfiguration pDataWorkspace = pDBConnection.get_DataWorkspace(a); frmDataWSSelector.DWName = pDataWorkspace.Name; } // Pass some other information to the form frmDataWSSelector.JTXDB = m_ipDatabase; IJTXJobManager pJobManager = m_ipDatabase.JobManager; IJTXJob2 pJob = pJobManager.GetJob(jobID) as IJTXJob2; frmDataWSSelector.theJob = pJob; if (frmDataWSSelector.ShowDialog() == DialogResult.OK) { return(1); } return(0); }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); // Assign the requested job try { IJTXJobManager jobManager = this.WmxDatabase.JobManager; IJTXConfiguration3 configMgr = this.WmxDatabase.ConfigurationManager as IJTXConfiguration3; IJTXJob3 job = jobManager.GetJob(m_jobId) as IJTXJob3; // As of Jan. 2011, the core Workflow Manager libraries do not // seem to check if the user has the privilege to add a comment // if a job as a hold on it. So run the check here. IJTXJobHolds jobHolds = job as IJTXJobHolds; if (jobHolds.Holds != null && jobHolds.Holds.Count > 0 && !CurrentUserHasPrivilege(ESRI.ArcGIS.JTX.Utilities.Constants.PRIV_CAN_ADD_COMMENTS_FOR_HELD_JOBS)) { throw new WmauException(WmauErrorCodes.C_NO_ADD_COMMENTS_HELD_JOBS_ERROR); } // If we get this far, then add the comment to the job. IJTXActivityType commentType = configMgr.GetActivityType(ESRI.ArcGIS.JTX.Utilities.Constants.ACTTYPE_COMMENT); job.LogJobAction(commentType, null, m_comment); job.Store(); // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_JOB_ID); IGPLong outValue = new GPLongClass(); outValue.Value = m_jobId; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); // Assign the requested job try { IJTXJobManager jobManager = this.WmxDatabase.JobManager; IJTXWorkflowExecution3 jobExec = jobManager.GetJob(m_jobId) as IJTXWorkflowExecution3; // Don't try to deal with the case of multiple active steps int[] currentStepIds = jobExec.GetCurrentSteps(); if (currentStepIds.Length != 1) { throw new WmauException(WmauErrorCodes.C_NO_OR_MULTIPLE_STEPS_ERROR); } jobExec.RunStepChecks(currentStepIds[0], true); IJTXExecuteInfo execInfo = jobExec.RunStep(currentStepIds[0], false, true, false, this); if (execInfo.ThrewError) { throw new WmauException( WmauErrorCodes.C_JOB_EXECUTION_ERROR, new Exception(execInfo.ErrorCode.ToString() + ": " + execInfo.ErrorDescription)); } // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_JOB_ID); IGPLong outValue = new GPLongClass(); outValue.Value = m_jobId; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } }
/// <summary> /// Called when a step of this type is executed in the workflow. /// </summary> /// <param name="JobID">ID of the job being executed</param> /// <param name="StepID">ID of the step being executed</param> /// <param name="argv">Array of arguments passed into the step's execution</param> /// <param name="ipFeedback">Feedback object to return status messages and files</param> /// <returns>Return code of execution for workflow path traversal</returns> public int Execute(int JobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback) { System.Diagnostics.Debug.Assert(m_ipDatabase != null); if (!ConfigurationCache.IsInitialized) { ConfigurationCache.InitializeCache(m_ipDatabase); } IJTXJobManager jobMan = m_ipDatabase.JobManager; IJTXJob2 m_ParentJob = (IJTXJob2)jobMan.GetJob(JobID); if (!GetInputParams(argv)) { return(0); } return(CreateJobs(m_ParentJob)); }
/// <summary> /// Called when a step of this type is executed in the workflow. /// </summary> /// <param name="JobID">ID of the job being executed</param> /// <param name="StepID">ID of the step being executed</param> /// <param name="argv">Array of arguments passed into the step's execution</param> /// <param name="ipFeedback">Feedback object to return status messages and files</param> /// <returns>Return code of execution for workflow path traversal</returns> public int Execute(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback) { IJTXJobManager ipJobManager = m_ipDatabase.JobManager; IJTXConfiguration ipConfig = m_ipDatabase.ConfigurationManager; IJTXJob ipJob = ipJobManager.GetJob(jobID); string strAssignType = ""; string strAssignTo = ""; if (!StepUtilities.GetArgument(ref argv, m_expectedArgs[0], true, out strAssignType)) { throw new ArgumentNullException(m_expectedArgs[0], string.Format("\nMissing the {0} parameter!", m_expectedArgs[0])); } if (!StepUtilities.GetArgument(ref argv, m_expectedArgs[1], true, out strAssignTo)) { throw new ArgumentNullException(m_expectedArgs[1], string.Format("\nMissing the {0} parameter!", m_expectedArgs[1])); } if (strAssignType == "group") { if (ipConfig.GetUserGroup(strAssignTo) == null) { throw new ArgumentOutOfRangeException(m_expectedArgs[1], string.Format("\nThe group {0} is not a group defined in the JTX database!", strAssignTo)); } ipJob.AssignedType = jtxAssignmentType.jtxAssignmentTypeGroup; } else { if (ipConfig.GetUser(strAssignTo) == null) { throw new ArgumentOutOfRangeException(m_expectedArgs[1], string.Format("\nThe user {0} is not a user defined in the JTX database!", strAssignTo)); } ipJob.AssignedType = jtxAssignmentType.jtxAssignmentTypeUser; } ipJob.AssignedTo = strAssignTo; ipJob.Store(); return(0); }
/// <summary> /// Called when a step of this type is executed in the workflow. /// </summary> /// <param name="JobID">ID of the job being executed</param> /// <param name="StepID">ID of the step being executed</param> /// <param name="argv">Array of arguments passed into the step's execution</param> /// <param name="ipFeedback">Feedback object to return status messages and files</param> /// <returns>Return code of execution for workflow path traversal</returns> public int Execute(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback) { // Get the arguments string sHoldTypeName = ""; string sHoldRemarks = ""; bool bHoldType = StepUtilities.GetArgument(ref argv, "HoldType", true, out sHoldTypeName); if (!bHoldType) { MessageBox.Show("Invalid arguments entered. No hold type entered."); return(-1); } bool bHoldRemarks = StepUtilities.GetArgument(ref argv, "HoldRemarks", true, out sHoldRemarks); // Get the hold type IJTXConfiguration pJTXConfig = m_ipDatabase.ConfigurationManager; IJTXHoldType pHoldType = pJTXConfig.GetHoldType(sHoldTypeName); if (pHoldType == null) { MessageBox.Show("Invalid hold type name entered: " + sHoldTypeName); return(-1); } // Get the job IJTXJobManager pJobManager = m_ipDatabase.JobManager; IJTXJob pJob = pJobManager.GetJob(jobID); IJTXJobHolds pJobHolds = pJob as IJTXJobHolds; // Add new job hold IJTXJobHold pNewHold = pJobHolds.CreateHold(pHoldType); if (bHoldRemarks) { pNewHold.HoldComments = sHoldRemarks; pNewHold.Store(); } return(0); }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Send the notification IJTXJobManager jobManager = this.WmxDatabase.JobManager; Common.WmauHelperFunctions.SendNotification( m_notificationName, this.WmxDatabase, jobManager.GetJob(m_jobId)); // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_JOB_ID); IGPLong outValue = new GPLongClass(); outValue.Value = m_jobId; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } }
/// <summary> /// Called when a step of this type is executed in the workflow. /// </summary> /// <param name="JobID">ID of the job being executed</param> /// <param name="StepID">ID of the step being executed</param> /// <param name="argv">Array of arguments passed into the step's execution</param> /// <param name="ipFeedback">Feedback object to return status messages and files</param> /// <returns>Return code of execution for workflow path traversal</returns> public int Execute(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback) { if (jobID <= 0) { throw (new ArgumentOutOfRangeException("JobID", jobID, "Job ID must be a positive value")); } System.Diagnostics.Debug.Assert(m_ipDatabase != null); IJTXJobManager pJobMan = m_ipDatabase.JobManager; IJTXJob2 pJob = pJobMan.GetJob(jobID) as IJTXJob2; // Make sure all the information exists to create this verion if (pJob.ActiveDatabase == null) { System.Windows.Forms.MessageBox.Show("Job does not have a data workspace"); return(-1); } if (pJob.ParentVersion == "") { System.Windows.Forms.MessageBox.Show("Job does not have a parent version"); return(-1); } string strVersionNameOverride; bool bVNOverride = StepUtilities.GetArgument(ref argv, m_expectedArgs[1], true, out strVersionNameOverride); if (pJob.VersionName == "" & !bVNOverride) { System.Windows.Forms.MessageBox.Show("The job does not have a version name"); return(-1); } IVersion pNewVersion; string strVersionName; if (bVNOverride) { strVersionName = strVersionNameOverride; } else { strVersionName = pJob.VersionName; } int index = strVersionName.IndexOf(".", 0); if (index >= 0) { strVersionName = strVersionName.Substring(index + 1); } esriVersionAccess verAccess = esriVersionAccess.esriVersionAccessPrivate; string strVerScope = ""; if (StepUtilities.GetArgument(ref argv, m_expectedArgs[0], true, out strVerScope)) { strVerScope = strVerScope.ToLower().Trim(); if (strVerScope == "public") { verAccess = esriVersionAccess.esriVersionAccessPublic; } else if (strVerScope == "protected") { verAccess = esriVersionAccess.esriVersionAccessProtected; } } pJob.VersionName = strVersionName; pNewVersion = pJob.CreateVersion(verAccess); if (pNewVersion == null) { throw (new System.SystemException("Unable to create version")); } IPropertySet pOverrides = new PropertySetClass(); pOverrides.SetProperty("[VERSION]", pNewVersion.VersionName); IJTXActivityType pActType = m_ipDatabase.ConfigurationManager.GetActivityType(Constants.ACTTYPE_CREATE_VERSION); if (pActType != null) { pJob.LogJobAction(pActType, pOverrides, ""); } JTXUtilities.SendNotification(Constants.NOTIF_VERSION_CREATED, m_ipDatabase, pJob, pOverrides); System.Runtime.InteropServices.Marshal.ReleaseComObject(pNewVersion); return(0); }
static void Main(string[] args) { JTXOverdueNotification prog = new JTXOverdueNotification(); if (prog.CheckoutLicense()) { try { // Arguments list // /NotifType:<Notification type to send> // example: JTXOverdueNotification.exe /NotifType:OverdueJob object[] pArgObjects = args as object[]; // Get some variables ready string sNotificationTypeName = ""; StepUtilities.GetArgument(ref pArgObjects, "NotifType", true, out sNotificationTypeName); if (sNotificationTypeName == "") { Console.WriteLine("A notification type must be entered."); return; } IJTXDatabaseManager jtxDBMan = new JTXDatabaseManagerClass(); IJTXDatabase pJTXDB = jtxDBMan.GetActiveDatabase(false); IJTXConfiguration pJTXConfig = pJTXDB.ConfigurationManager; // Create a simple query to find jobs that were due before today IQueryFilter pQF = new QueryFilterClass(); // NOTE #1: Verify the date format matches your selected RDBMS // NOTE #2: Verify the status id for 'Closed' with the JTX Administrator pQF.WhereClause = "DUE_DATE < '" + DateTime.Today.ToString() + "'" + " AND STATUS <> 9"; Console.WriteLine(pQF.WhereClause); // Get the notification type for the notification that will be sent IJTXNotificationConfiguration pNotificationConfig = pJTXConfig as IJTXNotificationConfiguration; IJTXNotificationType pNotificationType = pNotificationConfig.GetNotificationType(sNotificationTypeName); if (pNotificationType == null) { Console.WriteLine("Please enter a valid notification type."); return; } // Get the job manager to execute the query and find the jobs in question IJTXJobManager pJobManager = pJTXDB.JobManager; IJTXJobSet pJobs = pJobManager.GetJobsByQuery(pQF); pJobs.Reset(); for (int a = 0; a < pJobs.Count; a++) { IJTXJob pJob = pJobs.Next(); Console.WriteLine(pJob.Name); // Send it! JTXUtilities.SendNotification(sNotificationTypeName, pJTXDB, pJob, null); } } catch (Exception except) { Console.WriteLine("An error occurred: " + except.Message); } prog.CheckinLicense(); Console.WriteLine("Completed."); } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); // Assign the requested job try { IJTXJobManager jobManager = this.WmxDatabase.JobManager; IJTXJob3 job = jobManager.GetJob(m_jobId) as IJTXJob3; IJTXConfiguration3 configMgr = this.WmxDatabase.ConfigurationManager as IJTXConfiguration3; jtxAssignmentType assigneeType; string descriptionStr; string assigneeStr; if (m_assigneeType.Equals(C_OPT_ASSIGN_TO_GROUP)) { assigneeType = jtxAssignmentType.jtxAssignmentTypeGroup; assigneeStr = m_assignee; descriptionStr = "group '" + assigneeStr + "'"; } else if (m_assigneeType.Equals(C_OPT_ASSIGN_TO_USER)) { assigneeType = jtxAssignmentType.jtxAssignmentTypeUser; assigneeStr = m_assignee; descriptionStr = "user '" + assigneeStr + "'"; } else { assigneeType = jtxAssignmentType.jtxAssignmentTypeUnassigned; assigneeStr = string.Empty; descriptionStr = "no one (unassigned)"; } msgs.AddMessage("Assigning job " + m_jobId + " (" + job.Name + ") to " + descriptionStr); job.AssignedType = assigneeType; job.AssignedTo = assigneeStr; job.Store(); // Do the other things that still need to be handled manually, such as logging // the job's reassignment and sending any necessary notifications. job.LogJobAction( configMgr.GetActivityType(ESRI.ArcGIS.JTX.Utilities.Constants.ACTTYPE_ASSIGN_JOB), null, string.Empty); Common.WmauHelperFunctions.SendNotification( ESRI.ArcGIS.JTX.Utilities.Constants.NOTIF_JOB_ASSIGNED, this.WmxDatabase, job); // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_JOB_ID); IGPLong outValue = new GPLongClass(); outValue.Value = m_jobId; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } }
//////////////////////////////////////////////////////////////////////// // METHOD: SetJobProperties private IJTXJob SetJobProperties(IJTXJobManager pJobMan, IJTXJob pJob, IJTXJob2 pParentJob) { m_ipDatabase.LogMessage(5, 2000, "Before LogJobAction (CreateJobs)"); IJTXActivityType pActType = m_ipDatabase.ConfigurationManager.GetActivityType(Constants.ACTTYPE_COMMENT); pParentJob.LogJobAction(pActType, null, String.Format(Properties.Resources.ActTypeMessage, pJob.ID.ToString())); if (!string.IsNullOrEmpty(m_paramExtendedProperties)) { m_ipDatabase.LogMessage(5, 2000, "Before Create Extended Properties"); ExtendedPropertyIdentifier childExProps = new ExtendedPropertyIdentifier(); try { ParseExtendedPropertiesParam(out childExProps); } catch (Exception ex) { string msg = string.Format( "Unable to read parent job's extended property. Job ID: {0} ERROR: {1}", pParentJob.ID, ex.Message); m_ipDatabase.LogMessage(3, 1000, msg); } try { CreateExtendedPropertyRecord(pJob, childExProps); } catch (Exception ex) { string msg = string.Format( "Unable to set child job's extended property. Child Job ID: {0} ERROR: {1}", pJob.ID, ex.Message); m_ipDatabase.LogMessage(3, 1000, msg); } m_ipDatabase.LogMessage(5, 2000, "After Create Extended Properties"); } // Create dependencies on parent job if configured m_ipDatabase.LogMessage(5, 2000, "Before Setting Dependencies"); if (m_paramDependNextStep || m_paramDependThisStep) { IJTXJobDependencies ipDependencyManager = pJobMan as IJTXJobDependencies; CreateDependencyOnParentJob(ipDependencyManager, pParentJob, pJob.ID); } m_ipDatabase.LogMessage(5, 2000, "After Setting Dependencies"); // Create or assign version if configured m_ipDatabase.LogMessage(5, 2000, "Before Versioning"); if (m_paramCreateVersionType != CreateVersionType.None) { if (pParentJob.ActiveDatabase != null && !String.IsNullOrEmpty(pJob.ParentVersion) && (m_paramCreateVersionType != CreateVersionType.UseParentJobsVersion || pParentJob.VersionExists())) CreateChildVersion(ref pJob); else MessageBox.Show("Could not create version. Please ensure parent data workspace and versions are set correctly", Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (m_paramAssignVersionType != AssignVersionType.None) { if (pParentJob.ActiveDatabase != null) AssignChildVersion(pParentJob, ref pJob); else MessageBox.Show("Could not assign version. Please ensure parent data workspace is set correctly", Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); } m_ipDatabase.LogMessage(5, 2000, "After Versioning"); // Store the job and save the changes m_ipDatabase.LogMessage(5, 2000, "Before Storing Job"); pJob.Store(); m_ipDatabase.LogMessage(5, 2000, "After Storing Job"); return pJob; }
/// <summary> /// Called when a step of this type is executed in the workflow. /// </summary> /// <param name="JobID">ID of the job being executed</param> /// <param name="StepID">ID of the step being executed</param> /// <param name="argv">Array of arguments passed into the step's execution</param> /// <param name="ipFeedback">Feedback object to return status messages and files</param> /// <returns>Return code of execution for workflow path traversal</returns> public int Execute(int JobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback) { System.Diagnostics.Debug.Assert(m_ipDatabase != null); string strValue = ""; int jobTypeID = 0; if (!StepUtilities.GetArgument(ref argv, m_expectedArgs[0], true, out strValue)) { throw new ArgumentNullException(m_expectedArgs[0], string.Format("\nMissing the {0} parameter!", m_expectedArgs[0])); } if (!Int32.TryParse(strValue, out jobTypeID)) { throw new ArgumentNullException(m_expectedArgs[0], "Argument must be an integrer!"); } IJTXJobType pJobType = m_ipDatabase.ConfigurationManager.GetJobTypeByID(jobTypeID); IJTXJobManager pJobMan = m_ipDatabase.JobManager; IJTXJob pNewJob = pJobMan.CreateJob(pJobType, 0, true); IJTXActivityType pActType = m_ipDatabase.ConfigurationManager.GetActivityType(Constants.ACTTYPE_CREATE_JOB); if (pActType != null) { pNewJob.LogJobAction(pActType, null, ""); } JTXUtilities.SendNotification(Constants.NOTIF_JOB_CREATED, m_ipDatabase, pNewJob, null); // Assign a status to the job if the Auto Assign Job Status setting is enabled IJTXConfigurationProperties pConfigProps = (IJTXConfigurationProperties)m_ipDatabase.ConfigurationManager; if (pConfigProps.PropertyExists(Constants.JTX_PROPERTY_AUTO_STATUS_ASSIGN)) { string strAutoAssign = pConfigProps.GetProperty(Constants.JTX_PROPERTY_AUTO_STATUS_ASSIGN); if (strAutoAssign == "TRUE") { pNewJob.Status = m_ipDatabase.ConfigurationManager.GetStatus("Created"); } } // Associate the current job with the new job with a parent-child relationship pNewJob.ParentJob = JobID; // Assign the job as specified in the arguments string strAssignTo = ""; if (StepUtilities.GetArgument(ref argv, m_expectedArgs[1], true, out strAssignTo)) { pNewJob.AssignedType = jtxAssignmentType.jtxAssignmentTypeGroup; pNewJob.AssignedTo = strAssignTo; } else if (StepUtilities.GetArgument(ref argv, m_expectedArgs[2], true, out strAssignTo)) { pNewJob.AssignedType = jtxAssignmentType.jtxAssignmentTypeUser; pNewJob.AssignedTo = strAssignTo; } pNewJob.Store(); // Copy the workflow to the new job WorkflowUtilities.CopyWorkflowXML(m_ipDatabase, pNewJob); // Create 1-1 extended property entries IJTXAuxProperties pAuxProps = (IJTXAuxProperties)pNewJob; System.Array contNames = pAuxProps.ContainerNames; IEnumerator contNamesEnum = contNames.GetEnumerator(); contNamesEnum.Reset(); while (contNamesEnum.MoveNext()) { string strContainerName = (string)contNamesEnum.Current; IJTXAuxRecordContainer pAuxContainer = pAuxProps.GetRecordContainer(strContainerName); if (pAuxContainer.RelationshipType == esriRelCardinality.esriRelCardinalityOneToOne) { pAuxContainer.CreateRecord(); } } m_ipDatabase.LogMessage(5, 1000, System.Diagnostics.Process.GetCurrentProcess().MainWindowTitle); // Update Application message about the new job if (System.Diagnostics.Process.GetCurrentProcess().MainWindowTitle.Length > 0) //if its not running in server { MessageBox.Show("Created " + pJobType.Name + " Job " + pNewJob.ID, "Job Created", MessageBoxButtons.OK, MessageBoxIcon.Information); } return(0); }
private int addAttachments(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback) { // Get a handle to the job IJTXJobManager pJobManager = m_ipDatabase.JobManager; IJTXJob2 pJob = pJobManager.GetJob(jobID) as IJTXJob2; IJTXJob2 pParentJob = pJobManager.GetJob(pJob.ParentJob) as IJTXJob2; // Prompt the user to choose whether the attachment should be embedded // into the database or merely stored as a URL, UNC path, etc. AttachmentTypeDialog atd = new AttachmentTypeDialog(); // Check to see if this job has a parent. If so, enable the "attach to parent" dialog. if (pParentJob == null) { atd.EnableSelectParent = false; } else { atd.EnableSelectParent = true; } atd.ShowDialog(); if (atd.isNoneSelected()) { return(0); } // Set the file storage type, according to what the user selected. bool embedAttachment = atd.isEmbeddedSelected(); jtxFileStorageType fileStorageType; if (embedAttachment) { fileStorageType = jtxFileStorageType.jtxStoreInDB; } else { fileStorageType = jtxFileStorageType.jtxStoreAsLink; } // Prompt the user to select the file(s) to be attached. System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog(); ofd.CheckFileExists = true; ofd.Multiselect = false; ofd.ShowDialog(); // Add each file that the user selected. foreach (string filename in ofd.FileNames) { if (atd.AttachToCurrent) { pJob.AddAttachment(filename, fileStorageType, ""); } if (atd.AttachToParent) { pParentJob.AddAttachment(filename, fileStorageType, ""); } } return(1); }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); ////////////////////////////////////////////////////////////////////// // TODO: Update the job-deletion logic. // // In subsequent builds of Workflow Manager (post-10.0), there may be // a new API that deletes jobs and handles some of the logic included // in this class (ex: checking permissions, deleting versions, etc.). // If so, this GP tool should be revised to make use of this // simplified interface. // // Anyone using this tool as a reference, particularly with regards // to deleting Workflow Manager jobs, should keep this in mind. ////////////////////////////////////////////////////////////////////// // Delete the requested job try { IJTXJobManager jobManager = this.WmxDatabase.JobManager; IJTXJob3 job = jobManager.GetJob(m_jobToDelete) as IJTXJob3; msgs.AddMessage("Deleting job " + m_jobToDelete + " (" + job.Name + ")"); job.DeleteMXD(); if (job.VersionExists()) { if (CurrentUserHasPrivilege(ESRI.ArcGIS.JTX.Utilities.Constants.PRIV_DELETE_VERSION)) { try { job.DeleteVersion(null); } catch (System.Runtime.InteropServices.COMException comEx) { if (comEx.ErrorCode == (int)fdoError.FDO_E_SE_VERSION_NOEXIST) { // The "VersionExists" method above can apparently be fooled; if it is, an exception with this // error code is thrown. In this case, add a warning and continue on. msgs.AddWarning("Version '" + job.VersionName + "' is assigned to job " + job.ID.ToString() + " but could not be found"); } else { // If there's a different error, then re-throw it for someone else to deal with throw comEx; } } } else { string username = ESRI.ArcGIS.JTXUI.ConfigurationCache.GetCurrentSystemUser(ESRI.ArcGIS.JTXUI.ConfigurationCache.UseUserDomain); msgs.AddWarning("User '" + username + "' does not have permissions to " + "delete job versions; version '" + job.VersionName + "' will not be deleted"); } } jobManager.DeleteJob(m_jobToDelete, true); // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_JOB_DELETED); IGPLong outValue = new GPLongClass(); outValue.Value = m_jobToDelete; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (Exception ex) { WmauError error = new WmauError(WmauErrorCodes.C_DELETE_JOB_VERSION_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); StreamWriter logFileWriter = null; try { int errorCount = 0; if (!string.IsNullOrEmpty(m_logFilePath)) { logFileWriter = new StreamWriter(m_logFilePath); } IJTXConfiguration3 configMgr = this.WmxDatabase.ConfigurationManager as IJTXConfiguration3; IJTXConfigurationEdit2 configEdit = configMgr as IJTXConfigurationEdit2; IJTXJobManager jobMgr = this.WmxDatabase.JobManager; // Workflow Manager intentionally caches the data workspaces in the system. To ensure // that we have the most current list of data workspaces, invalidate this cache // before attempting to retrieve the list from the system. this.WmxDatabase.InvalidateDataWorkspaceNames(); // Run checks against users ExecuteUserChecks(msgs, ref errorCount, logFileWriter); // Run checks against groups ExecuteGroupChecks(msgs, ref errorCount, logFileWriter); // Run checks against any existing jobs ExecuteJobChecks(msgs, ref errorCount, logFileWriter); // Check for any template job types with an invalid default assignment ExecuteJobTypeChecks(msgs, ref errorCount, logFileWriter); // Check the workflow steps for problems ExecuteWorkflowStepChecks(msgs, ref errorCount, logFileWriter); // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_ISSUES_FOUND); IGPLong outValue = new GPLongClass(); outValue.Value = errorCount; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } finally { // Release any COM objects here! if (logFileWriter != null) { logFileWriter.Close(); } } }
/// <summary> /// Helper function that runs all of those checks that operate on each job; intended /// to make the checks slightly more efficient by running through them all at once /// rather than looping through all of the elements multiple times /// </summary> /// <param name="msgs">Add any GP messages to this object</param> /// <param name="errorCount">Counter used to track the number of problems found</param> /// <param name="logFileWriter">Object used to write error descriptions to a text file</param> private void ExecuteJobChecks(IGPMessages msgs, ref int errorCount, StreamWriter logFileWriter) { // Only continue executing this function if needed if (!m_flagInvalidJobAssign && !m_flagIsSelfParent && !m_flagJobsWithoutTypes) { return; } IJTXConfiguration3 configMgr = this.WmxDatabase.ConfigurationManager as IJTXConfiguration3; IJTXConfigurationEdit2 configEdit = configMgr as IJTXConfigurationEdit2; IJTXJobManager jobMgr = this.WmxDatabase.JobManager; // Use a database query as an alternate way of finding certain specific // problems with jobs. Declare some of these ComReleaser objects to help // ensure that cursors, etc., are immediately released after they go out // of scope. // Check for jobs without any job types set (should be a DB error) if (m_flagJobsWithoutTypes) { using (ComReleaser cr1 = new ComReleaser(), cr2 = new ComReleaser()) { IFeatureWorkspace featureWorkspace = this.WmxDatabase.JTXWorkspace as IFeatureWorkspace; // Get the name of the correct table from the jobs workspace, so // that the table doesn't have to be owned by the connecting user. string tableName = Common.WmauHelperFunctions.GetQualifiedTableName(Constants.JTX_TABLE_JTX_JOBS_TABLE, this.WmxDatabase.JTXWorkspace); ITable jobsTable = featureWorkspace.OpenTable(tableName); cr1.ManageLifetime(jobsTable); IQueryFilter query = new QueryFilterClass(); query.WhereClause = Constants.FIELD_JOBTYPEID + " IS NULL"; ICursor searchCursor = jobsTable.Search(query, true); cr2.ManageLifetime(searchCursor); // Store the ID and name of each job matching this query int idIndex = jobsTable.FindField(Constants.FIELD_JOBID); int nameIndex = jobsTable.FindField(Constants.FIELD_JOBNAME); IRow row = null; while ((row = searchCursor.NextRow()) != null) { string idStr = row.get_Value(idIndex).ToString(); string nameStr = row.get_Value(nameIndex).ToString(); string msg = "Job " + idStr + " (" + nameStr + ") has no associated job type"; RecordMessage(msg, msgs, logFileWriter); errorCount++; } } } // Check for jobs that are their own parent job if (m_flagIsSelfParent) { using (ComReleaser cr1 = new ComReleaser(), cr2 = new ComReleaser()) { IFeatureWorkspace featureWorkspace = this.WmxDatabase.JTXWorkspace as IFeatureWorkspace; // Get the name of the correct table from the jobs workspace, so // that the table doesn't have to be owned by the connecting user. string tableName = Common.WmauHelperFunctions.GetQualifiedTableName(Constants.JTX_TABLE_JTX_JOBS_TABLE, this.WmxDatabase.JTXWorkspace); ITable jobsTable = featureWorkspace.OpenTable(tableName); cr1.ManageLifetime(jobsTable); const string C_FIELD_PARENT_JOB = "PARENT_JOB"; IQueryFilter query = new QueryFilterClass(); query.WhereClause = Constants.FIELD_JOBID + " = " + C_FIELD_PARENT_JOB; ICursor searchCursor = jobsTable.Search(query, true); cr2.ManageLifetime(searchCursor); // Store the ID and name of each job matching this query int idIndex = jobsTable.FindField(Constants.FIELD_JOBID); int nameIndex = jobsTable.FindField(Constants.FIELD_JOBNAME); IRow row = null; while ((row = searchCursor.NextRow()) != null) { string idStr = row.get_Value(idIndex).ToString(); string nameStr = row.get_Value(nameIndex).ToString(); string msg = "Job " + idStr + " (" + nameStr + ") is its own parent"; RecordMessage(msg, msgs, logFileWriter); errorCount++; } } } // See if there are any checks selected for which we should iterate through // all of the jobs using the WMX interfaces if (m_flagInvalidJobAssign) { // Put the items into a sorted list in order to make the output easier to // read/follow IJTXJobSet allJobs = jobMgr.GetAllJobs(); SortedList <int, IJTXJob3> allJobsSorted = new SortedList <int, IJTXJob3>(); for (int i = 0; i < allJobs.Count; i++) { allJobsSorted[allJobs.get_Item(i).ID] = allJobs.get_Item(i) as IJTXJob3; } // Iterate over all of the jobs foreach (IJTXJob3 job in allJobsSorted.Values) { string assignedTo = job.AssignedTo; // Check for any existing jobs with an invalid job assignment. NOTE: only // want to flag jobs that are not closed if (m_flagInvalidJobAssign && job.Stage != jtxJobStage.jtxJobStageClosed) { if (job.AssignedType == jtxAssignmentType.jtxAssignmentTypeUser && configMgr.GetUser(assignedTo) == null) { string message = "Job '" + job.ID.ToString() + "' assigned to unknown user '" + assignedTo + "'"; RecordMessage(message, msgs, logFileWriter); errorCount++; } else if (job.AssignedType == jtxAssignmentType.jtxAssignmentTypeGroup && configMgr.GetUserGroup(assignedTo) == null) { string message = "Job '" + job.ID.ToString() + "' assigned to unknown group '" + assignedTo + "'"; RecordMessage(message, msgs, logFileWriter); errorCount++; } } } } }
//////////////////////////////////////////////////////////////////////// // METHOD: SetJobProperties private IJTXJob SetJobProperties(IJTXJobManager pJobMan, IJTXJob pJob, IJTXJob2 pParentJob) { m_ipDatabase.LogMessage(5, 2000, "Before LogJobAction (CreateJobs)"); IJTXActivityType pActType = m_ipDatabase.ConfigurationManager.GetActivityType(Constants.ACTTYPE_COMMENT); pParentJob.LogJobAction(pActType, null, String.Format(Properties.Resources.ActTypeMessage, pJob.ID.ToString())); if (!string.IsNullOrEmpty(m_paramExtendedProperties)) { m_ipDatabase.LogMessage(5, 2000, "Before Create Extended Properties"); ExtendedPropertyIdentifier childExProps = new ExtendedPropertyIdentifier(); try { ParseExtendedPropertiesParam(out childExProps); } catch (Exception ex) { string msg = string.Format( "Unable to read parent job's extended property. Job ID: {0} ERROR: {1}", pParentJob.ID, ex.Message); m_ipDatabase.LogMessage(3, 1000, msg); } try { CreateExtendedPropertyRecord(pJob, childExProps); } catch (Exception ex) { string msg = string.Format( "Unable to set child job's extended property. Child Job ID: {0} ERROR: {1}", pJob.ID, ex.Message); m_ipDatabase.LogMessage(3, 1000, msg); } m_ipDatabase.LogMessage(5, 2000, "After Create Extended Properties"); } // Create dependencies on parent job if configured m_ipDatabase.LogMessage(5, 2000, "Before Setting Dependencies"); if (m_paramDependNextStep || m_paramDependThisStep) { IJTXJobDependencies ipDependencyManager = pJobMan as IJTXJobDependencies; CreateDependencyOnParentJob(ipDependencyManager, pParentJob, pJob.ID); } m_ipDatabase.LogMessage(5, 2000, "After Setting Dependencies"); // Create or assign version if configured m_ipDatabase.LogMessage(5, 2000, "Before Versioning"); if (m_paramCreateVersionType != CreateVersionType.None) { if (pParentJob.ActiveDatabase != null && !String.IsNullOrEmpty(pJob.ParentVersion) && (m_paramCreateVersionType != CreateVersionType.UseParentJobsVersion || pParentJob.VersionExists())) { CreateChildVersion(ref pJob); } else { MessageBox.Show("Could not create version. Please ensure parent data workspace and versions are set correctly", Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else if (m_paramAssignVersionType != AssignVersionType.None) { if (pParentJob.ActiveDatabase != null) { AssignChildVersion(pParentJob, ref pJob); } else { MessageBox.Show("Could not assign version. Please ensure parent data workspace is set correctly", Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } m_ipDatabase.LogMessage(5, 2000, "After Versioning"); // Store the job and save the changes m_ipDatabase.LogMessage(5, 2000, "Before Storing Job"); pJob.Store(); m_ipDatabase.LogMessage(5, 2000, "After Storing Job"); return(pJob); }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); // Assign the requested job try { IJTXJobManager jobManager = this.WmxDatabase.JobManager; IJTXJob3 job = jobManager.GetJob(m_jobId) as IJTXJob3; IJTXConfiguration3 configMgr = this.WmxDatabase.ConfigurationManager as IJTXConfiguration3; // As of Jan. 2011, the core Workflow Manager libraries do not // seem to check if the user has the privilege to add an attachment // if a job as a hold on it. So run the check here. IJTXJobHolds jobHolds = job as IJTXJobHolds; if (jobHolds.Holds != null && jobHolds.Holds.Count > 0 && !CurrentUserHasPrivilege(ESRI.ArcGIS.JTX.Utilities.Constants.PRIV_CAN_ADD_ATTACHES_FOR_HELD_JOBS)) { throw new WmauException(WmauErrorCodes.C_NO_ADD_ATTACHMENTS_HELD_JOBS_ERROR); } // If we get this far, then figure out how to associate the attachment // with the job, and add the attachment. jtxFileStorageType attachmentType; if (m_attachmentType.Equals(C_OPT_EMBEDDED)) { attachmentType = jtxFileStorageType.jtxStoreInDB; } else { attachmentType = jtxFileStorageType.jtxStoreAsLink; } msgs.AddMessage("Adding attachment '" + m_attachmentPath + "' to job " + m_jobId + " (" + job.Name + ")"); job.AddAttachment(m_attachmentPath, attachmentType, m_attachmentType); job.Store(); // Do the other things that still need to be handled manually, such as logging // the job's reassignment and sending any necessary notifications. IPropertySet propSet = new PropertySetClass(); propSet.SetProperty(C_PROP_VAL_ATTACHMENT, "'" + m_attachmentPath + "'"); job.LogJobAction( configMgr.GetActivityType(ESRI.ArcGIS.JTX.Utilities.Constants.ACTTYPE_ADD_ATTACHMENT), propSet, string.Empty); Common.WmauHelperFunctions.SendNotification( ESRI.ArcGIS.JTX.Utilities.Constants.NOTIF_ATTACHMENT_ADDED, this.WmxDatabase, job); // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_JOB_ID); IGPLong outValue = new GPLongClass(); outValue.Value = m_jobId; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } }
/// <summary> /// Find those users in the database who are not being referenced in any way /// </summary> /// <returns>The total number of orphaned items found</returns> private int UpdateOrphanedUsers() { SortedList <string, string> unusedItems = new SortedList <string, string>(); IJTXDatabase3 wmxDb = this.WmxDatabase; IJTXConfiguration3 configMgr = wmxDb.ConfigurationManager as IJTXConfiguration3; IJTXJobManager jobMgr = wmxDb.JobManager; IJTXUserSet allUsers = configMgr.Users; Dictionary <string, string> usedItems = new Dictionary <string, string>(); // Get all of the users who are members of a group IJTXUserGroupSet allGroups = configMgr.UserGroups; for (int i = 0; i < allGroups.Count; i++) { IJTXUserGroup2 group = allGroups.get_Item(i) as IJTXUserGroup2; for (int j = 0; j < group.Users.Count; j++) { IJTXUser3 user = group.Users.get_Item(j) as IJTXUser3; usedItems[user.UserName] = user.FullName; } } // If necessary, add in the users who have jobs assigned to them if (usedItems.Count < allUsers.Count) { IJTXJobSet allJobs = jobMgr.GetAllJobs(); for (int i = 0; i < allJobs.Count; i++) { IJTXJob3 job = allJobs.get_Item(i) as IJTXJob3; if (job.AssignedType == jtxAssignmentType.jtxAssignmentTypeUser) { IJTXUser3 user = configMgr.GetUser(job.AssignedTo) as IJTXUser3; // It's possible for a user to have a job assigned, but have // already been removed from the DB. Throw an exception in // this case, as the DB needs to be cleaned up. if (user == null) { throw new WmauException(WmauErrorCodes.C_USER_NOT_FOUND_ERROR); } usedItems[user.UserName] = user.FullName; } } } // If necessary, add in the users who have a job type's default assignment // set to them if (usedItems.Count < allUsers.Count) { IJTXJobTypeSet allJobTypes = configMgr.JobTypes; for (int i = 0; i < allJobTypes.Count; i++) { // TODO: Exclude orphaned job types IJTXJobType3 jobType = allJobTypes.get_Item(i) as IJTXJobType3; if (jobType.DefaultAssignedType == jtxAssignmentType.jtxAssignmentTypeUser) { IJTXUser3 user = configMgr.GetUser(jobType.DefaultAssignedTo) as IJTXUser3; // It's possible for a user to have a job assigned, but have // already been removed from the DB. Throw an exception in // this case, as the DB needs to be cleaned up. if (user == null) { throw new WmauException(WmauErrorCodes.C_USER_NOT_FOUND_ERROR); } usedItems[user.UserName] = user.FullName; } } } // If necessary, add in the users who have steps assigned to them // by default if (usedItems.Count < allUsers.Count) { IJTXWorkflowSet allWorkflows = configMgr.Workflows; for (int i = 0; i < allWorkflows.Count; i++) { // Skip over unused workflows IJTXWorkflow workflow = allWorkflows.get_Item(i); if (m_unusedWorkflows.Keys.Contains(workflow.ID)) { continue; } // Examine the other items IJTXWorkflowConfiguration workflowCfg = allWorkflows.get_Item(i) as IJTXWorkflowConfiguration; int[] workflowStepIds = workflowCfg.GetAllSteps(); foreach (int j in workflowStepIds) { IJTXStep3 step = workflowCfg.GetStep(j) as IJTXStep3; if (step.AssignedType == jtxAssignmentType.jtxAssignmentTypeUser) { IJTXUser3 user = configMgr.GetUser(step.AssignedTo) as IJTXUser3; // It's possible for a user to have a job assigned, but have // already been removed from the DB. Throw an exception in // this case, as the DB needs to be cleaned up. if (user == null) { throw new WmauException(WmauErrorCodes.C_USER_NOT_FOUND_ERROR); } usedItems[user.UserName] = user.FullName; } } } } // Loop over all the users in the DB, looking for anything // that we didn't identify as "in use" for (int i = 0; i < allUsers.Count; i++) { IJTXUser3 item = allUsers.get_Item(i) as IJTXUser3; if (!usedItems.ContainsKey(item.UserName)) { m_unusedUsers[item.UserName] = item.FullName; } } return(m_unusedUsers.Count); }