예제 #1
0
        public void CalculateOutputFormYearJob_Success()
        {
            var date = new DateTime(2019, 2, 1);

            var dbContext = TypiconDbContextFactory.Create();
            var jobRepo   = new JobRepository();

            var yearHandler = CalculateModifiedYearJobHandlerTest.Build(dbContext, jobRepo);
            var yearJob     = new CalculateModifiedYearJob(1, 2019);

            jobRepo.Create(yearJob);

            Task task = yearHandler.ExecuteAsync(yearJob);

            task.Wait();

            var weekHandler = Build(dbContext, jobRepo);
            var weekJob     = new CalculateOutputFormWeekJob(1, 1, date);

            jobRepo.Create(weekJob);

            task = weekHandler.ExecuteAsync(weekJob);
            task.Wait();

            var queryProcessor = QueryProcessorFactory.Create();

            var week = queryProcessor.Process(new OutputWeekQuery(1, date, new OutputFilter()
            {
                Language = "cs-ru"
            }));

            Assert.AreEqual(true, week.Success);
        }
예제 #2
0
 protected void OnBtnBatchActivateClicked(object sender, EventArgs e)
 {
     GridItemCollection col = gridJobs.SelectedItems;
     JobRepository repo = new JobRepository();
     bool updated = false;
     foreach (GridDataItem item in col)
     {
         TableCell cell = item["JobID"];
         if (!string.IsNullOrEmpty(cell.Text))
         {
             int jobId = int.Parse(cell.Text);
             Job job = repo.FindOne(new Job(jobId));
             if (job != null)
             {
                 job.IsActive = true;
                 repo.Update(job);
                 updated = true;
             }
         }
     }
     if (updated)
     {
         //calExpiredDate.SelectedDate = null;
         //calRemindDate.SelectedDate = null;
         gridJobs.Rebind();
     }
 }
예제 #3
0
 public void DeleteJob(int jobId)
 {
     //unitOfWork.StartTransaction();
     JobRepository repo = new JobRepository(unitOfWork);
     repo.Delete(x => x.JobId == jobId);
     //unitOfWork.Commit();
 }
예제 #4
0
        private void RemoveJobAndDispose(Job job, bool jobIsJob2)
        {
            try
            {
                bool job2TypeFound = false;

                if (jobIsJob2)
                {
                    job2TypeFound = JobManager.RemoveJob(job as Job2, this, true, false);
                }

                if (!job2TypeFound)
                {
                    JobRepository.Remove(job);
                }

                job.Dispose();
            }
            catch (ArgumentException ex)
            {
                string message = PSRemotingErrorInvariants.FormatResourceString(
                    RemotingErrorIdStrings.CannotRemoveJob);

                ArgumentException ex2 = new ArgumentException(message, ex);
                WriteError(new ErrorRecord(ex2, "CannotRemoveJob", ErrorCategory.InvalidOperation, job));
            }
        }
예제 #5
0
 protected void JobAjaxManager_AjaxRequest(object sender, AjaxRequestEventArgs e)
 {
     if (e.Argument.IndexOf("OpenSelectedJob") > -1)
     {
         if (gridJobs.SelectedItems.Count == 1)
         {
             Response.Redirect(string.Format("~/JobProfile.aspx?JobId={0}&mode=edit", GetSelectedJobID()), true);
         }
     }
     else if (e.Argument.IndexOf("DeleteSelectedJob") > -1)
     {
         if (gridJobs.SelectedItems.Count == 1)
         {
             JobAjaxManager.AjaxSettings.AddAjaxSetting(JobAjaxManager, gridJobs);
             JobRepository jobRepo = new JobRepository();
             jobRepo.Delete(new Job(GetSelectedJobID()));
             gridJobs.Rebind();
         }
     }
     else if (e.Argument.IndexOf("PreviewJob") > -1)
     {
         if (gridJobs.SelectedItems.Count == 1)
         {
             string script = string.Format("openPopUp('{0}')", WebConfig.NeosJobDetailURL + GetSelectedJobID());
             JobAjaxManager.ResponseScripts.Add(script);
             JobAjaxManager.ResponseScripts.Add("processJobToolBar(\"JobGridSelected\");");
         }
     }
 }
예제 #6
0
 public static void MarkJobAsCompleteWithError(Job job)
 {
     using (var repo = new JobRepository())
     {
         repo.UpdateStateForJob(job, JobState.CompletedWithError);
     }
 }
예제 #7
0
        public void PlanTwoJobsWithMultipleTranscodingPluginsTest()
        {
            var wfsPluginMock = CreateWfsMock("1");

            wfsPluginMock.SetupGet(p => p.Busy).Returns(false);
            wfsPluginMock.Setup(p => p.CheckAndEstimate(It.IsAny <ExecutionTask>())).Returns(true);
            var ffmpegPluginMock = CreateFFMpegMock("1");

            ffmpegPluginMock.SetupGet(p => p.Busy).Returns(false);
            ffmpegPluginMock.Setup(p => p.CheckAndEstimate(It.IsAny <ExecutionTask>())).Returns(true);
            var planner = new SimplePlanner(new List <IPlugin> {
                wfsPluginMock.Object, ffmpegPluginMock.Object
            }, JobRepository, Logging, _callBackService.Object);
            var audioJob = CreateNewFFMpegJob();
            var videoJob = CreateNewWfsJob();

            JobRepository.Add(audioJob);
            JobRepository.Add(videoJob);
            Assert.That(JobRepository.WaitingJobs().Count(), Is.EqualTo(2));
            Assert.That(JobRepository.ActiveJobs().Count(), Is.EqualTo(0));
            planner.Calculate();
            ffmpegPluginMock.Verify(x => x.CheckAndEstimate(It.IsAny <ExecutionTask>()), Times.Once(), "ffmpeg plugin should only be called once");
            wfsPluginMock.Verify(x => x.CheckAndEstimate(It.IsAny <ExecutionTask>()), Times.Once(), "Wfs plugin should only be called once");
            Assert.That(JobRepository.WaitingJobs().Count(), Is.EqualTo(0));
            Assert.That(JobRepository.ActiveJobs().Count(), Is.EqualTo(2));
            var dbAudioJob = JobRepository.ActiveJobs().First(j =>
                                                              j.Plan.Tasks.First().PluginUrn == ffmpegPluginMock.Object.Urn);
            var dbVideoJob = JobRepository.ActiveJobs().First(j =>
                                                              j.Plan.Tasks.First().PluginUrn == wfsPluginMock.Object.Urn);

            Assert.That(dbAudioJob.Urn, Is.EqualTo(audioJob.Urn));
            Assert.That(dbVideoJob.Urn, Is.EqualTo(videoJob.Urn));
        }
예제 #8
0
        public static Job GetJob(int jobId, Logger defaultLogger)
        {
            Job currentJob;

            using (var repo = new JobRepository())
            {
                defaultLogger.Info("Passed job with ID of {0}", jobId);

                currentJob = repo.GetJobById(jobId);

                if (currentJob == null)
                {
                    defaultLogger.Warn("Job not found");
                    return(null);
                }

                defaultLogger.Info("Job found. URL is {0} and branch is {1}", currentJob.Url, currentJob.Branch);

                if (currentJob.State != JobState.Pending)
                {
                    defaultLogger.Warn("Cannot start job. Current state is {0}", currentJob.State);
                    return(null);
                }

                repo.UpdateStateForJob(currentJob, JobState.Running);
            }

            return(currentJob);
        }
예제 #9
0
        public void PlanAJobWithMuxingTest()
        {
            var wfsPluginMock = CreateWfsMock("1");

            wfsPluginMock.SetupGet(p => p.Busy).Returns(false);
            wfsPluginMock.Setup(p => p.CheckAndEstimate(It.IsAny <ExecutionTask>())).Returns(true);
            var ffmpegPluginMock = CreateFFMpegMock("1");

            ffmpegPluginMock.SetupGet(p => p.Busy).Returns(false);
            ffmpegPluginMock.Setup(p => p.CheckAndEstimate(It.IsAny <ExecutionTask>())).Returns(true);
            var planner = new SimplePlanner(new List <IPlugin> {
                wfsPluginMock.Object, ffmpegPluginMock.Object
            }, JobRepository, Logging, _callBackService.Object);
            var audioJob = CreateNewAudioMuxJob();

            JobRepository.Add(audioJob);
            Assert.That(JobRepository.WaitingJobs().Count(), Is.EqualTo(1));
            Assert.That(JobRepository.ActiveJobs().Count(), Is.EqualTo(0));
            planner.Calculate();
            ffmpegPluginMock.Verify(x => x.CheckAndEstimate(It.IsAny <ExecutionTask>()), Times.Exactly(1), "ffmpeg plugin should only be called once for muxing");
            wfsPluginMock.Verify(x => x.CheckAndEstimate(It.IsAny <ExecutionTask>()), Times.Exactly(1), "Wfs plugin should only be called once for transcoding");
            Assert.That(JobRepository.WaitingJobs().Count(), Is.EqualTo(0));
            Assert.That(JobRepository.ActiveJobs().Count(), Is.EqualTo(1));
            var dbMuxJob = JobRepository.ActiveJobs().First();

            Assert.That(dbMuxJob.Plan.Tasks.Count(), Is.EqualTo(2));
            Assert.That(dbMuxJob.Plan.Tasks[0].PluginUrn, Is.EqualTo(ffmpegPluginMock.Object.Urn));
            Assert.That(dbMuxJob.Plan.Tasks[1].PluginUrn, Is.EqualTo(wfsPluginMock.Object.Urn));
        }
예제 #10
0
        public ActionResult ViewLog(int id)
        {
            Job job;

            using (var repo = new JobRepository())
            {
                job = repo.GetJobById(id);
            }

            if (job == null)
            {
                return(Content("Job not found."));
            }

            string logFileName = "Deploy_" + job.Name + "_" + job.Id + ".log";

            string logFile = Path.Combine(_logDirectory, logFileName);

            if (System.IO.File.Exists(logFile))
            {
                string allText   = System.IO.File.ReadAllText(logFile);
                var    viewModel = new DeploymentLogViewModel
                {
                    JobId         = job.Id.ToString(),
                    DeploymentLog = allText,
                    LogName       = job.Name
                };

                return(View(viewModel));
            }


            return(Content("File not found."));
        }
예제 #11
0
        public void ValidateJob_EmptyName_ValidationError()
        {
            // Arrange
            DbContextOptions <YellowJacketContext> options = new DbContextOptionsBuilder <YellowJacketContext>()
                                                             .UseInMemoryDatabase("AddJob_EmptyName_ValidationError")
                                                             .Options;

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

            // Act
            ValidationResult validationResult;

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

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

                validationResult = service.Validate(model);
            }

            // Assert
            const int    expectedValidationErrorCount = 1;
            const string errorMessage = "'Name' should not be empty.";

            Assert.That(validationResult.Errors.Count, Is.EqualTo(expectedValidationErrorCount),
                        $"The validation error count should be {expectedValidationErrorCount}");

            Assert.That(validationResult.Errors.First().ErrorMessage, Is.EqualTo(errorMessage),
                        $"The expected error message '{errorMessage}' doesn't match the actual one {validationResult.Errors.First().ErrorMessage}");
        }
 public AdminAttendenceController(IEmpRepository empRepository, IWebHostEnvironment webHostEnvironment, AttendenceRepo attendenceRepo, JobRepository jobRepository)
 {
     _empRepository        = empRepository;
     _jobRepository        = jobRepository;
     _webHostEnvironment   = webHostEnvironment;
     _attendenceRepository = attendenceRepo;
 }
예제 #13
0
        public JobStateType(
            JobRepository jobRepository,
            JobStateRepository jobStateRepository
            )
        {
            Field(x => x.Id, type: typeof(IdGraphType));
            Field(x => x.Name);
            Field(x => x.DisplayName);

            Field <ListGraphType <JobType> >(
                "jobs",
                resolve: context => jobRepository.GetByJobStateId(context.Source.Id)
                );

            //// Async test
            //FieldAsync<ListGraphType<JobType>>(
            //    "jobs",
            //    resolve: async context =>
            //    {
            //        return await context.TryAsyncResolve(
            //            async c => await jobRepository.GetByJobStateIdAsync(context.Source.Id)
            //        );
            //    }
            //);

            Field(x => x.CreatedByUserId, type: typeof(IdGraphType));
            // TODO: Field(x => x.CreatedByUser, type: typeof(UserType));
            Field(x => x.ModifiedByUserId, type: typeof(IdGraphType));
            // TODO: Field(x => x.ModifiedByUser, type: typeof(UserType));
        }
예제 #14
0
        protected void ddlGroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            JobRepository Groupsrepo = new JobRepository();

            if (ddlGroups.SelectedValue != "0")
            {
                DataTable DT = new DataTable();
                DT = Groupsrepo.getJobsByGroupID(ddlGroups.SelectedValue.ToInt());

                if ((DT.Rows.Count > 0))
                {
                    gvSubGroups.DataSource = DT;

                    gvSubGroups.DataBind();
                }
                else
                {
                    gvSubGroups.DataSource = null;

                    gvSubGroups.DataBind();
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('این گروه هیچ زیرگروهی ندارد!');", true);
                }
            }
            else
            {
                gvSubGroups.DataSource = null;
                gvSubGroups.DataBind();
                gvSubGroups.DataSource = Groupsrepo.getAllJobsByGroupID();
                gvSubGroups.DataBind();
            }
        }
        public void IsApiUserAllowedTest()
        {
            IHandleJobs repo = new JobRepository("test");
            var         sut  = repo.IsApiUserAllowed("test", "test");

            sut.Success.Should().BeTrue();
        }
예제 #16
0
        // GET: Job/Create
        public ActionResult Create()
        {
            var repo = new JobRepository();
            var job  = repo.CreateJob();

            return(View(job));
        }
예제 #17
0
        public bool Save(Job job, out string strResult)
        {
            strResult = string.Empty;
            bool result = false;
            var  jo     = JobRepository.GetQueryable().FirstOrDefault(j => j.ID == job.ID);

            if (jo != null)
            {
                try
                {
                    jo.JobCode     = job.JobCode;
                    jo.JobName     = job.JobName;
                    jo.Description = job.Description;
                    jo.IsActive    = job.IsActive;
                    jo.UpdateTime  = DateTime.Now;

                    JobRepository.SaveChanges();
                    result = true;
                }
                catch (Exception ex)
                {
                    strResult = "原因:" + ex.Message;
                }
            }
            else
            {
                strResult = "原因:未找到当前需要修改的数据!";
            }
            return(result);
        }
예제 #18
0
        public bool Delete(string JobId, out string strResult)
        {
            strResult = string.Empty;
            bool result = false;
            Guid joId   = new Guid(JobId);
            var  job    = JobRepository.GetQueryable().FirstOrDefault(j => j.ID == joId);

            if (job != null)
            {
                try
                {
                    JobRepository.Delete(job);
                    JobRepository.SaveChanges();
                    result = true;
                }
                catch (Exception)
                {
                    strResult = "原因:已在使用";
                }
            }
            else
            {
                strResult = "原因:未找到当前需要删除的数据!";
            }
            return(result);
        }
예제 #19
0
        public object GetJob(int page, int rows, string queryString, string value)
        {
            string jobCode = "", jobName = "";

            if (queryString == "JobCode")
            {
                jobCode = value;
            }
            else
            {
                jobName = value;
            }
            IQueryable <Job> jobQuery = JobRepository.GetQueryable();
            var job = jobQuery.Where(j => j.JobCode.Contains(jobCode) && j.JobName.Contains(jobName) && j.IsActive == "1")
                      .OrderBy(j => j.JobCode).AsEnumerable().
                      Select(j => new
            {
                j.ID,
                j.JobCode,
                j.JobName,
                j.Description,
                IsActive = j.IsActive == "1" ? "可用" : "不可用"
            });
            int total = job.Count();

            job = job.Skip((page - 1) * rows).Take(rows);
            return(new { total, rows = job.ToArray() });
        }
예제 #20
0
        public object GetDetails(int page, int rows, string JobCode, string JobName, string IsActive)
        {
            IQueryable <Job> jobQuery = JobRepository.GetQueryable();
            var job = jobQuery.Where(j => j.JobCode.Contains(JobCode) && j.JobName.Contains(JobName))
                      .OrderByDescending(j => j.UpdateTime).AsEnumerable()
                      .Select(j => new
            {
                j.ID,
                j.JobCode,
                j.JobName,
                j.Description,
                IsActive   = j.IsActive == "1" ? "可用" : "不可用",
                UpdateTime = j.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss")
            });

            if (!IsActive.Equals(""))
            {
                job = jobQuery.Where(j => j.JobCode.Contains(JobCode) && j.JobName.Contains(JobName) && j.IsActive.Contains(IsActive))
                      .OrderByDescending(j => j.UpdateTime).AsEnumerable()
                      .Select(j => new
                {
                    j.ID,
                    j.JobCode,
                    j.JobName,
                    j.Description,
                    IsActive   = j.IsActive == "1" ? "可用" : "不可用",
                    UpdateTime = j.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss")
                });
            }
            int total = job.Count();

            job = job.Skip((page - 1) * rows).Take(rows);
            return(new { total, rows = job.ToArray() });
        }
예제 #21
0
        public JobControllerTest()
        {
            var context    = CreateDbContext();
            var repository = new JobRepository(context);

            _jobController = new JobsController(repository);
        }
        public async Task CanCreateJob()
        {
            // Arrange
            var expectedJob = new Database.Entities.Job
            {
                Id         = Guid.NewGuid(),
                LeagueCode = "LC",
                StatusCode = System.Net.HttpStatusCode.Created
            };

            using var executionContext = new ExecutionContext <AppDbContext>(true);
            using (var actionContext = await executionContext.CreateContextAsync())
            {
                var sut = new JobRepository(actionContext.Jobs);

                // Act
                sut.Add(expectedJob);
                await actionContext.SaveChangesAsync();
            }

            // Assert
            using var assertionContext = await executionContext.CreateContextAsync();

            var createdJob = await assertionContext.Jobs
                             .FirstOrDefaultAsync(job => job.Id == expectedJob.Id);

            createdJob.Should().NotBeNull();
            createdJob.Should().BeEquivalentTo(expectedJob);
        }
 public AdminTimeSController(IEmpRepository empRepository, IWebHostEnvironment webHostEnvironment, TaskRepo taskRepository, JobRepository jobRepository)
 {
     _empRepository      = empRepository;
     _jobRepository      = jobRepository;
     _webHostEnvironment = webHostEnvironment;
     _taskRepository     = taskRepository;
 }
        public void CreateApiUserTest()
        {
            IHandleJobs repo = new JobRepository("test");
            var         sut  = repo.CreateApiUser("test", "test");

            sut.Result.Success.Should().BeTrue();
        }
예제 #25
0
        public UnitOfWork(AddressRepository addressRepository, CandidateRepository candidateRepository, EmployerRepository employerRepository,
                          GorvernmentRepository gorvernmentRepository, JobRepository jobRepository, MicroCredentialRepository microCredentialRepository, MoocProviderRepository moocProviderRepository,
                          RecruitmentAgencyRepository recruitmentAgencyRepository, AccreditationBodyRepository accreditationBodyRepository, CandidateMicroCredentialCourseRepository candidateMicroCredentialCourseRepository,
                          EndorsementBodyRepository endorsementBodyRepository, CandidateJobApplicationRepository candidateJobApplicationRepository, CandidatetMicroCredentialBadgesRepository candidatetMicroCredentialBadgesRepository,
                          StratisAccountRepository stratisAccountRepository)
        {
            _addressRepository = addressRepository;

            _candidateRepository = candidateRepository;

            _employerRepository = employerRepository;

            _gorvernmentRepository = gorvernmentRepository;

            _jobRepository = jobRepository;

            _microCredentialRepository = microCredentialRepository;

            _moocProviderRepository = moocProviderRepository;

            _recruitmentAgencyRepository = recruitmentAgencyRepository;

            _accreditationBodyRepository = accreditationBodyRepository;

            _candidateMicroCredentialCourseRepository = candidateMicroCredentialCourseRepository;

            _endorsementBodyRepository = endorsementBodyRepository;

            _candidateJobApplicationRepository = candidateJobApplicationRepository;

            _candidatetMicroCredentialBadgesRepository = candidatetMicroCredentialBadgesRepository;

            _stratisAccountRepository = stratisAccountRepository;
        }
예제 #26
0
        protected void btnSaveNewGroup_Click(object sender, EventArgs e)
        {
            JobGroupsRepository repgp = new JobGroupsRepository();
            JobGroup            ngp   = new JobGroup();

            ngp.JobGroupTitle = tbxNewGroup.Text;
            repgp.Savegp(ngp);
            DataTable allGroups = new DataTable();

            allGroups           = repgp.getJobGroups();
            gvGroups.DataSource = null;
            gvGroups.DataBind();
            gvGroups.DataSource = allGroups;
            gvGroups.DataBind();
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "MyFunction()", false);
            ddlGroups.DataSource     = allGroups;
            ddlGroups.DataTextField  = "JobGroupTitle";
            ddlGroups.DataValueField = "JobGroupID";
            ddlGroups.DataBind();
            ddlGroups.Items.Insert(0, new ListItem("همه زیر گروه ها", "0"));
            JobRepository jobs = new JobRepository();

            gvSubGroups.DataSource = jobs.getAllJobsByGroupID();
            gvSubGroups.DataBind();
            ddlgroupsForModal.DataSource     = allGroups;
            ddlgroupsForModal.DataTextField  = "JobGroupsTitle";
            ddlgroupsForModal.DataValueField = "JobGroupsID";
            ddlgroupsForModal.DataBind();
            ddlgroupsForModal.Items.Insert(0, new ListItem("یکی از گروه ها را انتخاب کنید", "0"));
            tbxNewGroup.Text = "";
        }
예제 #27
0
 public static void MarkJobAsFailed(Job job, string error)
 {
     using (var repo = new JobRepository())
     {
         repo.UpdateStateForJob(job, JobState.Failed, error);
     }
 }
예제 #28
0
        public void CalculateOutputFormYearJob_Failed()
        {
            var date = new DateTime(2019, 9, 1);

            var dbContext = TypiconDbContextFactory.Create();
            var jobRepo   = new JobRepository();
            var handler   = Build(dbContext, jobRepo);

            var job = new CalculateOutputFormWeekJob(1, 1, date);

            jobRepo.Create(job);

            var task = handler.ExecuteAsync(job);

            task.Wait();

            var queryProcessor = QueryProcessorFactory.Create();

            var week = queryProcessor.Process(new OutputWeekQuery(1, date, new OutputFilter()
            {
                Language = "cs-ru"
            }));

            Assert.AreEqual(false, week.Success);
        }
예제 #29
0
        public void CalculateDoesNotReserveTheLastFFmpegPluginForHighPriorityOnly()
        {
            var wfsPluginMock = CreateFFMpegMock("1");

            wfsPluginMock.SetupGet(p => p.Busy).Returns(false);
            wfsPluginMock.Setup(p => p.CheckAndEstimate(It.IsAny <ExecutionTask>())).Returns(true);

            var wfsPluginMock2 = CreateFFMpegMock("2");

            wfsPluginMock2.SetupGet(p => p.Busy).Returns(false);
            wfsPluginMock2.Setup(p => p.CheckAndEstimate(It.IsAny <ExecutionTask>())).Returns(true);
            var planner = new SimplePlanner(new List <IPlugin> {
                wfsPluginMock.Object, wfsPluginMock2.Object
            }, JobRepository, Logging, _callBackService.Object);

            var jobMedium = CreateNewFFMpegJob();

            jobMedium.Priority = Priority.medium;
            JobRepository.Add(jobMedium);

            var jobLow = CreateNewFFMpegJob();

            jobLow.Priority = Priority.low;
            JobRepository.Add(jobLow);
            planner.Calculate();

            Assert.That(JobRepository.WaitingJobs().Count(), Is.EqualTo(0));
            Assert.That(JobRepository.ActiveJobs().Count(), Is.EqualTo(2));
        }
예제 #30
0
        public void PlannerUsesRenamePluginIfDestinationEssenceFilenameIsPresent()
        {
            var wfsPluginMock = CreateWfsMock("1");

            wfsPluginMock.SetupGet(p => p.Busy).Returns(false);
            wfsPluginMock.Setup(p => p.CheckAndEstimate(It.IsAny <ExecutionTask>())).Returns(true);
            var fileRenamerPluginMock = CreateFileRenamerMock("1");

            fileRenamerPluginMock.SetupGet(p => p.Busy).Returns(false);
            fileRenamerPluginMock.Setup(p => p.CheckAndEstimate(It.IsAny <ExecutionTask>())).Returns(true);

            var planner = new SimplePlanner(new List <IPlugin> {
                wfsPluginMock.Object, fileRenamerPluginMock.Object
            }, JobRepository, Logging, _callBackService.Object);
            var job = CreateNewWfsJob();

            job.Destination.Files = new List <EssenceFile> {
                EssenceFile.Template("NewName_%index%.%ext%")
            };
            var jobUrn = job.Urn;

            JobRepository.Add(job);
            planner.Calculate();
            Assert.That(JobRepository.Get(jobUrn).Plan.Tasks.Count, Is.EqualTo(2));
            Assert.That(JobRepository.Get(jobUrn).Plan.Tasks[1].PluginUrn, Is.EqualTo(fileRenamerPluginMock.Object.Urn));
        }
예제 #31
0
        public void Finished(int jobId)
        {
            JobRepository repo = new JobRepository(_connectionString);

            repo.Finished(jobId);
            Clients.All.SendAsync("FinishedJob", new { JobId = jobId });
        }
예제 #32
0
        /// <summary>
        /// Given a step and configuration, return true if the step should start,
        /// false if it should not, and throw an exception if the job should finish.
        /// </summary>
        /// <param name="lastStepExecution"></param>
        /// <param name="jobExecution"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        /// <exception cref="JobRestartException">&nbsp;</exception>
        /// <exception cref="StartLimitExceededException">&nbsp;</exception>
        protected bool ShouldStart(StepExecution lastStepExecution, JobExecution jobExecution, IStep step)
        {
            var stepStatus = lastStepExecution == null ? BatchStatus.Starting : lastStepExecution.BatchStatus;

            if (stepStatus == BatchStatus.Unknown)
            {
                throw new JobRestartException("Cannot restart step from UNKNOWN status. "
                                              + "The last execution ended with a failure that could not be rolled back, "
                                              + "so it may be dangerous to proceed. Manual intervention is probably necessary.");
            }

            if (stepStatus == BatchStatus.Completed &&
                (step.AllowStartIfComplete != null && !step.AllowStartIfComplete.Value) ||
                stepStatus == BatchStatus.Abandoned)
            {
                // step is complete, false should be returned, indicating that the
                // step should not be started
                Logger.Info("Step already complete or not restartable, so no action to execute: {0}", lastStepExecution);
                return(false);
            }

            if (JobRepository.GetStepExecutionCount(jobExecution.JobInstance, step.Name) < step.StartLimit)
            {
                // step start count is less than start max, return true
                return(true);
            }
            else
            {
                // start max has been exceeded, throw an exception.

                throw new StartLimitExceededException(
                          string.Format("Maximum start limit exceeded for step: {0} StartMax: {1}",
                                        step.Name, step.StartLimit));
            }
        }
예제 #33
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["adminid"] != null)
            {
                if (!IsPostBack)
                {
                    JobGroupsRepository repGP     = new JobGroupsRepository();
                    JobRepository       jobs      = new JobRepository();
                    DataTable           allGroups = new DataTable();
                    allGroups           = repGP.getJobGroups();
                    gvGroups.DataSource = allGroups;
                    gvGroups.DataBind();
                    ddlGroups.DataSource     = allGroups;
                    ddlGroups.DataTextField  = "JobGroupTitle";
                    ddlGroups.DataValueField = "JobGroupID";
                    ddlGroups.DataBind();
                    ddlGroups.Items.Insert(0, new ListItem("همه زیر گروه ها", "0"));

                    gvSubGroups.DataSource = jobs.getAllJobsByGroupID();
                    gvSubGroups.DataBind();
                    ddlgroupsForModal.DataSource     = jobs.getAllJobsByGroupID();
                    ddlgroupsForModal.DataTextField  = "JobTitle";
                    ddlgroupsForModal.DataValueField = "JobID";
                    ddlgroupsForModal.DataBind();
                    ddlgroupsForModal.Items.Insert(0, new ListItem("یکی از گروه ها را انتخاب کنید", "0"));
                }
            }
            else
            {
                Response.Redirect("/AdminLogin");
            }
        }
예제 #34
0
 public JobModel GetJobByEmployeeId(string employeeId)
 {
     //unitOfWork.StartTransaction();
     JobRepository repo = new JobRepository(unitOfWork);
     JobModel jobModel = new JobModel();
     Job job = new Job();
     AutoMapper.Mapper.Map(jobModel, job);
     job = repo.GetAll().Where(x => x.EmployeeId == employeeId).FirstOrDefault();
     //unitOfWork.Commit();
     AutoMapper.Mapper.Map(job, jobModel);
     return jobModel;
 }
예제 #35
0
 public List<JobModel> GetCompletedJobListByServiceProviderId(string serviceProviderId)
 {
     //unitOfWork.StartTransaction();
     JobRepository repo = new JobRepository(unitOfWork);
     List<JobModel> jobModelList = new List<JobModel>();
     List<Job> job = new List<Job>();
     AutoMapper.Mapper.Map(jobModelList, job);
     job = repo.GetAll().Where(x => x.ServiceProviderId == serviceProviderId && x.Status==JobStatus.Completed).OrderByDescending(x=>x.JobId).ToList();
     //unitOfWork.Commit();
     AutoMapper.Mapper.Map(job, jobModelList);
     return jobModelList;
 }
예제 #36
0
 public List<JobModel> GetAllJobs()
 {
     //unitOfWork.StartTransaction();
     JobRepository repo = new JobRepository(unitOfWork);
     List<JobModel> jobModelList = new List<JobModel>();
     List<Job> jobList = new List<Job>();
     AutoMapper.Mapper.Map(jobModelList, jobList);
     jobList = repo.GetAllIncluding("ServiceProvider").Where(x=>x.IsPaid==true).OrderByDescending(x=>x.JobId).ToList();
     //unitOfWork.Commit();
     AutoMapper.Mapper.Map(jobList, jobModelList);
     return jobModelList;
 }
예제 #37
0
 public bool CheckExistance(int jobId)
 {
     //unitOfWork.StartTransaction();
     JobRepository repo = new JobRepository(unitOfWork);
     var job = repo.GetAll().Where(x => x.JobId == jobId).Count();
     //unitOfWork.Commit();
     if (job > 0)
     {
         return true;
     }
     else
     {
         return false;
     }
 }
예제 #38
0
파일: Program.cs 프로젝트: c0d3m0nky/mty
        static void CoBProcess()
        {
            Database.SetInitializer<OenContext>(null);
            var oenContext = new OenContext();
            var heatContext = new HotmailHeatContext();
            var settings = new CancelOnBulkingSettings(oenContext);
            var logger = new Logger();
            var heatTestGen = new HeatDataFaking(oenContext, heatContext, logger);
#if DEBUG
            var emails = new string[] { "*****@*****.**" };
#else
            var emails = settings.NotifyEmails;
#endif
            var jobRepository = new JobRepository(oenContext, logger, true);
            var CoB = new CancelOnBulking(logger,
                                          new MtaAgent(logger, true),
                                          new EmailNotification(logger, jobRepository, emails, settings.SmtpServer),
                                          oenContext,
                                          new EventRepository(oenContext),
                                          jobRepository
                                          );

            heatTestGen.GenerateData(settings.RunIntervalMinutes);

            try
            {
                var nextReset = DateTime.Today.Add(settings.ResetTime);

                if (nextReset < DateTime.Now)
                {
                    nextReset = nextReset.AddDays(1);
                }
                CoB.FindAndCancelBulkingCampaigns(new PmtaRepository(oenContext),
                                                    new DeliveryGroupRepository(oenContext),
                                                    new HeatDataRepository(oenContext, heatContext),
                                                    settings.RunIntervalMinutes,
                                                    settings.MinimumRecords,
                                                    settings.MinimumInboxing,
                                                    nextReset
                                                    );
            }
            catch (Exception ex)
            {

                logger.Error(ex.UnwrapForLog(true));
            }
        }
예제 #39
0
    private void BindData()
    {
        FillDropDownListData();
        btnPreview.Visible = (Request.QueryString["JobId"] != null);

        if (!string.IsNullOrEmpty(Request.QueryString["JobId"])) //edit
        {
            Job currentJob = new JobRepository().FindOne(new Job(Int32.Parse(Request.QueryString["JobId"])));
            if (currentJob != null)
            {
                SessionManager.CurrentJob = currentJob;
                txtJobRef.Text = currentJob.JobID.ToString();
                txtNumberOfApplications.Text = currentJob.NrOfApplications.HasValue ? currentJob.NrOfApplications.Value.ToString() : "0";
                txtNumberOfVisits.Text = currentJob.NrOfVisites.HasValue ? currentJob.NrOfVisites.Value.ToString() : "0";
                calLastModif.SelectedDate = currentJob.LastModifiedDate;

                ddlProfile.SelectedValue = currentJob.ProfileID.HasValue ? currentJob.ProfileID.Value.ToString() : "";
                ddlLocation.SelectedValue = currentJob.Location;
                ddlResponsible.SelectedValue = currentJob.CareerManager;
                ddlCompany.SelectedValue = currentJob.CompanyID.HasValue ? currentJob.CompanyID.Value.ToString() : "";
                ddlFunction.SelectedValue = currentJob.FamilyFunctionID;
                calActivatedDate.SelectedDate = currentJob.ActivatedDate;
                calExpiredDate.SelectedDate = currentJob.ExpiredDate;
                calRemindDate.SelectedDate = currentJob.RemindDate;
                txtURL.Text = currentJob.URL;
                chkIsActive.Checked = currentJob.IsActive;
                chkIsConfidential.Checked = currentJob.IsConfidential.HasValue ? currentJob.IsConfidential.Value : false;
                //
                rdoSelectEmail.Checked = !string.IsNullOrEmpty(currentJob.CareerManagerEmail);
                rdoSelectURL.Checked = !string.IsNullOrEmpty(currentJob.URL);
                //
                txtEmail.Text = currentJob.CareerManagerEmail;
                txtURL.Text = currentJob.URL;

                txtTitle.Text = currentJob.Title;
                txtTitleNL.Text = currentJob.Title_NL;
                txtTitleEN.Text = currentJob.Title_EN;
                btnPreview.OnClientClick = string.Format("return onButtonPreview_ClientClick('{0}');", WebConfig.NeosJobDetailURL + currentJob.JobID);
                //show title
                lblJobProfileTitle.Text = currentJob.Title;
            }

            if (Request.QueryString["mode"] == "view")
            {
                EnableControls(false);
            }
            else
                EnableControls(true);
        }
        else
        {
            ddlResponsible.SelectedValue = SessionManager.CurrentUser.UserID;
            EnableControls(true);

            //show title
            lblJobProfileTitle.Text = ResourceManager.GetString("lblRightPaneAddNewJob");
        }
        if (!string.IsNullOrEmpty(Request.QueryString["CompanyID"]))
        {
            ddlCompany.SelectedValue = Request.QueryString["CompanyID"];
            lnkBackToCompany.NavigateUrl = string.IsNullOrEmpty(Request.UrlReferrer.PathAndQuery) ? Request.UrlReferrer.PathAndQuery : string.Format("~/CompanyProfile.aspx?CompanyId={0}&tab=job&mode=edit", Request.QueryString["CompanyID"]);
        }
    }
예제 #40
0
 public JobModel GetJobById(int jobId)
 {
     //unitOfWork.StartTransaction();
     JobRepository repo = new JobRepository(unitOfWork);
     JobModel jobModel = new JobModel();
     Job job = new Job();
     AutoMapper.Mapper.Map(jobModel, job);
     job = repo.GetAllIncluding("ServiceProvider").Where(x => x.JobId == jobId).OrderByDescending(x=>x.JobId).FirstOrDefault();
     //unitOfWork.Commit();
     AutoMapper.Mapper.Map(job, jobModel);
     return jobModel;
 }
예제 #41
0
 protected void OnCompanyJobGridNeedDataSource(object source, GridNeedDataSourceEventArgs e)
 {
     List<Job> jobList = new JobRepository().GetJobsOfCompany(Convert.ToInt32(Request.QueryString["CompanyId"]));
     CompanyJobGrid.DataSource = jobList;
 }
예제 #42
0
 private void BindJobGrid(Company company)
 {
     if (company != null)
     {
         List<Job> jobList = new JobRepository().GetJobsOfCompany(company.CompanyID);
         CompanyJobGrid.DataSource = jobList;
         CompanyJobGrid.DataBind();
     }
 }
예제 #43
0
 public JobService(JobRepository jobRepo, UserRepository userRepo, ProjectRepository projectRepo)
 {
     _jobRepo = jobRepo;
     _userRepo = userRepo;
     _projectRepo = projectRepo;
 }
예제 #44
0
파일: Program.cs 프로젝트: c0d3m0nky/mty
        static void CoBReset()
        {
            Database.SetInitializer<OenContext>(null);
            var oenContext = new OenContext();
            var heatContext = new HotmailHeatContext();
            var settings = new CancelOnBulkingSettings(oenContext);
            var logger = new Logger();
#if DEBUG
            var emails = new string[] { "*****@*****.**" };
#else
            var emails = settings.NotifyEmails;
#endif
            var jobRepository = new JobRepository(oenContext, logger, true);
            var CoB = new CancelOnBulking(logger,
                                          new MtaAgent(logger, true),
                                          new EmailNotification(logger, jobRepository, emails, settings.SmtpServer),
                                          oenContext,
                                          new EventRepository(oenContext),
                                          jobRepository
                                          );

            try
            {
                CoB.ResumeMtaQueues();
            }
            catch (Exception ex)
            {
                logger.Error(ex.UnwrapForLog(true));
            }
        }
예제 #45
0
파일: Program.cs 프로젝트: c0d3m0nky/mty
        static void F21Reset()
        {
            Database.SetInitializer<OenContext>(null);
            var oenContext = new OenContext();
            var logger = new Logger();
            var jobRepository = new JobRepository(oenContext, logger, true);
            var settings = new Four21Settings(oenContext);
#if DEBUG
            var emailNotify = new EmailNotification(logger, jobRepository, new string[] { "*****@*****.**" }, settings.SmtpServer);
#else
            var emailNotify = new EmailNotification(logger, jobRepository, settings.NotifyEmails, settings.SmtpServer);
#endif
            var f21 = new Four21(logger,
                                 new MtaAgentMock(0, logger),
                                 emailNotify,
                                 () => new OenContext(),
                                 u => new EventRepository((OenContext) u),
                                 u => new PmtaRepository((OenContext) u),
                                 u => new DeliveryGroupRepository((OenContext) u),
                                 u => new JobRepository((OenContext) u, logger, true)
                                 );

            try
            {
                f21.ResumeQueues(DateTime.Now);
            }
            catch (Exception ex)
            {
                logger.Error(ex.UnwrapForLog(true));
            }
        }
예제 #46
0
        /// <summary>
        /// Helper function used for opening a runspace
        /// </summary>
        private void DoOpenHelper()
        {
            // NTRAID#Windows Out Of Band Releases-915851-2005/09/13
            if (_disposed)
            {
                throw PSTraceSource.NewObjectDisposedException("runspace");
            }

            bool startLifeCycleEventWritten = false;
            s_runspaceInitTracer.WriteLine("begin open runspace");
            try
            {
                _transcriptionData = new TranscriptionData();

                if (InitialSessionState != null)
                {
                    // All ISS-based configuration of the engine itself is done by AutomationEngine,
                    // which calls InitialSessionState.Bind(). Anything that doesn't
                    // require an active and open runspace should be done in ISS.Bind()
                    _engine = new AutomationEngine(Host, null, InitialSessionState);
                }
                else
                {
                    _engine = new AutomationEngine(Host, RunspaceConfiguration, null);
                }
                _engine.Context.CurrentRunspace = this;

                //Log engine for start of engine life
                MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Available);
                startLifeCycleEventWritten = true;

                _commandFactory = new CommandFactory(_engine.Context);
                _history = new History(_engine.Context);
                _jobRepository = new JobRepository();
                _jobManager = new JobManager();
                _runspaceRepository = new RunspaceRepository();

                s_runspaceInitTracer.WriteLine("initializing built-in aliases and variable information");
                InitializeDefaults();
            }
            catch (Exception exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
                s_runspaceInitTracer.WriteLine("Runspace open failed");

                //Log engine health event
                LogEngineHealthEvent(exception);

                //Log engine for end of engine life
                if (startLifeCycleEventWritten)
                {
                    Dbg.Assert(_engine.Context != null, "if startLifeCycleEventWritten is true, ExecutionContext must be present");
                    MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped);
                }

                //Open failed. Set the RunspaceState to Broken.
                SetRunspaceState(RunspaceState.Broken, exception);

                //Raise the event
                RaiseRunspaceStateEvents();

                //Rethrow the exception. For asynchronous execution, 
                //OpenThreadProc will catch it. For synchronous execution
                //caller of open will catch it.
                throw;
            }

            SetRunspaceState(RunspaceState.Opened);
            RunspaceOpening.Set();

            //Raise the event
            RaiseRunspaceStateEvents();
            s_runspaceInitTracer.WriteLine("runspace opened successfully");

            // Now do initial state configuration that requires an active runspace
            if (InitialSessionState != null)
            {
                Exception initError = InitialSessionState.BindRunspace(this, s_runspaceInitTracer);
                if (initError != null)
                {
                    // Log engine health event
                    LogEngineHealthEvent(initError);

                    // Log engine for end of engine life
                    Debug.Assert(_engine.Context != null,
                                "if startLifeCycleEventWritten is true, ExecutionContext must be present");
                    MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped);

                    // Open failed. Set the RunspaceState to Broken.
                    SetRunspaceState(RunspaceState.Broken, initError);

                    // Raise the event
                    RaiseRunspaceStateEvents();

                    // Throw the exception. For asynchronous execution, 
                    // OpenThreadProc will catch it. For synchronous execution
                    // caller of open will catch it.
                    throw initError;
                }
            }

            TelemetryAPI.ReportLocalSessionCreated(InitialSessionState, TranscriptionData);
        }
예제 #47
0
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (_disposed)
                {
                    return;
                }
                lock (SyncRoot)
                {
                    if (_disposed)
                    {
                        return;
                    }

                    _disposed = true;
                }

                if (disposing)
                {
                    Close();
                    _engine = null;
                    _history = null;
                    _transcriptionData = null;
                    _jobManager = null;
                    _jobRepository = null;
                    _runspaceRepository = null;
                    if (RunspaceOpening != null)
                    {
                        RunspaceOpening.Dispose();
                        RunspaceOpening = null;
                    }

                    // Dispose the event manager
                    if (this.ExecutionContext != null && this.ExecutionContext.Events != null)
                    {
                        try
                        {
                            this.ExecutionContext.Events.Dispose();
                        }
                        catch (ObjectDisposedException)
                        {
                            ;
                        }
                    }
                }
            }
            finally
            {
                base.Dispose(disposing);
            }
        }
예제 #48
0
 public JobService(JobRepository jobRepo)
 {
     _jobRepo = jobRepo;
 }
예제 #49
0
 public JobController()
 {
     this.repo = new JobRepository();
 }
예제 #50
0
        private CancelOnBulking GetNewCancelOnBulking(OenContext oenContext, CancelOnBulkingSettings settings)
        {
            var logger = new Logger("COB");
            var jobRepository = new JobRepository(oenContext, logger, settings.DatabaseTestMode);
#if DEBUG
            var mta = new PmtaMonitoring.Testing.Mocking.MtaAgentMock(0, logger);
#else
            var mta = new MtaAgent(logger, settings.MtaTestMode);
#endif

            return new CancelOnBulking(logger,
                                       mta,
                                       new EmailNotification(logger, jobRepository, settings.NotifyEmails, settings.SmtpServer),
                                       oenContext,
                                       new EventRepository(oenContext),
                                       jobRepository
                                       );
        }
예제 #51
0
 public JobModel SaveJob(JobModel model)
 {
     //unitOfWork.StartTransaction();
     JobRepository repo = new JobRepository(unitOfWork);
     Job job = new Job();
     AutoMapper.Mapper.Map(model, job);
     repo.Insert(job);
     //unitOfWork.Commit();
     AutoMapper.Mapper.Map(job, model);
     return model;
 }
예제 #52
0
 public EmployeeJobFactory(DataManager dm)
 {
     _employee = new EmployeeRepository(dm);
     _job = new JobRepository(dm);
 }
예제 #53
0
        private bool MissingSharedResources()
        {
            try
            {
                _logger.Info("Checking resources");
                var oen = new OenContext();
                var coBSettings = new CancelOnBulkingSettings(oen);
                var f21Settings = new Four21Settings(oen);
                var jobRepository = new JobRepository(new OenContext(), _logger, true);

                if (!new EmailNotification(_logger, jobRepository, coBSettings.NotifyEmails.Union(f21Settings.NotifyEmails), coBSettings.SmtpServer).EmailNotificationResourcesAvailable())
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                _logger.Error(ex.UnwrapForLog(true));
                return true;
            }
        }
예제 #54
0
    protected void OnGridJobs_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "delete")
        {
            int jobID = Int32.Parse(e.CommandArgument.ToString());
            JobRepository jobRepo = new JobRepository();
            jobRepo.Delete(new Job(jobID));

            gridJobs.Rebind();
        }
    }
예제 #55
0
    private Neos.Data.Job SaveJobInfo()
    {
        UserMessageRepository messageRepo = new UserMessageRepository();
        JobRepository jobRepo = new JobRepository();
        Neos.Data.Job job = new Neos.Data.Job();

        if (!string.IsNullOrEmpty(Request.QueryString["JobId"])) //edit
        {
            job = jobRepo.FindOne(new Job(Int32.Parse(Request.QueryString["JobId"])));
            if (job != null)
            {
                string responsibleUser = job.CareerManager;
                job = SetInfoForJob(job);
                jobRepo.Update(job);

                if (responsibleUser != ddlResponsible.SelectedValue) // in case select another responsible user
                {
                    if (job.RemindDate.HasValue && job.ExpiredDate.HasValue)
                    {
                        UserMessage message = messageRepo.FindMessagesByRef(job.JobID.ToString());
                        if (message != null)
                        {
                            message.UserID = job.CareerManager;
                            messageRepo.Update(message);
                        }
                    }
                }
            }
        }
        else //edit
        {
            job = SetInfoForJob(job);
            job.CreatedDate = DateTime.Now;
            jobRepo.Insert(job);
            //insert a notification message
            if (job.RemindDate.HasValue && job.ExpiredDate.HasValue)
            {
                UserMessage message = new UserMessage();
                message.UserID = ddlResponsible.SelectedValue;
                message.Type = UserMessageType.JobResponsibility;
                message.Subject = ResourceManager.GetString("message.JobReminderSubject");
                message.MessageContent = string.Format(ResourceManager.GetString("message.JobReminderContent"), job.ExpiredDate.Value.ToString("dd/MM/yyyy hh:mm tt"), "JobProfile.aspx?JobId=" + job.JobID);
                message.RemindDate = job.RemindDate;
                message.CreatedDate = DateTime.Now;
                message.IsUnread = true;
                message.RefID = job.JobID.ToString();
                messageRepo.Insert(message);
            }
        }
        return job;
    }
예제 #56
0
        public JobModel UpadteJob(JobModel model)
        {
            //unitOfWork.StartTransaction();
            JobRepository repo = new JobRepository(unitOfWork);
            Job job = new Job();
            job = repo.GetAll().Where(x => x.JobId == model.JobId).FirstOrDefault();
            AutoMapper.Mapper.Map(model, job);
            repo.Update(job);
            //unitOfWork.Commit();
            AutoMapper.Mapper.Map(job, model);

            return model;
        }
예제 #57
0
    private List<Job> DoSearch()
    {
        List<Job> list = new List<Job>();
        string mode = "recent";
        if (!string.IsNullOrEmpty(Request.QueryString["mode"]))
        {
            mode = Request.QueryString["mode"];
        }
        if (mode == "recent")
        {
            list = new JobRepository().GetTopJobs(gridJobs.PageSize);
            return list;
        }
        JobSearchCriteria criteria = new JobSearchCriteria();
        switch (mode)
        {
            case "active":
                criteria.Active = "Yes";
                break;
            case "inactive":
                criteria.Active = "No";
                break;
            case "all":
                break;
            case "search":
                if (!string.IsNullOrEmpty(Request.QueryString["title"]))
                    criteria.Title = Request.QueryString["title"];
                if (!string.IsNullOrEmpty(Request.QueryString["active"]))
                    criteria.Active = Request.QueryString["active"];
                if (!string.IsNullOrEmpty(Request.QueryString["createdMin"]))
                    criteria.CreatedDateFrom = DateTime.ParseExact(Request.QueryString["createdMin"], "dd/MM/yyyy",
                                System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
                if (!string.IsNullOrEmpty(Request.QueryString["createdMax"]))
                    criteria.CreatedDateTo = DateTime.ParseExact(Request.QueryString["createdMax"], "dd/MM/yyyy",
                                System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
                if (!string.IsNullOrEmpty(Request.QueryString["activatedMin"]))
                    criteria.ActivatedDateFrom = DateTime.ParseExact(Request.QueryString["activatedMin"], "dd/MM/yyyy",
                                System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
                if (!string.IsNullOrEmpty(Request.QueryString["activatedMax"]))
                    criteria.ActivatedDateTo = DateTime.ParseExact(Request.QueryString["activatedMax"], "dd/MM/yyyy",
                                System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
                if (!string.IsNullOrEmpty(Request.QueryString["expiredMin"]))
                    criteria.ExpiredDateFrom = DateTime.ParseExact(Request.QueryString["expiredMin"], "dd/MM/yyyy",
                                System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
                if (!string.IsNullOrEmpty(Request.QueryString["expiredMax"]))
                    criteria.ExpiredDateTo = DateTime.ParseExact(Request.QueryString["expiredMax"], "dd/MM/yyyy",
                                System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);

                if (!string.IsNullOrEmpty(Request.QueryString["profile"]))
                    criteria.ProfileID = int.Parse(Request.QueryString["profile"]);
                if (!string.IsNullOrEmpty(Request.QueryString["functionFam"]))
                    criteria.FunctionFam = Request.QueryString["functionFam"];
                if (!string.IsNullOrEmpty(Request.QueryString["location"]))
                    criteria.Locations = Request.QueryString["location"].Split(';');
                if (!string.IsNullOrEmpty(Request.QueryString["responsible"]))
                    criteria.Responsible = Request.QueryString["responsible"];
                if (!string.IsNullOrEmpty(Request.QueryString["company"]))
                    criteria.ComName = Request.QueryString["company"];
                break;
        }
        list = new JobRepository().SearchJobs(criteria);

        return list;
    }
 public JobOverviewRestStore()
 {
     _repository = new JobRepository();
 }
예제 #59
0
 public IHttpActionResult RemoveBookmark([FromBody] RemoveJobViewModel model)
 {
     try
     {
         JobRepository jobRepo = new JobRepository();
         jobRepo.RemoveBookmark(model.job, model.user);
         return Ok();
     }
     catch (Exception ex)
     {
         return BadRequest(ex.Message);
     }
 }
예제 #60
0
 public List<JobModel> Paging(PagingModel model)
 {
     //unitOfWork.StartTransaction();
     JobRepository repo = new JobRepository(unitOfWork);
     List<JobModel> jobModelList = new List<JobModel>();
     List<Job> jobList = new List<Job>();
     //ResponseMessage responseMessage = new ResponseMessage();
     //PagingInfo Info = new PagingInfo();
     string searchparam = model.SearchText == null ? "" : model.SearchText;
     jobList = repo.GetAll().Where(x => x.Description.ToLower().Contains(searchparam.ToLower())).OrderByDescending(x=>x.JobId).ToList();
     //unitOfWork.Commit();
     AutoMapper.Mapper.Map(jobList, jobModelList);
     return jobModelList;
 }