Example #1
0
        /// <summary>
        /// 关闭工作
        /// </summary>
        /// <typeparam name="TData"></typeparam>
        /// <param name="data"></param>
        /// <param name="entityType"></param>
        /// <param name="userJob"></param>
        /// <param name="status"></param>
        private void OnClose(TData data, int entityType, UserJobType userJob, JobStatusType status = JobStatusType.Succeed)

        {
            var jobs = business.Access.All(p => p.EntityType == entityType && p.LinkId == data.Id &&
                                           p.JobType == userJob && p.JobStatus < JobStatusType.Succeed);

            if (userJob == UserJobType.Edit)
            {
                foreach (var job in jobs)
                {
                    if (job.ToUserId == TriggerUserId)
                    {
                        business.Close(job.Id);
                    }
                    business.Access.SetValue(p => p.JobStatus, status, job.Id);
                }
            }
            else
            {
                foreach (var job in jobs)
                {
                    if (job.ToUserId == TriggerUserId)
                    {
                        business.Access.SetValue(p => p.JobStatus, status, job.Id);
                        business.Close(job.Id);
                    }
                    else if (data.AuditState == AuditStateType.Deny)
                    {
                        business.Access.SetValue(p => p.JobStatus, JobStatusType.NoHit, job.Id);
                        business.Close(job.Id);
                    }
                }
            }
        }
        public List <JobStatusType> GetJobStatusTypes()
        {
            List <JobStatusType> jobStatusTypes = new List <JobStatusType>();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                string     textCommand = "SELECT * FROM tbl_JobStatusTypes";
                SqlCommand command     = new SqlCommand(textCommand, connection);
                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        JobStatusType jobStatusType = new JobStatusType
                        {
                            JobStatusTypeId   = Convert.ToInt32(reader["JobStatusTypeId"].ToString()),
                            JobStatusTypeName = reader["JobStatusTypeName"].ToString()
                        };

                        jobStatusTypes.Add(jobStatusType);
                    }
                    connection.Close();
                }
            }
            return(jobStatusTypes);
        }
Example #3
0
        /// <summary>
        ///     工作内容状态枚举类型名称转换
        /// </summary>
        public static string ToCaption(this JobStatusType value)
        {
            switch (value)
            {
            case JobStatusType.None:
                return("未开始");

            case JobStatusType.Trans:
                return("转发");

            case JobStatusType.Succeed:
                return("完成");

            case JobStatusType.Canceled:
                return("取消");

            case JobStatusType.NoHit:
                return("未命中");

            case JobStatusType.Notify:
                return("通知");

            default:
                return("工作内容状态枚举类型(未知)");
            }
        }
        public async Task <string> GetTemplate(long jobId, JobStatusType status, JobType jobType, DateTime dateTimeJobSubmittedUtc)
        {
            using (IJobQueueDataContext context = _contextFactory())
            {
                var job = await context.FileUploadJobMetaData.SingleOrDefaultAsync(x => x.JobId == jobId);

                ReturnPeriod period = null;
                if (job != null)
                {
                    period = await GetReturnPeriod(job.CollectionName, dateTimeJobSubmittedUtc);
                }

                var emailTemplate = await
                                    context.JobEmailTemplate.SingleOrDefaultAsync(
                    x => x.JobType == (short)jobType && x.JobStatus == (short)status && x.Active.Value);

                if (emailTemplate == null)
                {
                    return(string.Empty);
                }

                if (period != null)
                {
                    return(emailTemplate.TemplateOpenPeriod);
                }

                return(emailTemplate.TemplateClosePeriod ?? emailTemplate.TemplateOpenPeriod);
            }
        }
Example #5
0
        public override void ReadData(SerializedObject objSerializedObject)
        {
            base.ReadData(objSerializedObject);

            Name = objSerializedObject.Values.GetValue <string>("Name", string.Empty);

            _objTasks = objSerializedObject.Objects.GetObject <ITaskList>("Tasks", null);
            if (_objTasks == null)
            {
                _objTasks = new ITaskList();
            }

            Status = objSerializedObject.Values.GetValue <JobStatusType>("Status", JobStatusType.Queued);

            /// Create an ManualResetEvent for each of the job statuses that are currently
            /// defined.  We will use these to signal threads whenever a particular status
            /// has been set.
            ///
            _objWaitForStatusEvents = new Dictionary <JobStatusType, ManualResetEvent>();
            foreach (JobStatusType enuJobStatus in Enum.GetValues(typeof(JobStatusType)))
            {
                _objWaitForStatusEvents.Add(enuJobStatus, new ManualResetEvent(false));
            }

            _objStartThread = null;
            _objPauseEvent  = new ManualResetEvent(true);
        }
Example #6
0
        public ActionResult Post([FromRoute] long jobId, [FromRoute] JobStatusType status)
        {
            if (jobId == 0)
            {
                _logger.LogWarning("Job Post request received with empty data");
                return(BadRequest());
            }

            try
            {
                var job = _jobManager.GetJobById(jobId);
                if (job == null)
                {
                    _logger.LogError($"JobId {jobId} is not valid for job status update");
                    return(BadRequest("Invalid job Id"));
                }

                var result = _jobManager.UpdateCrossLoadingStatus(job.JobId, status);

                if (result)
                {
                    _logger.LogInfo($"Successfully updated cross loading job status for job Id: {jobId}");
                    return(Ok());
                }

                _logger.LogWarning($"Update cross loading status failed for job Id: {jobId}");
                return(BadRequest());
            }
            catch (Exception ex)
            {
                _logger.LogError($"Post for cross loading status post job failed for job: {jobId}", ex);

                return(BadRequest());
            }
        }
Example #7
0
        public override void ReadData(BinaryReaderExtension objBinaryReader)
        {
            base.ReadData(objBinaryReader);

            _strName   = objBinaryReader.ReadString();
            _enuStatus = (JobStatusType)objBinaryReader.ReadByte();
            _objTasks  = objBinaryReader.ReadTransportableObject <ITaskList>();
        }
Example #8
0
        public void Reset()
        {
            if (Status != JobStatusType.Completed)
            {
                throw new Exception("The job's status must equal 'Completed' prior to calling 'Reset'.");
            }

            Status = JobStatusType.Queued;
        }
Example #9
0
        public void WaitForStatus(JobStatusType enuJobStatus)
        {
            ManualResetEvent objManualResetEvent = _objWaitForStatusEvents[enuJobStatus];

            if (objManualResetEvent != null)
            {
                objManualResetEvent.WaitOne();
            }
        }
Example #10
0
        public async Task SendAsync(long jobId, JobStatusType jobStatusType, CancellationToken cancellationToken)
        {
            using (HttpClient client = new HttpClient())
            {
                string endPoint = $"{_endPointUrl}/{jobId}/{(int)jobStatusType}";
                _logger.LogDebug($"Calling status api at endpoint '{endPoint}'");
                HttpResponseMessage response = await client.PostAsync(endPoint, null, cancellationToken);

                response.EnsureSuccessStatusCode();
            }
        }
        public async Task <string> UpdateJobStatus(long jobId, JobStatusType status)
        {
            var job = new JobStatusDto()
            {
                JobId            = jobId,
                JobStatus        = (int)status,
                NumberOfLearners = 0
            };

            return(await httpClient.SendDataAsync("job/status", job));
        }
Example #12
0
        public override void Deserialize(GenericReader reader)
        {
            base.Deserialize(reader);
            int version = reader.ReadInt();

            //Version 0
            if (version >= 0)
            {
                m_Player    = reader.ReadMobile() as PlayerMobile;
                m_Job       = reader.ReadItem() as SocietyJob;
                m_JobStatus = (JobStatusType)reader.ReadInt();
            }
        }
Example #13
0
        public void Continue()
        {
            switch (Status)
            {
            case (JobStatusType.Paused):
                Status = JobStatusType.Running;
                _objPauseEvent.Set();
                break;

                //default:
                //    throw new Exception("The job's status must equal 'Paused' prior to calling 'Continue'.");
            }
        }
Example #14
0
 public void SetUp()
 {
     this.transactionScope        = new TransactionScope();
     this.jobRepository           = new JobRepository(ConfigurationManager.ConnectionStrings["BBOS"].ConnectionString);
     this.jobStatusTypeRepository = new JobStatusTypeRepository(ConfigurationManager.ConnectionStrings["BBOS"].ConnectionString);
     this.job               = BuildMeA.Job(DateTime.Now, DateTime.Now, DateTime.Now, "jwelkjwejwe", "grid");
     this.jobStatusType     = BuildMeA.JobStatusType("job status descrip");
     this.managementCompany = BuildMeA.ManagementCompany("manconame", "mancocode", "mancoshortname", "rufudbid");
     this.manCoDoc          = BuildMeA.ManCoDoc(2, 3, "Pub file name", "version", 2);
     this.parentCompany     = BuildMeA.ParentCompany("parent company name");
     this.managementCompany.ParentCompany = this.parentCompany;
     this.user     = BuildMeA.ApplicationUser("user");
     this.job.User = this.user;
 }
Example #15
0
        public void PostJob_UpdateJob_InvalidStatus_Failed_Test(JobStatusType status)
        {
            var job = new FileUploadJob()
            {
                JobId  = 100,
                Status = status,
                Ukprn  = 1000,
            };

            var controller = GetController();

            var result = controller.Post(job);

            result.Should().BeAssignableTo <BadRequestObjectResult>();
            ((BadRequestObjectResult)result).StatusCode.Should().Be(400);
        }
Example #16
0
        public void Pause()
        {
            switch (Status)
            {
            case (JobStatusType.Running):
            case (JobStatusType.Pausing):
                Status = JobStatusType.Pausing;
                _objPauseEvent.Reset();
                break;

                //case(JobStatusType.Paused):
                //    break;

                //default:
                //    throw new Exception("The job's status must equal 'Running' prior to calling 'Pause'.");
            }
        }
Example #17
0
        public void Stop()
        {
            switch (Status)
            {
            case (JobStatusType.Running):
            case (JobStatusType.Paused):
                _objPauseEvent.Set();
                Status = JobStatusType.Stopping;
                break;

            case (JobStatusType.Stopping):
            case (JobStatusType.Completed):
                break;

                //default:
                //    throw new Exception("The job's status must equal 'Running' or 'Paused' prior to calling 'Stop'.");
            }
        }
Example #18
0
        public void SetUp()
        {
            this.transactionScope          = new TransactionScope();
            this.applicationUserRepository = new ApplicationUserRepository(ConfigurationManager.ConnectionStrings["BBOS"].ConnectionString);
            this.jobStatusRepository       = new JobStatusRepository(ConfigurationManager.ConnectionStrings["BBOS"].ConnectionString);
            this.jobRepository             = new JobRepository(ConfigurationManager.ConnectionStrings["BBOS"].ConnectionString);
            this.jobStatusTypeRepository   = new JobStatusTypeRepository(ConfigurationManager.ConnectionStrings["BBOS"].ConnectionString);

            this.user = BuildMeA.ApplicationUser("UserName");
            this.applicationUserRepository.Create(user);
            this.job            = BuildMeA.Job(DateTime.Now, DateTime.Now, DateTime.Now, String.Empty, "dfsdfjdf");
            this.job.ManCoDocID = 10;
            this.job.UserID     = this.user.Id;
            this.jobRepository.Create(this.job);

            this.jobStatusType = BuildMeA.JobStatusType("descrip");
            this.jobStatusTypeRepository.Create(this.jobStatusType);

            this.jobStatus       = BuildMeA.JobStatus(DateTime.Now).WithJobStatusType(this.jobStatusType);
            this.jobStatus.JobID = this.job.JobID;
        }
        public async Task TestRemove(int age, int updateTimeBack, JobStatusType status, int expected)
        {
            DateTime utcNow = DateTime.UtcNow;
            Mock <IDateTimeProvider> dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(x => x.GetNowUtc()).Returns(utcNow);

            using (var connection = new SqliteConnection("DataSource=:memory:"))
            {
                connection.Open();
                var options = new DbContextOptionsBuilder <JobQueueDataContext>()
                              .UseSqlite(connection)
                              .Options;

                // Create the schema in the database
                using (var context = new JobQueueDataContext(options))
                {
                    context.Database.EnsureCreated();
                    context.Jobs.Add(new JobEntity
                    {
                        JobId = 1,
                        DateTimeUpdatedUtc   = utcNow.AddMinutes(updateTimeBack),
                        CrossLoadingStatus   = (short)status,
                        DateTimeSubmittedUtc = utcNow.AddMinutes(updateTimeBack + -1),
                        JobType     = (short)JobType.IlrSubmission,
                        NotifyEmail = "*****@*****.**",
                        Priority    = 1,
                        Status      = (short)JobStatusType.Completed,
                        RowVersion  = Encoding.UTF8.GetBytes("RowVersion"),
                        SubmittedBy = "Tester"
                    });
                    await context.SaveChangesAsync();

                    ICrossLoadActiveJobService crossLoadActiveJobService =
                        new CrossLoadActiveJobService(options, dateTimeProvider.Object, age);
                    var results = crossLoadActiveJobService.GetStuckJobs();
                    results.Should().HaveCount(expected);
                }
            }
        }
Example #20
0
        protected bool HasBeenCancelled()
        {
            bool blnHasBeenCancelled = false;

            if (Status == JobStatusType.Pausing)
            {
                Status = JobStatusType.Paused;
                _objPauseEvent.WaitOne();
            }

            switch (Status)
            {
            case (JobStatusType.Running):
                blnHasBeenCancelled = false;
                break;

            case (JobStatusType.Stopping):
                blnHasBeenCancelled = true;
                break;
            }

            return(blnHasBeenCancelled);
        }
Example #21
0
        public static Job UpdateJobStatus(UserInfo userInfo, string agentId, string jobId, JobStatusType status, JobErrorViewModel errorModel = null, int count = 0)
        {
            var jobsApi = GetApiInstance(userInfo.Token, userInfo.ServerUrl);

            try
            {
                return(jobsApi.ApiVapiVersionJobsIdStatusStatusPutWithHttpInfo(agentId, jobId, status, userInfo.ApiVersion, userInfo.OrganizationId, errorModel).Data);
            }
            catch (Exception ex)
            {
                if (ex.GetType().GetProperty("ErrorCode").GetValue(ex, null).ToString() == "401" && count < 2)
                {
                    UtilityMethods.RefreshToken(userInfo);
                    count++;
                    return(UpdateJobStatus(userInfo, agentId, jobId, status, errorModel, count));
                }
                else if (ex.Message != "One or more errors occurred.")
                {
                    throw new InvalidOperationException("Exception when calling JobsApi.UpdateJobStatus: " + ex.Message);
                }
                else
                {
                    throw new InvalidOperationException(ex.InnerException.Message);
                }
            }
        }
Example #22
0
 public JobStatusBuilder WithJobStatusType(JobStatusType jobStatusType)
 {
     Instance.JobStatusType = jobStatusType;
     return(this);
 }
Example #23
0
        public static ApiResponse <Job> UpdateJobStatus(AuthAPIManager apiManager, string agentId, string jobId, JobStatusType status, JobErrorViewModel errorModel = null)
        {
            JobsApi jobsApi = new JobsApi(apiManager.Configuration);

            try
            {
                return(jobsApi.ApiV1JobsIdStatusStatusPutWithHttpInfo(agentId, jobId, status, errorModel));
            }
            catch (Exception ex)
            {
                // In case of Unauthorized request
                if (ex.GetType().GetProperty("ErrorCode").GetValue(ex, null).ToString() == "401")
                {
                    // Refresh Token and Call API
                    jobsApi.Configuration.AccessToken = apiManager.GetToken();
                    return(jobsApi.ApiV1JobsIdStatusStatusPutWithHttpInfo(agentId, jobId, status, errorModel));
                }
                throw ex;
            }
        }
        public async Task <IActionResult> ChangeStatus(string id, JobStatusType status, [BindRequired, FromQuery] string agentId, [FromBody] JobErrorViewModel jobErrors)
        {
            try
            {
                if (id == null)
                {
                    ModelState.AddModelError("ChangeStatus", "No Job ID was passed");
                    return(BadRequest(ModelState));
                }

                bool isValid = Guid.TryParse(id, out Guid agentGuid);
                if (!isValid)
                {
                    ModelState.AddModelError("ChangeStatus", "Job ID is not a valid GUID ");
                    return(BadRequest(ModelState));
                }
                if (status == null)
                {
                    ModelState.AddModelError("ChangeStatus", "No status was provided");
                    return(BadRequest(ModelState));
                }

                Guid entityId = new Guid(id);

                var existingJob = repository.GetOne(entityId);
                if (existingJob == null)
                {
                    return(NotFound("Unable to find a Job for the specified ID"));
                }

                if (existingJob.AgentId.ToString() != agentId)
                {
                    return(UnprocessableEntity("The provided Agent ID does not match the Job's Agent ID"));
                }

                switch (status)
                {
                case JobStatusType.Completed:
                    existingJob.IsSuccessful = true;
                    break;

                case JobStatusType.Failed:
                    existingJob.IsSuccessful = false;
                    break;
                }

                existingJob.JobStatus             = status;
                existingJob.ErrorReason           = string.IsNullOrEmpty(jobErrors.ErrorReason) ? existingJob.ErrorReason : jobErrors.ErrorReason;
                existingJob.ErrorCode             = string.IsNullOrEmpty(jobErrors.ErrorCode) ? existingJob.ErrorCode : jobErrors.ErrorReason;
                existingJob.SerializedErrorString = string.IsNullOrEmpty(jobErrors.SerializedErrorString) ? existingJob.SerializedErrorString : jobErrors.ErrorReason;

                var response = await base.PutEntity(id, existingJob);

                //send SignalR notification to all connected clients
                await _hub.Clients.All.SendAsync("sendjobnotification", string.Format("Job id {0} updated.", existingJob.Id));

                await webhookPublisher.PublishAsync("Jobs.JobUpdated", existingJob.Id.ToString()).ConfigureAwait(false);

                return(response);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Job", ex.Message);
                return(BadRequest(ModelState));
            }
        }
Example #25
0
        public override void OnSingleClick(Mobile from)
        {
            PlayerMobile player = from as PlayerMobile;

            if (player == null)
            {
                return;
            }

            if (m_Job == null)
            {
                LabelTo(from, "an expired society job contract.");
                return;
            }

            if (m_Job.Deleted)
            {
                LabelTo(from, "an expired society job contract.");
                return;
            }

            if (m_Player == null)
            {
                LabelTo(from, "an expired society job contract.");
                return;
            }

            bool accountHasCompleted = m_Job.AccountHasCompleted(player);

            if (accountHasCompleted && m_JobStatus != JobStatusType.Completed)
            {
                m_JobStatus = JobStatusType.Completed;
            }

            else if (m_Job.m_Expiration <= DateTime.UtcNow && m_JobStatus != JobStatusType.Expired)
            {
                m_JobStatus = JobStatusType.Expired;
            }

            string jobText        = "Job Contract: " + m_Job.GetJobDescriptionProgressText(m_Player);
            string ownerText      = "(Accepted by " + m_Player.RawName + ")";
            string expirationText = "[Expires in " + Utility.CreateTimeRemainingString(DateTime.UtcNow, m_Job.m_Expiration, true, true, true, true, false) + "]";

            switch (m_JobStatus)
            {
            case JobStatusType.None:
                LabelTo(from, jobText);
                LabelTo(from, ownerText);
                LabelTo(from, expirationText);
                break;

            case JobStatusType.Ready:
                LabelTo(from, jobText);
                LabelTo(from, ownerText);
                LabelTo(from, expirationText);
                break;

            case JobStatusType.Completed:
                ownerText = "(Completed by Account)";

                LabelTo(from, jobText);
                LabelTo(from, ownerText);
                break;

            case JobStatusType.Expired:
                LabelTo(from, "an expired society job contract.");
                break;
            }
        }
Example #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CreateJobViewModel" /> class.
 /// </summary>
 /// <param name="id">id.</param>
 /// <param name="agentId">agentId (required).</param>
 /// <param name="startTime">startTime.</param>
 /// <param name="endTime">endTime.</param>
 /// <param name="enqueueTime">enqueueTime.</param>
 /// <param name="dequeueTime">dequeueTime.</param>
 /// <param name="automationId">automationId (required).</param>
 /// <param name="jobStatus">jobStatus.</param>
 /// <param name="message">message.</param>
 /// <param name="isSuccessful">isSuccessful.</param>
 /// <param name="jobParameters">jobParameters.</param>
 public CreateJobViewModel(Guid?id = default(Guid?), Guid?agentId = default(Guid?), DateTime?startTime = default(DateTime?), DateTime?endTime = default(DateTime?), DateTime?enqueueTime = default(DateTime?), DateTime?dequeueTime = default(DateTime?), Guid?automationId = default(Guid?), JobStatusType jobStatus = default(JobStatusType), string message = default(string), bool?isSuccessful = default(bool?), List <JobParameter> jobParameters = default(List <JobParameter>))
 {
     // to ensure "agentId" is required (not null)
     if (agentId == null)
     {
         throw new InvalidDataException("agentId is a required property for CreateJobViewModel and cannot be null");
     }
     else
     {
         this.AgentId = agentId;
     }
     // to ensure "automationId" is required (not null)
     if (automationId == null)
     {
         throw new InvalidDataException("automationId is a required property for CreateJobViewModel and cannot be null");
     }
     else
     {
         this.AutomationId = automationId;
     }
     this.Id            = id;
     this.StartTime     = startTime;
     this.EndTime       = endTime;
     this.EnqueueTime   = enqueueTime;
     this.DequeueTime   = dequeueTime;
     this.JobStatus     = jobStatus;
     this.Message       = message;
     this.IsSuccessful  = isSuccessful;
     this.JobParameters = jobParameters;
 }
Example #27
0
        public static Job UpdateJobStatus(UserInfo userInfo, string agentId, string jobId, JobStatusType status, JobErrorViewModel errorModel = null)
        {
            var jobsApi = GetApiInstance(userInfo.Token, userInfo.ServerUrl);

            try
            {
                return(jobsApi.ApiVapiVersionJobsIdStatusStatusPutWithHttpInfo(agentId, jobId, status, userInfo.ApiVersion, userInfo.OrganizationId, errorModel).Data);
            }
            catch (Exception ex)
            {
                if (ex.Message != "One or more errors occurred.")
                {
                    throw new InvalidOperationException("Exception when calling JobsApi.UpdateJobStatus: " + ex.Message);
                }
                else
                {
                    throw new InvalidOperationException(ex.InnerException.Message);
                }
            }
        }
Example #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Job" /> class.
 /// </summary>
 /// <param name="id">id.</param>
 /// <param name="isDeleted">isDeleted (default to false).</param>
 /// <param name="createdBy">createdBy.</param>
 /// <param name="createdOn">createdOn.</param>
 /// <param name="deletedBy">deletedBy.</param>
 /// <param name="deleteOn">deleteOn.</param>
 /// <param name="timestamp">timestamp.</param>
 /// <param name="updatedOn">updatedOn.</param>
 /// <param name="updatedBy">updatedBy.</param>
 /// <param name="agentId">agentId.</param>
 /// <param name="agentGroupId">agentGroupId.</param>
 /// <param name="startTime">startTime.</param>
 /// <param name="endTime">endTime.</param>
 /// <param name="executionTimeInMinutes">executionTimeInMinutes.</param>
 /// <param name="enqueueTime">enqueueTime.</param>
 /// <param name="dequeueTime">dequeueTime.</param>
 /// <param name="automationId">automationId (required).</param>
 /// <param name="automationVersion">automationVersion (required).</param>
 /// <param name="automationVersionId">automationVersionId (required).</param>
 /// <param name="jobStatus">jobStatus.</param>
 /// <param name="message">message.</param>
 /// <param name="isSuccessful">isSuccessful.</param>
 /// <param name="errorReason">errorReason.</param>
 /// <param name="errorCode">errorCode.</param>
 /// <param name="serializedErrorString">serializedErrorString.</param>
 public Job(Guid?id = default(Guid?), bool?isDeleted = false, string createdBy = default(string), DateTime?createdOn = default(DateTime?), string deletedBy = default(string), DateTime?deleteOn = default(DateTime?), byte[] timestamp = default(byte[]), DateTime?updatedOn = default(DateTime?), string updatedBy = default(string), Guid?scheduleId = default(Guid?), Guid?agentId = default(Guid?), Guid?agentGroupId = default(Guid?), DateTime?startTime = default(DateTime?), DateTime?endTime = default(DateTime?), int?startDay = default(int?), int?endDay = default(int?), double?executionTimeInMinutes = default(double?), DateTime?enqueueTime = default(DateTime?), DateTime?dequeueTime = default(DateTime?), Guid?automationId = default(Guid?), int?automationVersion = default(int?), Guid?automationVersionId = default(Guid?), JobStatusType jobStatus = default(JobStatusType), string message = default(string), bool?isSuccessful = default(bool?), string errorReason = default(string), string errorCode = default(string), string serializedErrorString = default(string), int automationLogCount = default(int), int automationExecutionLogCount = default(int))
 {
     // to ensure "automationId" is required (not null)
     if (automationId == null)
     {
         throw new InvalidDataException("automationId is a required property for Job and cannot be null");
     }
     else
     {
         this.AutomationId = automationId;
     }
     // to ensure "automationVersion" is required (not null)
     if (automationVersion == null)
     {
         throw new InvalidDataException("automationVersion is a required property for Job and cannot be null");
     }
     else
     {
         this.AutomationVersion = automationVersion;
     }
     // to ensure "automationVersionId" is required (not null)
     if (automationVersionId == null)
     {
         throw new InvalidDataException("automationVersionId is a required property for Job and cannot be null");
     }
     else
     {
         this.AutomationVersionId = automationVersionId;
     }
     this.Id = id;
     // use default value if no "isDeleted" provided
     if (isDeleted == null)
     {
         this.IsDeleted = false;
     }
     else
     {
         this.IsDeleted = isDeleted;
     }
     this.CreatedBy                   = createdBy;
     this.CreatedOn                   = createdOn;
     this.DeletedBy                   = deletedBy;
     this.DeleteOn                    = deleteOn;
     this.Timestamp                   = timestamp;
     this.UpdatedOn                   = updatedOn;
     this.UpdatedBy                   = updatedBy;
     this.ScheduleId                  = scheduleId;
     this.AgentId                     = agentId;
     this.AgentGroupId                = agentGroupId;
     this.StartTime                   = startTime;
     this.EndTime                     = endTime;
     this.StartDay                    = startDay;
     this.EndDay                      = endDay;
     this.ExecutionTimeInMinutes      = executionTimeInMinutes;
     this.EnqueueTime                 = enqueueTime;
     this.DequeueTime                 = dequeueTime;
     this.JobStatus                   = jobStatus;
     this.Message                     = message;
     this.IsSuccessful                = isSuccessful;
     this.ErrorReason                 = errorReason;
     this.ErrorCode                   = errorCode;
     this.SerializedErrorString       = serializedErrorString;
     this.AutomationLogCount          = automationLogCount;
     this.AutomationExecutionLogCount = automationExecutionLogCount;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="JobViewModel" /> class.
 /// </summary>
 /// <param name="id">id.</param>
 /// <param name="agentName">agentName.</param>
 /// <param name="automationName">automationName.</param>
 /// <param name="agentId">agentId (required).</param>
 /// <param name="startTime">startTime.</param>
 /// <param name="endTime">endTime.</param>
 /// <param name="enqueueTime">enqueueTime.</param>
 /// <param name="dequeueTime">dequeueTime.</param>
 /// <param name="automationId">automationId (required).</param>
 /// <param name="automationVersion">automationVersion (required).</param>
 /// <param name="automationVersionId">automationVersionId (required).</param>
 /// <param name="jobStatus">jobStatus.</param>
 /// <param name="message">message.</param>
 /// <param name="isSuccessful">isSuccessful.</param>
 /// <param name="createdOn">createdOn.</param>
 /// <param name="createdBy">createdBy.</param>
 /// <param name="errorReason">errorReason.</param>
 /// <param name="errorCode">errorCode.</param>
 /// <param name="serializedErrorString">serializedErrorString.</param>
 /// <param name="jobParameters">jobParameters.</param>
 public JobViewModel(Guid?id = default(Guid?), string agentName = default(string), string automationName = default(string), Guid?agentId = default(Guid?), DateTime?startTime = default(DateTime?), DateTime?endTime = default(DateTime?), DateTime?enqueueTime = default(DateTime?), DateTime?dequeueTime = default(DateTime?), Guid?automationId = default(Guid?), int?automationVersion = default(int?), Guid?automationVersionId = default(Guid?), JobStatusType jobStatus = default(JobStatusType), string message = default(string), bool?isSuccessful = default(bool?), DateTime?createdOn = default(DateTime?), string createdBy = default(string), string errorReason = default(string), string errorCode = default(string), string serializedErrorString = default(string), List <JobParameter> jobParameters = default(List <JobParameter>))
 {
     // to ensure "agentId" is required (not null)
     if (agentId == null)
     {
         throw new InvalidDataException("agentId is a required property for JobViewModel and cannot be null");
     }
     else
     {
         this.AgentId = agentId;
     }
     // to ensure "automationId" is required (not null)
     if (automationId == null)
     {
         throw new InvalidDataException("automationId is a required property for JobViewModel and cannot be null");
     }
     else
     {
         this.AutomationId = automationId;
     }
     // to ensure "automationVersion" is required (not null)
     if (automationVersion == null)
     {
         throw new InvalidDataException("automationVersion is a required property for JobViewModel and cannot be null");
     }
     else
     {
         this.AutomationVersion = automationVersion;
     }
     // to ensure "automationVersionId" is required (not null)
     if (automationVersionId == null)
     {
         throw new InvalidDataException("automationVersionId is a required property for JobViewModel and cannot be null");
     }
     else
     {
         this.AutomationVersionId = automationVersionId;
     }
     this.Id                    = id;
     this.AgentName             = agentName;
     this.AutomationName        = automationName;
     this.StartTime             = startTime;
     this.EndTime               = endTime;
     this.EnqueueTime           = enqueueTime;
     this.DequeueTime           = dequeueTime;
     this.JobStatus             = jobStatus;
     this.Message               = message;
     this.IsSuccessful          = isSuccessful;
     this.CreatedOn             = createdOn;
     this.CreatedBy             = createdBy;
     this.ErrorReason           = errorReason;
     this.ErrorCode             = errorCode;
     this.SerializedErrorString = serializedErrorString;
     this.JobParameters         = jobParameters;
 }
Example #30
0
        private void StartThread()
        {
            DateTime       dtJobStartTime = DateTime.Now;
            TaskResultList objTaskResults = new TaskResultList();

            Status = JobStatusType.Running;
            OnJobBegin();

            JobResultType enuJobResult = JobResultType.Completed;

            int  intTaskIndex        = 0;
            int  intTaskCount        = _objTasks.Count;
            bool blnHasBeenCancelled = false;

            while (intTaskIndex < intTaskCount)
            {
                ITask objTask = _objTasks[intTaskIndex];

                blnHasBeenCancelled = HasBeenCancelled();
                if (blnHasBeenCancelled == true)
                {
                    enuJobResult = JobResultType.Cancelled;
                    break;
                }

                DateTime    dtTaskStartTime = DateTime.Now;
                JobTicket   objJobTicket    = new JobTicket(dtTaskStartTime, HasBeenCancelled, TaskProgressChanged);
                ITaskResult objTaskResult   = null;

                try
                {
                    OnTaskBegin(objTask, intTaskIndex, intTaskCount);
                    objTaskResult = objTask.Execute(objJobTicket);
                }
                catch (Exception objException)
                {
                    string    strErrorMessage = objException.ToString();
                    TaskStats objTaskStats    = new TaskStats(objTask, dtTaskStartTime, DateTime.Now);
                    objTaskResult = new TaskResult(objTask, objTaskStats, TaskResultType.Failed, strErrorMessage);
                }

                if (objTaskResult == null)
                {
                    string    strErrorMessage = "A null value was returned by the task.";
                    TaskStats objTaskStats    = new TaskStats(objTask, dtTaskStartTime, DateTime.Now);
                    objTaskResult = new TaskResult(objTask, objTaskStats, TaskResultType.Failed, strErrorMessage);
                }

                blnHasBeenCancelled = HasBeenCancelled();
                if (blnHasBeenCancelled == true)
                {
                    objTaskResults.Add(objTaskResult);
                    break;
                }
                else
                {
                    TaskActionType enuTaskActionType = OnTaskEnd(objTaskResult, intTaskIndex);
                    if (enuTaskActionType == TaskActionType.Retry)
                    {
                        continue;
                    }
                    else if (enuTaskActionType == TaskActionType.Continue)
                    {
                        objTaskResults.Add(objTaskResult);
                        intTaskIndex++;

                        if (objTaskResult.Result == TaskResultType.RebootRequired)
                        {
                            enuJobResult = JobResultType.RebootRequired;
                            break;
                        }

                        continue;
                    }
                    else if (enuTaskActionType == TaskActionType.Cancel)
                    {
                        objTaskResults.Add(objTaskResult);
                        enuJobResult = JobResultType.Cancelled;
                        break;
                    }
                }
            }

            if (blnHasBeenCancelled == true)
            {
                for (int intRemainingTaskIndex = intTaskIndex + 1; intRemainingTaskIndex < intTaskCount; intRemainingTaskIndex++)
                {
                    ITask       objRemainingTask       = _objTasks[intRemainingTaskIndex];
                    TaskStats   objTaskStats           = new TaskStats(objRemainingTask, dtJobStartTime, DateTime.Now);
                    ITaskResult objRemainingTaskResult = new TaskResult(objRemainingTask, objTaskStats, TaskResultType.Cancelled);

                    objTaskResults.Add(objRemainingTaskResult);
                }
            }

            Thread.Sleep(200);

            JobResult objJobResult = new JobResult(this, enuJobResult, dtJobStartTime, DateTime.Now, new TaskResultList(objTaskResults));

            OnJobEnd(objJobResult);

            Thread.Sleep(200);

            Status = JobStatusType.Completed;
        }