Example #1
0
        public async Task<Job> PostJob(JobModel model)
        {
            var task = Task.Run(() =>
            {
                var job = new Job();
                job.Tasks = model.Tasks;
                job.Name = model.Name;
                return job;
            });

            return await task;
        }
Example #2
0
 public async Task<IHttpActionResult> Post(JobModel model)
 {
     try
     {
         Job job = await _repository.PostJob(model);
         return Json(job);
     }
     catch (Exception)
     {
         return InternalServerError();
     }
 }
Example #3
0
        /// <summary>
        ///		Carga los datos de un trabajo
        /// </summary>
        internal JobModel Load(string fileName)
        {
            JobModel job = new JobModel();

            // Carga los datos del archivo
            if (System.IO.File.Exists(fileName))
            {
                MLFile fileML = new LibMarkupLanguage.Services.XML.XMLParser().Load(fileName);

                if (fileML != null)
                {
                    foreach (MLNode rootML in fileML.Nodes)
                    {
                        if (rootML.Name == TagRoot)
                        {
                            // Carga los parámetros básicos
                            job.Name        = rootML.Nodes[TagName].Value;
                            job.Description = rootML.Nodes[TagDescription].Value;
                            // Carga el resto de parámetros
                            foreach (MLNode nodeML in rootML.Nodes)
                            {
                                switch (nodeML.Name)
                                {
                                case TagBlock:
                                    job.Steps.Add(LoadBlock(job, nodeML));
                                    break;

                                case TagStep:
                                    job.Steps.Add(LoadStep(job, nodeML));
                                    break;

                                case TagParameter:
                                    LoadParameter(nodeML, job.Parameters);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            // Devuelve los datos del trabajo
            return(job);
        }
        public void EditJob(string Id, JobModel model)
        {
            int id      = int.Parse(Id);
            var headers = OperationContext.Current.IncomingMessageProperties["httpRequest"];
            var token   = ((HttpRequestMessageProperty)headers).Headers["Token"];

            using (var dbContext = new TokenDbContext())
            {
                ITokenValidator validator = new DatabaseTokenValidator(dbContext);
                if (validator.IsValid(token) == true)
                {
                    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString("GyrodataTracker")))
                    {
                        var p = new DynamicParameters();

                        p.Add("@Id", id);
                        p.Add("@JobNumber", model.JobNumber);
                        p.Add("@Client", model.ClientName);
                        p.Add("@gdp", model.GDP);
                        p.Add("@modem", model.Modem);
                        p.Add("@ModemVersion", model.ModemVersion);
                        p.Add("@bbp", model.Bullplug);
                        p.Add("@newJobCirculation", model.CirculationHours);
                        p.Add("@Battery", model.Battery);
                        p.Add("@MaxTemp", model.MaxTemp);
                        p.Add("@EngineerOne", model.EngineerOne);
                        p.Add("@EngineerTwo", model.EngineerTwo);
                        p.Add("@EngineerOneArrived", model.eng_one_arrived);
                        p.Add("@EngineerTwoArrived", model.eng_two_arrived);
                        p.Add("@EngineerOneLeft", model.eng_one_left);
                        p.Add("@EngineerTwoLeft", model.eng_two_left);
                        p.Add("@Container", model.Container);
                        p.Add("@ContainerArrived", model.ContainerArrived);
                        p.Add("@ContainerLeft", model.ContainerLeft);
                        p.Add("@Rig", model.Rig);
                        p.Add("@Issues", model.Issues);
                        p.Add("@Comment", model.Comment);

                        connection.Execute("dbo.spUpdate_Job", p, commandType: CommandType.StoredProcedure);
                    }
                }
            }
        }
        public ActionResult Create([Bind(Include = "ID,BuyerID,SellerID,BankID,EstateAgentID,SolicitorID")] JobModel jobModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.JobModels.Add(jobModel);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                ModelState.AddModelError("", "Unable to save changes.");
            }

            return(View(jobModel));
        }
        /// <summary>
        /// Fill in individual device responses
        /// </summary>
        /// <param name="job"></param>
        /// <returns></returns>
        private async Task <JobModel> QueryDevicesInfoAsync(JobModel job)
        {
            var    query        = $"SELECT * FROM devices.jobs WHERE devices.jobs.jobId = '{job.JobId}'";
            var    statement    = _registry.CreateQuery(query);
            string continuation = null;
            var    devices      = new List <DeviceJobModel>();

            do
            {
                var response = await statement.GetNextAsDeviceJobAsync(new QueryOptions {
                    ContinuationToken = continuation
                });

                devices.AddRange(response.Select(j => j.ToModel()));
                continuation = response.ContinuationToken;
            }while (!string.IsNullOrEmpty(continuation));
            job.Devices = devices;
            return(job);
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            DataTable dtCompanyDetails = new DataTable();

            PurchaseOrder             objPurchaseOrder = objDataAccess.GetPurchaseOrderById(Convert.ToInt32(ReportId));
            List <JobPOMaterialModel> lJobMaterials    = objDataAccess.GetJobPOMaterials(objPurchaseOrder.JobId, objPurchaseOrder.Id);
            JobPOModel objJobPOModel = objDataAccess.GetJobPODetails(objPurchaseOrder.Id);
            JobModel   objJobDetails = objDataAccess.GetJobDetails(objPurchaseOrder.JobId);

            if (objJobDetails.BranchId != null)
            {
                dtCompanyDetails = CompanyDetails(Convert.ToInt32(objJobDetails.BranchId));
            }

            DataTable dtToDetails      = GetVendorDetails(objPurchaseOrder);
            DataTable dtReportContents = ReportContents(lJobMaterials);

            decimal?  dTotalValue;
            DataTable dtTermsConditions = Terms_ConditionsContent(objJobPOModel, out dTotalValue);
            DataTable dtTotal           = new DataTable();

            dtTotal.Columns.Add("TotalValue", typeof(decimal));

            DataRow drTotalRow = dtTotal.NewRow();

            drTotalRow["TotalValue"] = Convert.ToDecimal(dTotalValue);
            dtTotal.Rows.Add(drTotalRow);

            ReportDataSource rhCompanyDetailsDataSource = new ReportDataSource("rhCompanyDetails", dtCompanyDetails);
            ReportDataSource rhToDetailsDataSource      = new ReportDataSource("rhToDetail", dtToDetails);
            ReportDataSource rhReportContentsDataSource = new ReportDataSource("rhContents", dtReportContents);
            ReportDataSource rhReportTermsConditions    = new ReportDataSource("rhTerms_Conditions", dtTermsConditions);
            ReportDataSource rh_Total = new ReportDataSource("rh_Total", dtTotal);

            reportViewer.LocalReport.ReportPath = "PurchaseOrderReport.rdlc";
            reportViewer.LocalReport.DataSources.Add(rhCompanyDetailsDataSource);
            reportViewer.LocalReport.DataSources.Add(rhToDetailsDataSource);
            reportViewer.LocalReport.DataSources.Add(rhReportContentsDataSource);
            reportViewer.LocalReport.DataSources.Add(rhReportTermsConditions);
            reportViewer.LocalReport.DataSources.Add(rh_Total);
            reportViewer.RefreshReport();
        }
        private void BindScheduler(SchedulerModel scheduler, Process process)
        {
            scheduler.Process = process;
            NameValueCollection properties = new NameValueCollection();

            properties["quartz.scheduler.proxy"]         = "true";
            properties["quartz.scheduler.proxy.address"] = string.Format("tcp://localhost:{0}/QuartzScheduler", scheduler.Port);
            ISchedulerFactory factory = new StdSchedulerFactory(properties);

            try
            {
                if (SchedulerRepository.Instance.Lookup(scheduler.SchedulerName) == null)
                {
                    scheduler.Scheduler = factory.GetScheduler();
                }
                else
                {
                    scheduler.Scheduler = factory.GetScheduler(scheduler.SchedulerName);
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }

            scheduler.Jobs = new List <JobModel>();
            var groups = scheduler.Scheduler.GetJobGroupNames();

            foreach (var group in groups)
            {
                var jobkeys = scheduler.Scheduler.GetJobKeys(Quartz.Impl.Matchers.GroupMatcher <JobKey> .GroupContains(group));
                foreach (var key in jobkeys)
                {
                    var job = new JobModel()
                    {
                        GroupName = key.Group, JobName = key.Name
                    };
                    scheduler.Jobs.Add(job);
                    BindJobStatus(scheduler.Scheduler, job);
                }
            }
        }
        public void SetUp()
        {
            inProgressMessages        = new List <InProgressMessage>();
            completedMessages         = new List <CompletedMessage>();
            outstandingOrTimedOutJobs = new List <OutstandingJobResult>();
            mocker = AutoMock.GetLoose();

            job = new JobModel
            {
                Id                = 1,
                DcJobId           = 99,
                StartTime         = DateTimeOffset.UtcNow.AddSeconds(-1),
                Status            = JobStatus.InProgress,
                LearnerCount      = null,
                JobType           = JobType.PeriodEndStartJob,
                DcJobEndTime      = DateTimeOffset.Now,
                DcJobSucceeded    = true,
                IlrSubmissionTime = DateTime.Now,
                Ukprn             = 1234,
                AcademicYear      = 1920,
                CollectionPeriod  = 01
            };
            mocker.Mock <IJobStorageService>()
            .Setup(x => x.GetJob(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(job);
            mocker.Mock <IJobStorageService>()
            .Setup(x => x.GetInProgressMessages(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(inProgressMessages);
            mocker.Mock <IJobStorageService>()
            .Setup(x => x.GetCompletedMessages(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(completedMessages);
            mocker.Mock <IJobStorageService>()
            .Setup(x => x.GetJobStatus(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((hasFailedMessages: false, endTime: null));
            mocker.Mock <IJobServiceConfiguration>()
            .SetupGet(cfg => cfg.EarningsJobTimeout)
            .Returns(TimeSpan.FromSeconds(20));

            mocker.Mock <IJobsDataContext>()
            .Setup(x => x.GetOutstandingOrTimedOutJobs(It.IsAny <long>(), It.IsAny <DateTimeOffset>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(outstandingOrTimedOutJobs);
        }
Example #10
0
        public void SetUp()
        {
            inProgressMessages = new List <InProgressMessage>();
            completedMessages  = new List <CompletedMessage>();
            stepsStatuses      = new Dictionary <JobStepStatus, int>()
            {
                { JobStepStatus.Completed, 10 }
            };
            mocker             = AutoMock.GetLoose();
            lastJobStepEndTime = DateTimeOffset.UtcNow;

            job = new JobModel
            {
                Id                = 1,
                DcJobId           = 99,
                StartTime         = DateTimeOffset.UtcNow.AddSeconds(-10),
                Status            = JobStatus.InProgress,
                LearnerCount      = 100,
                JobType           = JobType.EarningsJob,
                DcJobEndTime      = DateTimeOffset.Now,
                DcJobSucceeded    = true,
                IlrSubmissionTime = DateTime.Now,
                Ukprn             = 1234,
                AcademicYear      = 1920,
                CollectionPeriod  = 01
            };
            mocker.Mock <IJobStorageService>()
            .Setup(x => x.GetJob(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(job);
            mocker.Mock <IJobStorageService>()
            .Setup(x => x.GetInProgressMessages(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(inProgressMessages);
            mocker.Mock <IJobStorageService>()
            .Setup(x => x.GetCompletedMessages(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(completedMessages);
            mocker.Mock <IJobStorageService>()
            .Setup(x => x.GetJobStatus(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((hasFailedMessages: false, endTime: null));
            mocker.Mock <IJobServiceConfiguration>()
            .SetupGet(cfg => cfg.EarningsJobTimeout)
            .Returns(TimeSpan.FromSeconds(20));
        }
Example #11
0
        public async Task <IActionResult> Get(string id)
        {
            try
            {
                JobModel model = await _jobService.Find(id);

                if (model == null)
                {
                    return(StatusCode(404));
                }

                return(Ok(model));
            }
            catch (Exception ex)
            {
                HandleError(ex);

                return(StatusCode(500, id));
            }
        }
Example #12
0
        public async Task <IActionResult> Create([Bind("Id,JobTitle,Language,CompanyId,AppStatusId,ContactId,Notes")] JobModel jobModel)
        {
            ModelState.Remove("User");

            if (ModelState.IsValid)
            {
                ApplicationUser user = await GetCurrentUserAsync();

                jobModel.User = user;
                _context.Add(jobModel);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            ViewData["AppStatusId"] = new SelectList(_context.AppStatusModel, "Id", "AppStatusTitle", jobModel.AppStatusId);
            ViewData["CompanyId"]   = new SelectList(_context.CompanyModel, "Id", "WebsiteUrl", jobModel.CompanyId);
            ViewData["ContactId"]   = new SelectList(_context.ContactModel, "Id", "Email", jobModel.ContactId);
            return(View(jobModel));
        }
        private IEnumerable <JobModel> RunningJobs(IEnumerable <Job> runningJobs)
        {
            List <JobModel> jobs = new List <JobModel>();

            if (runningJobs != null)
            {
                JobModel jobModel = new JobModel();
                foreach (Job job in runningJobs)
                {
                    jobModel.Title     = job.Name;
                    jobModel.Priority  = job.Options.Priority.ToString();
                    jobModel.Status    = job.Status.ToString();
                    jobModel.Progress  = job.Status.Processed.ToString();
                    jobModel.QueueTime = job.QueueTime.ToString();
                    jobs.Add(jobModel);
                }
                return(jobs);
            }
            return(null);
        }
        public async Task QueueJob()
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json")
                         .Build();

            StorageHelper <JobModel> storage = new StorageHelper <JobModel>(config);

            JobModel model = new JobModel();

            model.Id         = "999";
            model.Job        = "Sleep";
            model.Details    = "Power sleeping";
            model.Path       = "XYZ";
            model.Parameters = new System.Collections.Generic.Dictionary <string, string>();
            model.Parameters.Add("Iterations", "10");
            model.Parameters.Add("Delay", "3000");

            await storage.SaveToServiceBusQueue(model, "jobs");
        }
Example #15
0
        public List <JobManager.Model.JobModel> SearchJobs(int?jobId, int?branchId, DateTime?startDate, DateTime?endDate)
        {
            var jobs = jmdc.SearchJobDetails(jobId, branchId, startDate, endDate);

            List <JobManager.Model.JobModel> jobsList = new List <JobManager.Model.JobModel>();

            foreach (var jm in jobs)
            {
                JobModel jobDetails = new JobModel();
                jobDetails.JobId       = jm.Id;
                jobDetails.JobName     = jm.JobName;
                jobDetails.CreatedDate = jm.CreatedDate;
                jobDetails.StatusId    = jm.StatusId;
                jobDetails.BranchId    = jm.BranchId;
                jobDetails.Status      = jm.Status;
                jobDetails.Branch      = jm.Branch;
                jobsList.Add(jobDetails);
            }
            return(jobsList);
        }
Example #16
0
        public async Task <bool?> Post(int JobId, JobModel jobModel)
        {
            try
            {
                var updated = await _manageJobs.UpdateJobAsync(jobModel);

                if (updated)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(null);
            }
        }
Example #17
0
        private static PartialDateRange GetDates(JobModel jobModel)
        {
            if (jobModel.StartDate == null && jobModel.EndDate == null && (jobModel.IsCurrent == null || !jobModel.IsCurrent.Value))
            {
                return(null);
            }

            if (jobModel.StartDate != null)
            {
                return(jobModel.EndDate == null
                    ? new PartialDateRange(jobModel.StartDate.Value)
                    : jobModel.StartDate.Value > jobModel.EndDate.Value
                        ? new PartialDateRange(jobModel.EndDate.Value, jobModel.StartDate.Value)
                        : new PartialDateRange(jobModel.StartDate.Value, jobModel.EndDate.Value));
            }

            return(jobModel.EndDate != null
                ? new PartialDateRange(null, jobModel.EndDate.Value)
                : new PartialDateRange());
        }
        private List <LinkInfo> GenerateJobModelLinks(JobModel model, HttpRequest request)
        {
            var links = new List <LinkInfo>
            {
                new LinkInfo
                {
                    Href   = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}",
                    Rel    = "self",
                    Method = "GET"
                },
                new LinkInfo
                {
                    Href   = $"{request.Scheme}://{request.Host}/api/jobs/{model.JobId}/materials",
                    Rel    = "materials",
                    Method = "GET"
                }
            };

            return(links);
        }
Example #19
0
        public ActionResult Apply([FromForm] ApplyViewModel model)
        {
            try {
                string   UserId = _usermanager.GetUserId(User);
                JobModel job    = _context.jobs.Where(x => x.Id == model.JobId).FirstOrDefault();

                UserJob user = new UserJob {
                    UserId = UserId, JobId = job.Id
                };
                _context.Candidates.Add(user);
                _context.SaveChanges();
            }
            catch (Exception e)
            {
                return(BadRequest());
            }


            return(Ok());
        }
Example #20
0
        /// <summary>
        /// Converts <see cref="JobModel"/> to <see cref="Job"/>
        /// </summary>
        /// <param name="jobModel">
        /// The job model object
        /// </param>
        /// <returns>
        /// The job object
        /// </returns>
        public static Job ToJob(this JobModel jobModel)
        {
            if (jobModel == null)
            {
                return(null);
            }

            var contact   = new Contact(jobModel.ContactName, jobModel.ContactPhone, jobModel.ContactEmail);
            var jobStatus = Enum.TryParse <Status>(jobModel.Status, true, out var status) ? status : Status.New;

            return(new Job(
                       jobModel.Id,
                       jobModel.Suburb.ToSuburb(),
                       contact,
                       jobModel.Category.ToCategory(),
                       jobModel.Description,
                       jobModel.Time,
                       jobModel.Price,
                       jobStatus));
        }
Example #21
0
        public async Task <bool?> Post(JobModel jobModel)
        {
            try
            {
                var added = await _manageJobs.AddJobAsync(jobModel);

                if (added)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(null);
            }
        }
Example #22
0
        protected virtual async Task <bool> IsJobTimedOut(JobModel job, CancellationToken cancellationToken)
        {
            var timedOutTime = DateTimeOffset.UtcNow;

            if (job.Status != JobStatus.InProgress || job.StartTime.Add(Config.EarningsJobTimeout) >= timedOutTime)
            {
                return(false);
            }
            Logger.LogWarning(
                $"Job {job.DcJobId} has timed out.  Start time: {job.StartTime}, timed out at: {timedOutTime}.");
            var status = JobStatus.TimedOut;

            if (job.DcJobSucceeded.HasValue)
            {
                status = job.DcJobSucceeded.Value ? JobStatus.CompletedWithErrors : JobStatus.DcTasksFailed;
            }

            return(await CompleteJob(job, status, timedOutTime, cancellationToken)
                   .ConfigureAwait(false));
        }
 public JsonResult UpdateJob(JobModel model)
 {
     try
     {
         var result   = CorporateBusiness.UpdateJob(model);
         var response = new ApiRespnoseWrapper {
             status = ApiRespnoseStatus.Success, results = new ArrayList()
             {
                 result
             }
         };
         return(new JsonResult {
             Data = response
         });
     }
     catch (Exception ex)
     {
         return(CommonBusiness.GetErrorResponse(ex.Message));
     }
 }
        public async Task <IActionResult> UpdateJob(int jobId, [FromBody] JobModel model)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            try
            {
                var jobData = JobAssistantMapper.Map <Job>(model);
                await _repo.Update(jobData);
            }
            catch (Exception e)
            {
                _logger.LogError(1, e, "Failed to update job in DB repository");
                throw;
            }

            return(Ok());
        }
Example #25
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            JobModel myModel = new JobModel();

            myModel.Job       = JobName.Text;
            myModel.MinSalary = Convert.ToDecimal(MinSalary.Text);
            myModel.MaxSalary = Convert.ToDecimal(MaxSalary.Text);

            if (HiddenField1.Value != "")
            {
                myModel.ID = Convert.ToInt32(HiddenField1.Value);
            }
            myModel = jobInterface.AddAndUpdateJob(myModel);
            if (myModel.ID > 0)
            {
                Response.Write("<script>alert('Record saved successfully')</script>");
                Response.Redirect("Job.aspx");
            }
            bindGrid();
        }
        public ActionResult Edit(JobModel job)
        {
            if (ModelState.IsValid)
            {
                var update = db.Jobs.Single(x => x.Id == job.Id);

                // Update normal Stats.
                update.Name        = job.Name;
                update.JobCategory = job.JobCategory;
                update.JobType     = job.JobType;
                update.SkillId     = job.SkillId;
                update.SkillLevel  = job.SkillLevel;

                // processes
                update.ClearProcessRelations();
                foreach (var id in job.SelectedProcessIds)
                {
                    update.AddProcess(db.Processes.Single(x => x.Id == id));
                }

                // labor
                update.ClearLaborRelations();
                foreach (var id in job.SelectedLaborIds)
                {
                    update.AddLabor(db.Products.Single(x => x.Id == id));
                }

                // jobs
                update.ClearJobRelations();
                foreach (var id in job.SelectedRelatedJobIds)
                {
                    update.AddRelatedJob(db.Jobs.Single(x => x.Id == id));
                }

                db.Entry(update).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.SkillId = new SelectList(db.Skills, "Id", "Name", job.SkillId);
            return(View(job));
        }
        public async Task AddJob_ValidJob_NoError()
        {
            // Arrange
            DbContextOptions <YellowJacketContext> options = new DbContextOptionsBuilder <YellowJacketContext>()
                                                             .UseInMemoryDatabase("AddJob_ValidJob_NoError")
                                                             .Options;

            const string jobName = "MyJob";

            JobModel model = new JobModel
            {
                Name        = jobName,
                Features    = new List <string>(),
                PackageName = "MyPackage.zip",
            };

            // Act
            using (YellowJacketContext context = new YellowJacketContext(options))
            {
                IJobRepository jobRepository = new JobRepository(context);

                IJobService service = new JobService(jobRepository, GetMapper());

                await service.Add(model);
            }

            // Assert
            using (YellowJacketContext context = new YellowJacketContext(options))
            {
                const int expectedCount = 1;

                Assert.That(
                    expectedCount, Is.EqualTo(Convert.ToInt32(context.Jobs.Count())),
                    $"The job count should be {expectedCount}.");

                Assert.That(
                    jobName,
                    Is.EqualTo(context.Jobs.Single().Name),
                    $"The expected job name {jobName} doesn't match the actual value {context.Jobs.Single().Name}");
            }
        }
        public async Task WhenThereAreJobsFromPreviousAcademicYearAndCurrentAcademicYear_thenOnlyReturnsJobsFromCurrentAcademicYear()
        {
            using (var sut = new InMemoryMetricsQueryDataContext())
            {
                await sut.Jobs.AddAsync(new JobModel
                {
                    JobType          = JobType.EarningsJob,
                    AcademicYear     = 2122,
                    CollectionPeriod = 1,
                    DcJobId          = 1,
                    Ukprn            = 1,
                    Status           = JobStatus.InProgress,
                    DcJobSucceeded   = true,
                    StartTime        = DateTimeOffset.Now.AddMinutes(-148)
                });

                await sut.Jobs.AddAsync(new JobModel
                {
                    JobType          = JobType.EarningsJob,
                    AcademicYear     = 2021,
                    CollectionPeriod = 14,
                    DcJobId          = 14,
                    Ukprn            = 14,
                    Status           = JobStatus.InProgress,
                    DcJobSucceeded   = true,
                    StartTime        = DateTimeOffset.Now.AddMinutes(-148)
                });

                await sut.SaveChangesAsync();

                var periodEndStartJob = new JobModel {
                    JobType = JobType.PeriodEndStartJob, AcademicYear = 2122, CollectionPeriod = 1, StartTime = DateTimeOffset.Now, DcJobId = 123
                };

                var actual = await sut.GetOutstandingOrTimedOutJobs(periodEndStartJob, CancellationToken.None);

                actual.Count.Should().Be(1);
                actual[0].DcJobId.Should().Be(1);
                actual[0].Ukprn.Should().Be(1);
            }
        }
Example #29
0
        public ActionResult Edit(JobModel model)
        {
            if (ModelState.IsValid)
            {
                var fileName = model.JobImage ?? "";
                if (Request.Form.Files.Count > 0)
                {
                    var file        = Request.Form.Files[0];
                    var webRootPath = _hostingEnvironment.WebRootPath;
                    var newPath     = Path.Combine(webRootPath, "images");
                    if (!Directory.Exists(newPath))
                    {
                        Directory.CreateDirectory(newPath);
                    }

                    if (file.Length > 0)
                    {
                        fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                        var fullPath = Path.Combine(newPath, fileName);
                        using (var stream = new FileStream(fullPath, FileMode.Create))
                        {
                            file.CopyTo(stream);
                        }
                    }
                }

                var job = new JobEntity()
                {
                    JobID     = model.JobID,
                    CityId    = model.CityId,
                    JobImage  = fileName,
                    JobTitle  = model.JobTitle,
                    UpdatedBY = "1",
                    IsActive  = model.IsActive,
                };

                _jobManager.Update(job);
                return(RedirectToAction("Index", "Job"));
            }
            return(View("addjob_view", model));
        }
Example #30
0
        private void LoadFormWithJobFromComboBox(string selectedJob)
        {
            try
            {
                JobModel jobModel = ApiHelpers.ApiConnectorHelper.GetSelectedJobData <JobModel>(selectedJob, pathJobSelected).First();
                job_id = jobModel.Id;

                oldJobCircultaionHours = jobModel.CirculationHours;

                editJobLabel.Text                = jobModel.JobNumber;
                editJobNumberText.Text           = jobModel.JobNumber;
                editJobClientText.Text           = jobModel.ClientName;
                editJobGdpText.Text              = jobModel.GDP;
                editJobModemText.Text            = jobModel.Modem;
                editJobModemVersionText.Text     = jobModel.ModemVersion;
                editJobBbpText.Text              = jobModel.Bullplug;
                editJobCirculationHoursText.Text = jobModel.CirculationHours.ToString();
                editJobMaxTemperatureText.Text   = jobModel.MaxTemp.ToString();
                editJobBatteryText.Text          = jobModel.Battery;

                editJobEngOneText.Text      = jobModel.EngineerOne;
                editJobEngTwoText.Text      = jobModel.EngineerTwo;
                editJobEng1ArrivedText.Text = jobModel.eng_one_arrived;
                editJobEng2ArrivedText.Text = jobModel.eng_two_arrived;
                editJobEng1LeftText.Text    = jobModel.eng_one_left;
                editJobEng2LeftText.Text    = jobModel.eng_two_left;

                editJobContainerText.Text   = jobModel.Container;
                editJobContArrivedText.Text = jobModel.ContainerArrived;
                editJobContLeftText.Text    = jobModel.ContainerLeft;

                editJobRigText.Text = jobModel.Rig;
                // TODO - refactor combobox to appropriate format

                editJobCommentText.Text = jobModel.Comment;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Example #31
0
        /// <summary>
        /// 创建一个任务
        /// </summary>
        /// <param name="Errors">错误返回</param>
        /// <param name="task">任务</param>
        /// <param name="taskName">命名空间类</param>
        /// <param name="taskId">可利用标识</param>
        /// <param name="taskTitle">任务标题</param>
        /// <returns></returns>
        public static int CreateTaskJob(ref ValidationErrors Errors, string task, string taskName, string taskId, string taskTitle)
        {
            ITaskRun taskRun  = new TaskRun();
            JobModel jobmodel = taskRun.CreateJobModel(task, taskName, taskId, taskTitle);

            if (jobmodel != null)
            {
                if (jobmodel.taskType == 0)
                {
                    //执行简单任务
                    return(taskRun.runSample <TaskJob>(jobmodel, ref Errors));
                }
                else
                {
                    //执行复杂任务
                    return(taskRun.runComplex <TaskJob>(jobmodel, ref Errors));
                }
            }

            return(0);
        }
Example #32
0
        protected override async Task <bool> CompleteJob(JobModel job, JobStatus status, DateTimeOffset endTime,
                                                         CancellationToken cancellationToken)
        {
            status = job.DcJobSucceeded.HasValue && !job.DcJobSucceeded.Value
                ? JobStatus.DcTasksFailed
                : status;
            if (!await base.CompleteJob(job, status, endTime, cancellationToken))
            {
                return(false);
            }

            if (!job.DcJobSucceeded.HasValue)
            {
                return(false);
            }
            if (job.JobType == JobType.EarningsJob || job.JobType == JobType.ComponentAcceptanceTestEarningsJob)
            {
                await EventPublisher.SubmissionFinished(status == JobStatus.Completed || status == JobStatus.CompletedWithErrors, job.DcJobId.Value, job.Ukprn.Value, job.AcademicYear, job.CollectionPeriod, job.IlrSubmissionTime.Value).ConfigureAwait(false);
            }
            return(true);
        }
Example #33
0
        public int AddJob(JobModel model)
        {
            if (model == null) throw new ArgumentException("parameter model is null");

            using (SqlConnection conn = SqlConnectionService.GetConnection())
            {
                string query = "INSERT INTO dbo.Jobs (JobDescription, Salary, Threshold, EarningPoints, NecessaryPoints) OUTPUT INSERTED.JobId values (@Des, @Salary, @Thres, @Earn, @Necessary)";
                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@Des", model.JobDescription);
                    cmd.Parameters.AddWithValue("@Salary", model.Salary);
                    cmd.Parameters.AddWithValue("@Thres", model.Threshold);
                    cmd.Parameters.AddWithValue("@Earn", model.EarningPoints);
                    cmd.Parameters.AddWithValue("@Necessary", model.NecessaryPoints);

                    int lgn = (int)cmd.ExecuteScalar();

                    conn.Close();

                    return lgn;
                }
            }
        }
Example #34
0
 public async Task<IHttpActionResult> Post(JobModel model)
 {
     Job job = await repository.PostJob(model);
     return Ok(job);
 }
Example #35
0
        /// <summary>
        /// Gets all the info relating the job of the User corresponding to the connectionId
        /// </summary>
        /// <param name="connectionId"></param>
        /// <returns>Returns a job model containing all the infos</returns>
        public JobModel GetUserJobInfos(string connectionId)
        {
            if (connectionId == null) throw new ArgumentException("there is no id");
            ServerPlayerModel user = ServiceProvider.GetPlayerService().GetPlayer(connectionId);
            if (user == null) throw new ArgumentException("parameter user is null");

            using (SqlConnection conn = SqlConnectionService.GetConnection())
            {
                string query = "SELECT * from dbo.Users u JOIN dbo.Jobs j on j.JobId = u.JobId WHERE u.UserId = @id";
                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    conn.Open();

                    cmd.Parameters.AddWithValue("@id", user.UserId);

                    JobModel model = new JobModel();

                    var reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        model.JobDescription = reader["JobDescription"].ToString();
                        model.JobId = Convert.ToInt32(reader["JobId"]);
                        model.Salary = Convert.ToInt32(reader["Salary"]);
                        model.Threshold = Convert.ToInt32(reader["Threshold"]);
                        model.EarningPoints = Convert.ToInt32(reader["EarningPoints"]);
                        model.NecessaryPoints = Convert.ToInt32(reader["NecessaryPoints"]);
                    }

                    conn.Close();

                    return model;
                }
            }
        }
Example #36
0
        /// <summary>
        /// Delete the job corresponding to the specified JobModel
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool DeleteJob(JobModel model)
        {
            if (model == null) throw new ArgumentException("parameter model is null");

            return DeleteJob(model.JobId);
        }
Example #37
0
 public Task<Job> PostJob(JobModel model)
 {
     throw new NotImplementedException();
 }
Example #38
0
        /// <summary>
        /// Gets a list of every possible jobs
        /// </summary>
        /// <returns></returns>
        public List<JobModel> GetAllJobs()
        {
            List<JobModel> jobs = new List<JobModel>();
            using (SqlConnection conn = SqlConnectionService.GetConnection())
            {
                string query = "SELECT * from dbo.Jobs";
                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    conn.Open();
                    var reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        JobModel model = new JobModel();
                        model.JobDescription = reader["JobDescription"].ToString();
                        model.JobId = Convert.ToInt32(reader["JobId"]);
                        model.Salary = Convert.ToInt32(reader["Salary"]);
                        model.Threshold = Convert.ToInt32(reader["Threshold"]);
                        model.EarningPoints = Convert.ToInt32(reader["EarningPoints"]);
                        model.NecessaryPoints = Convert.ToInt32(reader["NecessaryPoints"]);
                        jobs.Add(model);
                    }

                    conn.Close();
                    return jobs;
                }
            }
        }