public async Task <WorkResult> DeleteAllPages(CancellationToken cancellationToken) { List <Page> pages = await UnitOfWork.PageRepository.GetAll(cancellationToken); if (pages == null || pages.Count == 0) { return(WorkResult.Failed("Page cannot be null or empty")); } try { foreach (var page in pages) { UnitOfWork.PageRepository.Remove(page); } int result = await UnitOfWork.SaveChanges(cancellationToken); if (result > 0) { return(WorkResult.Success()); } return(WorkResult.Failed("SaveChanges returned 0")); } catch (Exception ex) { return(WorkResult.Failed(ex.Message)); } }
public override async Task <WorkResult> Delete(CancellationToken cancellationToken, string userName) { if (!string.IsNullOrEmpty(userName)) { return(WorkResult.Failed("Wrong param.Entity is null")); } try { // Check is userId owned Admin User user = await UnitOfWork.UserRepository.FindByUserName(cancellationToken, userName); if (user.Admin != null) { UnitOfWork.UserRepository.Remove(user); int result = await UnitOfWork.SaveChanges(cancellationToken); if (result > 0) { return(WorkResult.Success()); } return(WorkResult.Failed("SaveChanges returned result 0")); } return(WorkResult.Failed("userId isn't owned by Admin")); } catch (Exception ex) { return(WorkResult.Failed(ex.Message)); } }
protected override Object DoInBackground(params Object[] @params) { var result = new WorkResult { Inserted = 0, Completed = false }; try { var query = new PendingRecurringTransactionsQuery(); var pendingTransactions = Database.ExecuteAsync(query).GetAwaiter().GetResult(); if (pendingTransactions.Any()) { var command = new BatchInsertTransactionsCommand(pendingTransactions); result.Inserted = Database.ExecuteAsync(command).GetAwaiter().GetResult(); } result.Completed = true; } catch (Exception e) { System.Diagnostics.Debug.WriteLine($"Failed to run recurring transactions job: {e.Message}"); } return(result); }
public async Task <WorkResult> RemoveQuestion(CancellationToken cancellationToken, Question question, Page page) { if ((question == null) || (page == null)) { return(WorkResult.Failed("Page or question cannot be null")); } try { if (page.Questions.Contains(question)) { page.Questions.Remove(question); int result = await UnitOfWork.SaveChanges(cancellationToken); if (result > 0) { return(WorkResult.Success()); } return(WorkResult.Failed("SaveChanges returned 0")); } return(WorkResult.Failed("Current page hold this question")); } catch (Exception ex) { return(WorkResult.Failed(ex.Message)); } }
public override async Task <WorkResult> Delete(CancellationToken cancellationToken, Guid userId) { if (userId == Guid.Empty) { return(WorkResult.Failed("Wrong param.Entity is null")); } try { // Check is userId owned Admin Admin admin = await UnitOfWork.AdminRepository.FindById(cancellationToken, userId); if (admin != null) { UnitOfWork.UserRepository.Remove(admin.User); int result = await UnitOfWork.SaveChanges(cancellationToken); if (result > 0) { return(WorkResult.Success()); } return(WorkResult.Failed("SaveChanges returned result 0")); } return(WorkResult.Failed("userId isn't owned by Admin")); } catch (Exception ex) { return(WorkResult.Failed(ex.Message)); } }
public override async Task <WorkResult> Delete(string userName) { if (userName == null) { return(WorkResult.Failed("Wrong param.Entity is null")); } try { // Check is userId owned by Employer User user = await UnitOfWork.UserRepository.FindByUserName(userName); if (user.Employer != null) { UnitOfWork.UserRepository.Remove(user); int result = await UnitOfWork.SaveChanges(); if (result > 0) { return(WorkResult.Success()); } return(WorkResult.Failed("SaveChanges returned result 0")); } return(WorkResult.Failed("userId isn't owned by Employer")); } catch (Exception ex) { return(WorkResult.Failed(ex.Message)); } }
public async Task <WorkResult> AddAnswer(Answer answer, Question question) { if ((question == null) || (answer == null)) { return(WorkResult.Failed("Answer or question cannot be null")); } try { if (!question.Answers.Contains(answer)) { question.Answers.Add(answer); int result = await UnitOfWork.SaveChanges(); if (result > 0) { return(WorkResult.Success()); } return(WorkResult.Failed("SaveChanges returned 0")); } return(WorkResult.Failed("Current question hold this answer")); } catch (Exception ex) { return(WorkResult.Failed(ex.Message)); } }
public async Task <WorkResult> RemoveAnswer(CancellationToken cancellationToken, Answer answer, Question question) { if ((question == null) || (answer == null)) { return(WorkResult.Failed("Answer or question cannot be null")); } try { if (question.Answers.Contains(answer)) { question.Answers.Remove(answer); int result = await UnitOfWork.SaveChanges(cancellationToken); if (result > 0) { return(WorkResult.Success()); } return(WorkResult.Failed("SaveChanges returned 0")); } return(WorkResult.Failed("Current question not have this answer")); } catch (Exception ex) { return(WorkResult.Failed(ex.Message)); } }
/// <summary> /// Send mails with reports to recievers /// </summary> /// <returns>Operation result</returns> public async Task <WorkResult> SendMailsToRecieversAsync() { if (_employee == null || _pages == null || _pages.Count == 0) { return(WorkResult.Failed("Params are not valid.")); } byte[] pdfReport, wordReport; Document pdf, docx; try { pdf = new PdfDocument(_pages, _employee); docx = new WordDocument(_pages, _employee); pdfReport = pdf.GetDocument(); wordReport = docx.GetDocument(); } catch (Exception ex) { return(WorkResult.Failed(ex.ToString())); } if (pdfReport.Length == 0 && wordReport.Length == 0) { return(WorkResult.Failed("Length of file is 0")); } return(await SendMailsAsync(wordReport, docx.Name, pdfReport, pdf.Name)); }
//завершаем операцию, записываем дату завершения и добавляем итоги операции в массив public void AddAction(ActionResult ar) { ar.StopAction(); innerResults.Add(ar); this.resultsByTypes[ar.actType].MergeResults(ar); this.globalWorkRes = ActionResult.CompareTwoResults(this.globalWorkRes, ar.result); }
public override async Task <WorkResult> Delete(Advisor entity) { if (entity != null) { return(await Delete(entity.AdvisorId)); } return(WorkResult.Failed("Admin cannot be null")); }
public override async Task <WorkResult> Delete(CancellationToken cancellationToken, Admin entity) { if (entity != null) { return(await Delete(cancellationToken, entity.AdminId)); } return(WorkResult.Failed("Admin cannot be null")); }
public void AddInnerController(ResultController rc) { this.innerControllers.Add(rc); this.globalWorkRes = ActionResult.CompareTwoResults(this.globalWorkRes, rc.globalWorkRes); foreach (KeyValuePair <ActionType, ActionResult> resTypes in rc.resultsByTypes) { this.resultsByTypes[resTypes.Key].MergeResults(resTypes.Value); } }
public void UpdateTestMethod(WorkResult work) { //arrange WorkResultCreator stCreator = (WorkResultCreator)factory.GetWorkResultCreator(); //act bool isUpdated = stCreator.Update(work); //assert Assert.IsTrue(isUpdated); }
public FileSupertypeFake(int _fileCount, int _bytesCount, WorkResult _res, bool _addAnError, ActionType _source_dest) { this.statistics.incrementBytes(_bytesCount); this.statistics.incrementFiles(_fileCount); this.statistics.addResult(_res); if (_addAnError) { this.statistics.addError("Test error"); } this.source_dest = _source_dest; }
public static bool IsResultIsNotError(WorkResult wr) { if (wr != WorkResult.Error) { return(true); } else { return(false); } }
public void ReadTestMethod() { //arrange WorkResult expected = new WorkResult(1, "8", 1, 1, 1, 1); //act WorkResultCreator stCreator = (WorkResultCreator)factory.GetWorkResultCreator(); WorkResult actual = stCreator.Read(1); //assert Assert.AreEqual(expected, actual); }
public static WorkResult CompareTwoResults(WorkResult retRes, WorkResult comparedRes) { if (comparedRes < retRes) { return(comparedRes); } else { return(retRes); } }
private WorkResult Handle <TCommand>(IValidatableCommandHandler <TCommand> handler, TCommand command) { WorkResult result = null; handler.Handle(command, validationErrorAction: exception => { result = new WorkResult(exception.ValidationResults); }); return(result ?? new WorkResult()); }
public void Start() { if (isValidated) { WorkResult result = WorkResult.OK; bool isError = false; try { _txtFileParser = new Parser(_arr); } catch (NullReferenceException) { isError = true; result = WorkResult.NullReferenceException; } catch (ArgumentException) { isError = true; result = WorkResult.ArgumentException; } catch (PathTooLongException) { isError = true; result = WorkResult.PathTooLongException; } catch (DirectoryNotFoundException) { isError = true; result = WorkResult.DirectoryNotFoundException; } catch (UnauthorizedAccessException) { isError = true; result = WorkResult.UnauthorizedAccessException; } catch (FileNotFoundException) { isError = true; result = WorkResult.FileNotFoundException; } int count = -1; if (!isError) { count = _txtFileParser.Start(); } if (_visualizator != null) { _visualizator.AnswerCatcher(result, count); } } }
public async Task <ActionResult> ChangeEmployeeName(EmployeeChangeNameViewModel employeeInfo) { if (!ModelState.IsValid || employeeInfo.Id == Guid.Empty) { return(View(employeeInfo)); } var employee = await adminManager.GetEmployee(employeeInfo.Id); string employeeOldName = employee.LastName + " " + employee.FirstName; if (employee != null) { employee.FirstName = employeeInfo.FirstName; employee.LastName = employeeInfo.LastName; employee.Prefix = employeeInfo.Prefix; WorkResult result = await adminManager.UpdateEmployee(employee); if (result.Succeeded) { var user = await employerManager.GetBaseUserByName(User.Identity.Name); var alert = new Alert(); { alert.AlertId = Guid.NewGuid(); alert.EmployerId = employee.EmployerId; alert.EmployeeId = employee.EmployeeId; alert.AlertType = AlertType.Employee_Rename; alert.AlertIsDeleted = false; alert.AlertCreateTS = DateTime.Now; alert.AlertUpdateTS = DateTime.Now; alert.UserId = user.UserId; }; await alertManager.CreateAsync(alert); var messageInfo = new ChangeEmployeeNameMessageBuilder( $"{employee.FirstName} {employee.Prefix} {employee.LastName}"); await mailingService.SendMailAsync(messageInfo.Body, messageInfo.Subject, employee.Employer.User.Email); return(RedirectToAction("EmployerProfile", new { id = employee.EmployerId })); } } ModelState.AddModelError("", SERVER_ERROR); return(View(employeeInfo)); }
public async Task <ActionResult> DeleteAdvisor(Guid?id) { var user = await GetUserIfAdvisorAsync(id); WorkResult result = await advisorManager.Delete(user.UserId); if (user != null && result.Succeeded) { return(View("Settings")); } return(RedirectToAction("Index")); }
public static IWorkResult <T> EnqueueWork <T>(WorkType type, Func <T> function) { var workResult = new WorkResult <T>(); var action = new Action(() => { var result = function.Invoke(); workResult.SetResult(result); }); WorkQueue.Enqueue(new WorkEntry(type, action)); return(workResult); }
public void AnswerCatcher(WorkResult masage, int count = -1) { string result = ""; switch (masage) { case WorkResult.OK: if (count >= 0) { result = string.Format("Found {0} occurrences of a given line", count); } else { result = "Done!!!"; } break; case WorkResult.NullReferenceException: result = "Transferred array or its elements have null references."; break; case WorkResult.ArgumentException: result = "Too many or few values passed."; break; case WorkResult.PathTooLongException: result = "The specified path, file name, or both exceed the maximum length."; break; case WorkResult.DirectoryNotFoundException: result = "The specified path is invalid"; break; case WorkResult.UnauthorizedAccessException: result = "The path parameter specifies a read-only file."; break; case WorkResult.FileNotFoundException: result = "The file specified by the path parameter was not found."; break; case WorkResult.NeedInstruction: result = "Run the program with parameters:\n1.<file path> <line to count>" + "- to count the number of occurrences\n2. < file path > < search " + "string> < replacement string> - to replace all occurrences"; break; } Console.WriteLine(result); Console.ReadKey(); }
private void backWorkerExec_DoWork(object sender, DoWorkEventArgs e) { var bw = sender as BackgroundWorker; var eExecType = (ExecType)e.Argument; var kWorkResult = new WorkResult(); kWorkResult.eFailedReason = EnumFailedReason.None; kWorkResult.Path = string.Empty; int nAll = listTargetFileInfos.Count; for (int i = 0; i < nAll; ++i) { // Cancellation if (bw != null && bw.CancellationPending) { e.Cancel = true; break; } // Exec var reason = ExecCropAnalize(eExecType, i, listTargetFileInfos[i].Name, listTargetFileInfos[i].Path); if (reason == EnumFailedReason.None) { if (bw != null) { int progress = (int)((float)i / (float)nAll * 100f); if (i + 1 == nAll) { progress = 100; } bw.ReportProgress(progress); Thread.Sleep(10); } } else { kWorkResult.eFailedReason = reason; kWorkResult.Path = listTargetFileInfos[i].Path; break; } } e.Result = kWorkResult; }
public async Task <WorkResult> CreateEmployee(Employee employee) { if (employee != null) { UnitOfWork.EmployerRepository.AddEmployee(employee); int result = await UnitOfWork.SaveChanges(); if (result > 0) { return(WorkResult.Success()); } return(WorkResult.Failed("SaveChanges returned result 0")); } return(WorkResult.Failed("Wrong param.Entity is null")); }
public async Task <WorkResult> UpdateEmployee(CancellationToken cancellationToken, Employee employee) { if (employee != null) { UnitOfWork.EmployeeRepository.Update(employee); int result = await UnitOfWork.SaveChanges(cancellationToken); if (result > 0) { return(WorkResult.Success()); } return(WorkResult.Failed("SaveChanges returned result 0")); } return(WorkResult.Failed("Wrong param.Entity is null")); }
public IWorkResult <TResult> Handle(Func <TWorkArgs> args, Action <IWorkResult <TResult> > uiAction, IWorkResult[] preWorkUnitList, WaitMode mode) { this.waitMode = mode; this.uiAction = uiAction; this.preWorkUnitList = preWorkUnitList; this.workResult.IsError = false; this.workResult.IsComplete = false; Task <IWorkResult <TResult> > task = new Task <IWorkResult <TResult> >( o => { TResult result = default(TResult); try { if (this.waitMode == WaitMode.Default || this.waitMode == WaitMode.Bll) { if (!WorkResult.Wait(this.preWorkUnitList)) { this.isSuccessPreWorkUnitList = false; return(this.workResult); } } result = this.work(args()); this.workResult.Result = result; } catch (DevException hsex) { this.workResult.IsError = true; this.workResult.HsufErrorNo = hsex.ErrorNo; this.workResult.ErrorMessage = hsex.Message; } catch (Exception exc) { this.workResult.IsError = true; this.workResult.ErrorMessage = exc.Message; } return(this.workResult); }, args); task.Start(); task.ContinueWith(this.UpdateUI); return(workResult); }
public static string ToRussianString(this WorkResult workResult) { switch (workResult) { case WorkResult.Late: return("Выполнено в срок"); case WorkResult.OnTime: return("Выполнено не в срок"); case WorkResult.None: return(""); default: throw new Exception($"No such value '{workResult}' in workResult enum"); } }
public async Task <WorkResult> AddPages(CancellationToken cancellationToken, IEnumerable <Page> pages) { if (pages == null) { return(WorkResult.Failed("Pages cannot be null")); } try { UnitOfWork.PageRepository.AddRange(pages); await UnitOfWork.SaveChanges(cancellationToken); return(WorkResult.Success()); } catch (Exception ex) { return(WorkResult.Failed(ex.Message)); } }