public ServiceResult CreatePost(PostCreateDto model) { var serviceResult = new ServiceResult(true); #region validation if (string.IsNullOrEmpty(model.Title)) { serviceResult.AddError("عنوان پست نمی تواند فاقد مقدار باشد"); } if (!string.IsNullOrEmpty(model.Title) && model.Title.Length > 128) { serviceResult.AddError("تعداد کاراکترهای عنوان پست نمی تواند بیش از 128 کاراکتر باشد".ToPersianNumbers()); } if (string.IsNullOrEmpty(model.PrimaryPicture)) { serviceResult.AddError("عکس اصلی پست نمی تواند فاقد مقدار باشد"); } #endregion if (serviceResult.IsSuccess) { var entity = model.ToEntity(); entity.CreateDate = DateTime.Now; _context.Posts.Add(entity); if (_context.SaveChanges() == 0) { serviceResult.AddError("در انجام عملیات خطایی رخ داد"); } } return(serviceResult); }
public async Task<IServiceResult> CreateProject(ProjectEditViewModel model) { var result = new ServiceResult<ProjectEditViewModel>(); try { var responsible = await userManager.FindByIdAsync(model.ResponsibleUserId); if(responsible == null) { result.AddError(m => m.ResponsibleUserId, "Ilyen felhasználó nem létezik"); } if(result.Succeeded) { var project = mapper.Map<Project>(model); project.Responsible = responsible; context.Projects.Add(project); await context.SaveChangesAsync(); } } catch (Exception e) { result.AddError("", e.Message); } return result; }
public async Task<IServiceResult> CreateProjectVersion(ProjectVersionEditViewModel model) { var result = new ServiceResult<ProjectVersionEditViewModel>(); try { var project = await ProjectStore.GetAll().Include(p => p.Versions).SingleOrDefaultAsync(p => p.Id == model.ProjectId); if (project == null) { result.AddError(m => m.ProjectId, "Ilyen azonosítóval nem létezik projekt!"); return result; } var version = Mapper.Map<ProjectVersionEditViewModel, ProjectVersion>(model); version.Project = project; await ProjectVersionStore.InsertAsync(version); } catch (Exception e) { Log.Error(e.Message, e); result.AddError("", e.Message); } return result; }
public ServiceResult CreateInstagramTag(string name) { var serviceResult = new ServiceResult(true); if (string.IsNullOrEmpty(name)) { serviceResult.AddError("آیدی نمی تواند فاقد مقدار باشد"); } if (!string.IsNullOrEmpty(name) && name.Length > 400) { serviceResult.AddError("تعداد کاراکترهای آیدی نمی تواند بیش از 400 کاراکتر باشد".ToPersianNumbers()); } if (serviceResult.IsSuccess) { _context.InstagramTags.Add(new InstagramTag { Name = name }); if (_context.SaveChanges() == 0) { serviceResult.AddError("در انجام عملیات خطایی رخ داد"); } } return(serviceResult); }
public async Task<ServiceResult> ChangeState(int issueId, IssueState newState) { var result = new ServiceResult(); try { //franc se tudja miért, de ha nincs ráincludeolva a project, elszáll a required miatt... var issue = await context.Issues.Include(i => i.Project).SingleOrDefaultAsync(i => i.Id == issueId); if (issue == null) { result.AddError("", "Nincs ilyen azonosítójú feladat."); return result; } issue.State = newState; await context.SaveChangesAsync(); } catch (Exception e) { result.AddError("", e.Message); } return result; }
public async Task <ServiceResult <PathInfo> > FindGreaterPath() { var sr = new ServiceResult <PathInfo>(); if (_triangle.Any() && _triangle.First().Any()) { bool isEven = _triangle.First().First() % 2 == 0; // first number var rowNo = 0; var index = 0; var pathResult = new List <int>(); await FindNext(rowNo, index, isEven, pathResult); if (!_greaterPath.Any()) { sr.AddError(ErrorKey.NoProperPathExists); } } else { sr.AddError(ErrorKey.NoDataProvided); } sr.Result = GetPathInfo(_greaterPath); return(sr); }
public async Task <ServiceResult> AddUserActivity(string userId, string operation, string text) { var result = new ServiceResult(); var user = _dbContext.Users.FirstOrDefaultAsync(r => r.Id == userId) .GetAwaiter() .GetResult(); if (user == null) { return(result.AddError(String.Empty, "User Not Found")); } try { var userActivity = new UserActivity() { UserId = userId, Operation = operation, Text = text }; _dbContext.UserActivities.Add(userActivity); await _dbContext.SaveChangesAsync(); } catch (Exception ex) { result.AddError(ex.GetBaseException().ToString(), ex.ToString()); await AddLogEntry(ex.GetBaseException().ToString(), ex.ToString()); } return(result); }
public async Task<IServiceResult> CreateIssue(IssueEditViewModel model) { var result = new ServiceResult<IssueEditViewModel>(); try { var project = await context.Projects.FindAsync(model.ProjectId); if(project == null) { result.AddError(m => m.ProjectId, "Ilyen projekt nem létezik"); return result; } var issue = mapper.Map<Issue>(model); issue.Project = project; issue.State = IssueState.New; context.Issues.Add(issue); await context.SaveChangesAsync(); } catch (Exception e) { result.AddError("", e.Message); } return result; }
public async Task <ServiceResult <string> > CreateShortCode(SourceUrlDto entity) { var result = new ServiceResult <string>(); try { Boolean isValid = true; try { entity.Url.ValidateUrl(); } catch (Exception) { result.AddError("", "Invalid Url"); isValid = false; } if (isValid) { var codeResult = await this.GenerateShortCode(entity); result.Response = codeResult.Code.ToString(); } return(result); } catch (Exception e) { result.AddError("", e.InnerException.ToString()); } return(result); }
public ServiceResult CreateSlideShow(SlideShowCreateDto model) { var serviceResult = new ServiceResult(true); #region validation if (string.IsNullOrEmpty(model.Title)) { serviceResult.AddError("عنوان اسلایدشو نمی تواند فاقد مقدار باشد"); } if (!string.IsNullOrEmpty(model.Title) && model.Title.Length > 128) { serviceResult.AddError("تعداد کاراکترهای عنوان اسلایدشو نمی تواند بیش از 128 کاراکتر باشد".ToPersianNumbers()); } if (!string.IsNullOrEmpty(model.Description) && model.Description.Length > 128) { serviceResult.AddError("تعداد کاراکترهای توضیحات اسلایدشو نمی تواند بیش از 128 کاراکتر باشد".ToPersianNumbers()); } if (!string.IsNullOrEmpty(model.Link) && model.Link.Length > 128) { serviceResult.AddError("تعداد کاراکترهای لینک اسلایدشو نمی تواند بیش از 128 کاراکتر باشد".ToPersianNumbers()); } #endregion if (serviceResult.IsSuccess) { _context.SlideShows.Add(model.ToEntity()); if (_context.SaveChanges() == 0) { serviceResult.AddError("در انجام عملیات خطایی رخ داد"); } } return(serviceResult); }
public async Task <ServiceResult <IdentityUser> > UpdateIdentityUserAsync(UpsertUserModel model) { var serviceResult = new ServiceResult <IdentityUser>(); var identityUser = await _userManger.FindByEmailAsync(model.Email); if (identityUser == null) { serviceResult.AddError("No identity user found."); } else { identityUser.Email = model.Email; identityUser.UserName = model.Username ?? model.Email; var updateResult = await _userManger.UpdateAsync(identityUser); if (updateResult.Succeeded == false) { foreach (var err in updateResult.Errors) { serviceResult.AddError(err.Description); } } else { serviceResult.ResultObj = identityUser; } } return(serviceResult); }
public async Task<IServiceResult> CreateSpentTime(SpentTimeEditViewModel model) { var result = new ServiceResult<SpentTimeEditViewModel>(); try { var user = await userManager.FindByIdAsync(model.UserId); if(user == null) { result.AddError("", "Ez a felhasználó nem létezik"); } var issue = await context.Issues.FindAsync(model.IssueId); if(issue == null) { result.AddError(m => m.IssueId, "Ez a feladat nem létezik"); } if(result.Succeeded) { var spentTime = mapper.Map<SpentTime>(model); spentTime.User = user; spentTime.Issue = issue; context.SpentTimes.Add(spentTime); await context.SaveChangesAsync(); } } catch (Exception e) { result.AddError("", e.Message); } return result; }
private static ServiceResult RequiredAttribute(ServiceResult serviceResult, object value, PropertyInfo property, CustomAttributeData attribute) { if (property.PropertyType == typeof(String)) { if (value == null) { serviceResult.AddError(attribute.NamedArguments.Select(c => c.TypedValue.Value.ToString()).FirstOrDefault()); } else { if (string.IsNullOrEmpty(value.ToString())) { serviceResult.AddError(attribute.NamedArguments.Select(c => c.TypedValue.Value.ToString()).FirstOrDefault()); } } } if (property.PropertyType == typeof(IFormFile)) { if (value == null) { serviceResult.AddError(attribute.NamedArguments.Select(c => c.TypedValue.Value.ToString()).FirstOrDefault()); } } return(serviceResult); }
public ServiceResult CreateNewsFile(NewsFileCreateDto model) { var serviceResult = new ServiceResult(true); #region validation if (string.IsNullOrEmpty(model.Title)) { serviceResult.AddError("عنوان نمی تواند فاید مقدار باشد"); } if (!string.IsNullOrEmpty(model.Title) && model.Title.Length > 128) { serviceResult.AddError("عنوان نمی تواند بیش از 128 کاراکتر را شامل شود".ToPersianNumbers()); } #endregion if (serviceResult.IsSuccess) { var entity = model.ToEntity(); _context.Entry(entity).State = EntityState.Added; if (_context.SaveChanges() == 0) { serviceResult.AddError("در انجام عملیات خطایی رخ داد"); } } return(serviceResult); }
public ServiceResult <string> Upload(IFormFile file, string folderName, long?maxLength) { var serviceResult = new ServiceResult <string>(true); if (file == null) { serviceResult.AddError("فایلی انتخاب نشده است"); } else { if (file.Length > maxLength) { serviceResult.AddError("حجم فایل انتخابی بزرگ می باشد"); } else { var extension = System.IO.Path.GetExtension(file.FileName); var fileName = $"{Guid.NewGuid()}{extension}"; var path = System.IO.Path.Combine(_env.WebRootPath, "Files", folderName, fileName); var fileStream = new System.IO.FileStream(path, System.IO.FileMode.Create); file.CopyTo(fileStream); fileStream.Close(); serviceResult.Data = fileName; } } return(serviceResult); }
public ServiceResult <string> DeleteEvent(int id) { var serviceResult = new ServiceResult <string>(true); var entity = _context.Events.FirstOrDefault(c => c.Id == id); if (entity == null) { serviceResult.AddError(" برنامه با شناسه ارسالی یافت نشد"); } else { var fileCount = _context.EventFiles.Where(c => c.EventId == id).Count(); if (fileCount > 0) { serviceResult.AddError("برنامه دارای چندین فایل می باشد زیرا امکان حذف برنامه وجود ندارد"); } if (serviceResult.IsSuccess) { serviceResult.Data = entity.PrimaryPicture; _context.Entry(entity).State = EntityState.Deleted; if (_context.SaveChanges() == 0) { serviceResult.AddError("در انجام عملیات خطایی رخ داد"); } } } return(serviceResult); }
public ServiceResult DeleteImageForProduct(int id, string imageGuid) { var serviceResult = new ServiceResult(true); var entity = _dbContext.Products.Find(id); if (entity == null) { serviceResult.AddError("محصولی یافت نشد"); } else { var imageList = JsonConvert.DeserializeObject <List <string> >(entity.ImagesJson); if (imageList.Any(c => c == imageGuid)) { imageList.Remove(imageGuid); entity.ImagesJson = JsonConvert.SerializeObject(imageList); Update(entity); serviceResult = Save("یک عکس با موفقیت حذف شد"); if (serviceResult.IsSuccess) { DeleteFile(imageList.ToString(), FileType.ProductImage); } } else { serviceResult.AddError("عکسی یافت نشد"); } } return(serviceResult); }
public ServiceResult DeleteCategory(int id) { var serviceResult = new ServiceResult(true); var entity = _dbContext.Categories.Find(id); if (entity == null) { serviceResult.AddError("دسته بندی یافت نشد"); } else { // آیا زیرگروه دارد؟ if (_dbContext.Categories.Any(c => c.ParentId == id)) { serviceResult.AddError("امکان حذف دسته بندی وجود ندارد زیرا دارای چندین زیردسته می باشد"); } else { if (_dbContext.Products.Any(c => c.CategoryId == id)) { serviceResult.AddError("امکان حذف دسته بندی وجود ندارد زیرا دارای چندین محصول می باشد"); } else { Remove(entity); serviceResult = Save("دسته بندی با موفقیت حذف شد"); } } } return(serviceResult); }
public ServiceResult <string> DeletePost(int id) { var serviceResult = new ServiceResult <string>(true); var entity = _context.Posts.FirstOrDefault(c => c.Id == id); if (entity == null) { serviceResult.AddError(" پستی با شناسه ارسالی یافت نشد"); } else { var countFile = _context.PostFiles.Where(c => c.PostId.Equals(id)).Count(); if (countFile > 0) { serviceResult.AddError("پست را نمی توانید حذف کنید زیرا دارای چندین فایل می باشد"); } if (serviceResult.IsSuccess) { serviceResult.Data = entity.PrimaryPicture; _context.Entry(entity).State = EntityState.Deleted; if (_context.SaveChanges() == 0) { serviceResult.AddError("در انجام عملیات خطایی رخ داد"); } } } return(serviceResult); }
public ServiceResult <string> ChangeProfile_Validation(ChangeProfileDto dto) { var serviceResult = new ServiceResult <string>(true); #region validation if (string.IsNullOrEmpty(dto.FullName)) { serviceResult.AddError("نام و نام خانوداگی نمی تواند فاقد مقدار باشد"); } if (string.IsNullOrEmpty(dto.PhoneNumber)) { serviceResult.AddError("شماره همراه نمی تواند فاقد مقدار باشد"); } if (!string.IsNullOrEmpty(dto.PhoneNumber) && !dto.PhoneNumber.IsValidIranianMobileNumber()) { serviceResult.AddError("ساختار شماره همراه وارد شده درست نمی باشد"); } if (!string.IsNullOrEmpty(dto.FullName) && dto.FullName.Length > 500) { serviceResult.AddError("نام و نام خانواگی نمی تواند بیش از 500 کاراکتر را شامل شود".ToPersianNumbers()); } if (!string.IsNullOrEmpty(dto.PhoneNumber) && dto.PhoneNumber.Length > 256) { serviceResult.AddError("شماره همراه وارد نشده نباید بیش از 256 کارکتر را شامل شود".ToPersianNumbers()); } #endregion return(serviceResult); }
public async Task <IActionResult> Login(LoginViewModel model) { var serviceResult = new ServiceResult(true); var user = _dbContext.Users.FirstOrDefault(c => c.PhoneNumber == model.PhoneNumber); if (user == null) { serviceResult.AddError("کاربری یافت نشد"); } if (serviceResult.IsSuccess) { var checkPass = await _signInManager.CheckPasswordSignInAsync(user, model.Password, true); if (checkPass.Succeeded) { var signInResult = await _signInManager .PasswordSignInAsync(user.UserName, model.Password, true, false); if (signInResult.Succeeded) { return(RedirectPermanent("/admin")); } } else { serviceResult.AddError("کاربری یافت نشد"); } } Swal(false, serviceResult.Errors.FirstOrDefault()); return(View(model)); }
public ServiceResult <byte[]> ReportPrintAsync(Guid solicitationId) { var newDirectory = Path.Combine(StaticFilesDirectory, "Reports", "VR_REPORT.rdl"); var files = new FileInfo(newDirectory); var notif = new ServiceResult <byte[]>(); if (!files.Exists) { notif.AddError("Error", "El Reporte no fue encontrado."); return(notif); } var rv = new reportingNameSpace.LocalReport(newDirectory); var solic = _solicitationSubsidyService.GetByIdSubsidy(solicitationId).Response; if (solic == null) { notif.AddError("Error", "La solicitud no existe"); return(notif); } var destiny = _destinyService.Get_DestiniesProcedure(solicitationId).Response; var images = _solicitationSubsidyService.SolicitationApprovedBySupervisorId(solicitationId, solic.UserId).Response; var totalLetter = _context.GetLetterNumberTotalSolicitationAsync(destiny.Sum(x => x.Amount).ToString("F").Replace(",", "."), "."); rv.AddDataSource("SolicitationDTODataSet", new List <FindByIdSolicitationSubsidyDto>() { solic }); rv.AddDataSource("UserDataSet", new List <UserDto>() { solic.User }); rv.AddDataSource("Destination", destiny); rv.AddDataSource("SignSupervisorImage", new List <UrlSignHolograph>() { images }); rv.AddDataSource("DestinationDataSet", solic.Destinies); rv.AddDataSource("ExpenditureDataSet", solic.Expenditures); rv.AddDataSource("Common", new List <ReportDto>() { new ReportDto() { TodayDate = DateTime.Today.ToString("d"), TotalLetter = totalLetter.FirstOrDefault() == null ? "" : totalLetter.FirstOrDefault().LetterNumber } }); System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); var result = rv.Execute(reportingNameSpace.RenderType.Pdf); return(new ServiceResult <byte[]>(result.MainStream)); }
public ServiceResult <byte[]> PrintReportCommission(Guid solicitationId) { var newDirectory = Path.Combine(StaticFilesDirectory, "Reports", "Informe_de_comision_de_servicio.rdl"); var files = new FileInfo(newDirectory); var notif = new ServiceResult <byte[]>(); if (!files.Exists) { notif.AddError("Error", "El Reporte no fue encontrado."); return(notif); } var solic = _solicitationSubsidyService.GetByIdSubsidy(solicitationId).Response; if (solic == null) { notif.AddError("Error", "La solicitud no existe."); return(notif); } var rv = new reportingNameSpace.LocalReport(newDirectory); var iscommission = solic.IsCommission == null ? true : false; if (!iscommission) { rv.AddDataSource("solicitationDataSet", new List <FindByIdSolicitationSubsidyDto>() { solic }); } else { var commisionList = _context.SolicitationSubsidies.Where(v => v.RandomKey == solic.RandomKey) .ToList(); rv.AddDataSource("solicitationDataSet", commisionList); } rv.AddDataSource("DestinationDataSet", new List <DestinyFromSolicitationSubsidyFindByIdDto>(solic.Destinies)); rv.AddDataSource("UsersDataSet", new List <UserDto>() { solic.User }); rv.AddDataSource("ObservationList", new List <ObservationDto>(solic.Observations)); System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); var result = rv.Execute(reportingNameSpace.RenderType.Pdf); return(new ServiceResult <byte[]>(result.MainStream)); }
public ServiceResult <string> EditNews(NewsEditDto model) { var serviceResult = new ServiceResult <string>(true); var entity = _context.News.FirstOrDefault(c => c.Id == model.Id); if (entity == null) { serviceResult.AddError("خبری با شناسه ارسالی یافت نشد"); } #region validation if (string.IsNullOrEmpty(model.Title)) { serviceResult.AddError("عنوان خبر نمی تواند فاقد مقدار باشد"); } if (!string.IsNullOrEmpty(model.Title) && model.Title.Length > 128) { serviceResult.AddError("تعداد کاراکترهای عنوان خبر نمی تواند بیش از 128 کاراکتر باشد".ToPersianNumbers()); } if (!model.Type.HasValue) { serviceResult.AddError("نوع خبر نمی تواند فاقد مقدار باشد"); } #endregion if (serviceResult.IsSuccess) { entity.Title = model.Title; entity.Type = model.Type.Value; if (!string.IsNullOrEmpty(model.PrimaryPicture)) { serviceResult.Data = entity.PrimaryPicture; entity.PrimaryPicture = model.PrimaryPicture; } entity.Description = model.Description; _context.Entry(entity).State = EntityState.Modified; if (_context.SaveChanges() == 0) { serviceResult.AddError("در انجام عملیات خطایی رخ داد"); } } return(serviceResult); }
public async Task <ServiceResult <ResetPassword> > ResetPassword(ResetPassword model) { var notif = new ServiceResult <ResetPassword>(); var valid = _fluentValidationResetPassword.Validate(model); if (!valid.IsValid) { return(valid.ToServiceResult <ResetPassword>(model)); } if (!model.Password.Any(char.IsUpper)) { notif.AddError("Error", "La contraseña debe contener al menos una mayuscula ('A','Z')"); } if (!model.Password.Any(char.IsLower)) { notif.AddError("Error", "La contraseña debe contener al menos una minuscula ('a','z')"); } if (notif.Errors.Count() > 0) { return(notif); } var user = _userManager.Users.FirstOrDefault(x => x.Id == model.UserId); if (user != null) { var unescapedString = Uri.UnescapeDataString(model.PasswordResetToken); var result = await _userManager.ResetPasswordAsync(user, unescapedString, model.Password); if (!result.Succeeded) { var newResult = new ServiceResult <ResetPassword>(); foreach (var identityError in result.Errors) { var error = (identityError.Code.Equals("InvalidToken")) ? "El token expiró o es erróneo." : ""; newResult.AddError("Error", error); } return(newResult); } } return(new ServiceResult <ResetPassword>()); }
public async Task <ServiceResult> ChangePassword(ChangePasswordDto model) { var serviceResult = new ServiceResult(true); var user = _context.Users.FirstOrDefault(c => c.Id.Equals(model.UserId)); if (user == null) { serviceResult.AddError("کاربری یافت نشد"); } #region validation if (string.IsNullOrEmpty(model.Password)) { serviceResult.AddError("رمز عبور نمی تواند فاقد مقدار باشد"); } if (string.IsNullOrEmpty(model.NewPassword)) { serviceResult.AddError("رمز عبور جدید نمی تواند فاقد مقدرا باشد"); } if (!string.IsNullOrEmpty(model.NewPassword) && model.NewPassword.Length < 6) { serviceResult.AddError("رمز عبور جدید باید دارای حداقل شش کاراکتر باشد"); } if (model.NewPassword != model.ConfirmNewPassword) { serviceResult.AddError("رمز عبور جدید با تکرارش مطابقت ندارد"); } #endregion if (serviceResult.IsSuccess) { var identityResult = await _userManager.ChangePasswordAsync(user, model.Password, model.NewPassword); if (!identityResult.Succeeded) { serviceResult.IsSuccess = false; serviceResult.Errors = GetErrorsForChangePassword(identityResult.Errors.Select(c => c.Code).ToList()); } } return(serviceResult); }
public async Task <ServiceResult> CountBlockAsync(string id) { try { var user = await m_userRepository.FindEntityAsync(x => x.Id == id); if (user != null) { int counter = user.BlockCounter; if (counter >= 5) { var result = await BlockAsync(id); return(result); } else { counter++; user.BlockCounter = counter; await m_userRepository.UpdateAsync(user); await m_userRepository.SaveChangesAsync(); return(ServiceResult.Success); } } return(ServiceResult.AddError("user không tồn tại")); } catch (Exception e) { return(ServiceResult.AddError(e.Data.ToString())); } }
public async Task <ServiceResult> BlockAsync(string id) { try { var user = await m_userRepository.FindEntityAsync(x => x.Id == id); if (user != null) { user.IsBlocked = true; await m_userRepository.UpdateAsync(user); await m_userRepository.SaveChangesAsync(); return(ServiceResult.Success); } else { return(ServiceResult.AddError("User không tồn tại")); } } catch (Exception e) { return(ServiceResult.AddError(e.Data.ToString())); } }
public ServiceResult <int> DeleteEducationFile(int id) { var serviceResult = new ServiceResult <int>(true); var entity = _dbContext.EducationFiles.Find(id); if (entity == null) { serviceResult.AddError("فایلی یافت نشد"); } else { DeleteFile(entity.FileName, FileType.EducationFile); Remove(entity); var result = Save("یک فایل با موفقیت حذف شد"); serviceResult.IsSuccess = result.IsSuccess; serviceResult.Data = entity.EducationId; serviceResult.Message = result.Message; } return(serviceResult); }
public ServiceResult DeleteEducation(int id) { var serviceResult = new ServiceResult(true); var entity = _dbContext.Educations.Include(c => c.Files).FirstOrDefault(c => c.Id == id); if (entity == null) { serviceResult.AddError("آموزشی یافت نشد"); } else { DeleteFile(entity.Image, FileType.EducationImage); Remove(entity); Remove <EducationFile>(entity.Files.ToList()); foreach (var file in entity.Files) { DeleteFile(file.FileName, FileType.EducationFile); } serviceResult = Save("یک آموزش با موفقیت حذف شد"); } return(serviceResult); }
private static ServiceResult MaxLengthAttribute(ServiceResult serviceResult, object value, PropertyInfo property, CustomAttributeData attribute) { int length = (int)attribute.ConstructorArguments.Select(c => c.Value).FirstOrDefault(); var errorMessage = ""; if (property.PropertyType == typeof(String)) { if (value != null && value.ToString().Length > length) { errorMessage = attribute.NamedArguments.Select(c => c.TypedValue.Value.ToString()).FirstOrDefault(); } } if (property.PropertyType == typeof(IFormFile)) { if (value != null && ((IFormFile)value).Length > length) { errorMessage = attribute.NamedArguments.Select(c => c.TypedValue.Value.ToString()).FirstOrDefault(); } } errorMessage = errorMessage.Replace("@", length.ToPersianNumbers()); if (!string.IsNullOrEmpty(errorMessage)) { serviceResult.AddError(errorMessage); } return(serviceResult); }
public async Task <ServiceResult> DownGradeUserAsync(string userId) { try { ApplicationUser user = m_userRepository.FindEntity(x => x.Id == userId); if (user != null) { //update user paid status user.IsPaid = false; await m_userRepository.UpdateAsync(user); await m_userRepository.SaveChangesAsync(); var classes = await m_classService.GetRegisteredClassesAsync(userId); //get user registed class foreach (Class c in classes) // change goal all class { await m_classService.ChangeGoalAsync(userId, c.Id, HePa.Core.Helpers.Constraint.FreeUserLearnwordAmount.FREE_USER_LEARNWORD_AMOUNT); } return(ServiceResult.Success); } else { return(ServiceResult.AddError("User is not found")); } } catch (Exception e) { return(ServiceResult.AddError(e.Data.ToString())); } }
public ServiceResult Insert(string id, int expirytDate) { //Generate passport code try { bool isSame = true; IList <string> codes = m_hepapassportRepository.Find().Select(x => x.Code).ToList(); string code = ""; while (isSame != false) //Neu isSame = true thi sinh lai code { code = RandomString(3); isSame = checkSameCode(code); } //Create new object and insert to database HepaPassport hp = new HepaPassport(); hp.Code = code; hp.Id = id; hp.ExpiryDate = expirytDate; hp.CreateDate = DateTime.Now.Date; m_hepapassportRepository.Insert(hp); m_hepapassportRepository.SaveChanges(); return(ServiceResult.Success); } catch (Exception e) { return(ServiceResult.AddError(e.Data.ToString())); } }
public async Task <ServiceResult <IdentityUser> > CreateIdentityUserAsync(UpsertUserModel model) { var serviceResult = new ServiceResult <IdentityUser>(); var identityUser = new IdentityUser(); identityUser.Email = model.Email; identityUser.UserName = model.Username ?? model.Email; var result = await _userManger.CreateAsync(identityUser, model.Password); if (result.Succeeded == false) { foreach (var err in result.Errors) { serviceResult.AddError(err.Description); } } else { serviceResult.ResultObj = identityUser; } return(serviceResult); }
public async Task <ServiceResult <UpdateSongError> > UpdateSongForPartyGoerAsync(PartyGoer partyGoer, List <string> songUris, int currentSongProgressInMs) { HttpResponseMessage response = await SendHttpRequestAsync(partyGoer, _apiEndpoints[ApiEndpointType.PlaySong], new ApiParameters { Parameters = new Dictionary <string, object> { { "device_id", _partyGoerSettingsService.GetConfigurationSetting(partyGoer).PerferredDeviceId } } }, new StartUserPlaybackSong { uris = songUris.Select(song => song.Contains("spotify:track:") ? song : $"spotify:track:{song}").ToList(), position_ms = currentSongProgressInMs }); ServiceResult <UpdateSongError> error = new ServiceResult <UpdateSongError>(); if (response.IsSuccessStatusCode) { return(error); } else { await _logService.LogExceptionAsync(new Exception($"Unable to update song for {partyGoer.Id}"), await response.Content.ReadAsStringAsync()); // TODO: Check status codes and add specific messaging for status codes based on Spotifys API error.AddError(new UpdateSongError($"Unable to update song for {partyGoer.Id}")); return(error); } }
public ServiceResult<Category> GetCategory(string name) { var result = new ServiceResult<Category>(); var category = _db.Connection.Query<Category>("SELECT * FROM Category WHERE Name = @name", new { name }); if (category == null || !category.Any()) { result.AddError(ErrorType.NotFound, "Category {0} not found", name); return result; } // are there multiple categories with the same name? if (category.Count() > 1) { result.AddError(ErrorType.Generic, "Multiple Categories with name {0} exist", name); return result; } result.Result = category.First(); return result; }
public ServiceResult<Vendor> GetVendor(string name) { var result = new ServiceResult<Vendor>(); var vendor = _db.Connection.Query<Vendor>("SELECT * FROM Vendor WHERE Name = @name", new { name }); if (vendor == null || !vendor.Any()) { result.AddError(ErrorType.NotFound, "Vendor {0} not found", name); return result; } // are there multiple vendors with the same name? if (vendor.Count() > 1) { result.AddError(ErrorType.Generic, "Multiple Vendors with name {0} exist", name); return result; } result.Result = vendor.First(); return result; }
public async Task<IServiceResult> CreateComment(CommentEditViewModel model) { var result = new ServiceResult<CommentEditViewModel>(); try { var issue = await context.Issues.FindAsync(model.IssueId); if (issue == null) { result.AddError(m => m.IssueId, "Ez a feladat nem létezik"); } var user = await userManager.FindByIdAsync(model.UserId); if (user == null) { result.AddError(m => m.UserId, "Ez a felhasználó nem létezik"); } if (result.Succeeded) { var comment = mapper.Map<Comment>(model); comment.User = user; comment.Issue = issue; comment.Created = DateTime.Now; context.Comments.Add(comment); await context.SaveChangesAsync(); result.Data = mapper.Map<Comment, CommentListViewModel>(comment); } } catch (Exception e) { result.AddError("", e.Message); } return result; }
/// <summary> /// Készít egy új platformot /// </summary> /// <param name="model">Az új platform modelje</param> /// <returns></returns> public async Task<IServiceResult> CreatePlatform(PlatformEditViewModel model) { var result = new ServiceResult<PlatformEditViewModel>(); try { await TestPlatformStore.InsertAsync(Mapper.Map<PlatformEditViewModel, Platform>(model)); } catch (Exception e) { Log.Error(e.Message, e); result.AddError("", e.Message); } return result; }
public ServiceResult<bool> DeleteBudgetCategory(int categoryId, DateTime month) { // TODO handle cascading deletes var result = new ServiceResult<bool>(); bool deletionResult = false; // does category exist? var categoryResult = _categoryService.GetCategory(categoryId); if (categoryResult.HasErrors) { result.AddErrors(categoryResult); return result; } // does budget category exist? var predicates = new List<IPredicate>(); predicates.Add(Predicates.Field<BudgetCategory>(x => x.Month, Operator.Eq, month)); predicates.Add(Predicates.Field<BudgetCategory>(x => x.CategoryId, Operator.Eq, categoryId)); var predicate = new PredicateGroup { Operator = GroupOperator.And, Predicates = predicates }; var budgetCategory = _db.GetList<BudgetCategory>(predicate); // are there multiple budget categories with the same month? if (budgetCategory.Count() > 1) { result.AddError(ErrorType.Generic, "Multiple Budget Categories for month {0} exist", month.ToShortDateString()); return result; } // is this an existing budget category? else if (budgetCategory.Count() == 1) { var existingBudgetCategory = budgetCategory.First(); deletionResult = _db.Delete<BudgetCategory>(existingBudgetCategory); } result.Result = deletionResult; return result; }
public ServiceResult<bool> DeleteVendorMap(int vendorMapId) { ServiceResult<bool> result = new ServiceResult<bool>(); var vendorMap = _importDescriptionVendorMapRepository.GetById(vendorMapId); if (vendorMap == null) { result.Result = false; result.AddError(ErrorType.NotFound, "Vendor Mapping {0} not found", vendorMapId); return result; } _importDescriptionVendorMapRepository.Delete(vendorMap); _unitOfWork.Commit(); return result; }
public ServiceResult<Account> GetAccount(int accountId) { var result = new ServiceResult<Account>(); result.Result = _accountRepository.GetById(accountId); if (result.Result == null) { result.AddError(ErrorType.NotFound, "Account {0} not found", accountId); } return result; }
public ServiceResult<Bill> GetBill(int billId) { var result = new ServiceResult<Bill>(); result.Result = _billRepository.GetById(billId); if (result.Result == null) { result.AddError(ErrorType.NotFound, "Bill {0} not found", billId); } return result; }
public ServiceResult<Bill> AddBill(string name, decimal amount, int billGroupId, int? categoryId, int? vendorId, DateTime startDate, DateTime endDate, int frequency, DateTime? secondaryStartDate, DateTime? secondaryEndDate) { ServiceResult<Bill> result = new ServiceResult<Bill>(); if (categoryId.HasValue && categoryId.Value == 0) categoryId = null; if (vendorId.HasValue && vendorId.Value == 0) vendorId = null; // get bill group var billGroup = _billGroupRepository.GetById(billGroupId); if (billGroup == null) { // if we don't have any bill groups at all, create one if (_billGroupRepository.GetAll().Count() == 0) { billGroup = new BillGroup() { IsActive = true, Name = "Bills" }; _billGroupRepository.Add(billGroup); _unitOfWork.Commit(); } else { result.AddError(ErrorType.NotFound, "Bill Group {0} not found", billGroupId); return result; } } // create bill var bill = new Bill() { Name = name, Amount = amount, BillGroupId = billGroup.Id, CategoryId = categoryId, VendorId = vendorId, StartDate = startDate, EndDate = endDate, RecurrenceFrequency = frequency, StartDate2 = secondaryStartDate, EndDate2 = secondaryEndDate }; // create transactions int count = 0; DateTime cur = new DateTime(startDate.Year, startDate.Month, startDate.Day); while (cur <= endDate) { BillTransaction trx = new BillTransaction() { Amount = amount, OriginalAmount = amount, CategoryId = categoryId, OriginalCategoryId = categoryId, VendorId = vendorId, OriginalVendorId = vendorId, Timestamp = cur, OriginalTimestamp = cur }; bill.BillTransactions.Add(trx); count++; if (frequency == 0) cur = endDate.AddDays(1); else if (frequency > 0) cur = startDate.AddDays(count * frequency); else cur = startDate.AddMonths(count * -1 * frequency); } if (secondaryStartDate.HasValue) { if (secondaryEndDate.HasValue) endDate = secondaryEndDate.Value; count = 0; cur = new DateTime(secondaryStartDate.Value.Year, secondaryStartDate.Value.Month, secondaryStartDate.Value.Day); while (cur <= endDate) { BillTransaction trx = new BillTransaction() { Amount = amount, OriginalAmount = amount, CategoryId = categoryId, OriginalCategoryId = categoryId, VendorId = vendorId, OriginalVendorId = vendorId, Timestamp = cur, OriginalTimestamp = cur }; bill.BillTransactions.Add(trx); count++; if (frequency == 0) cur = endDate.AddDays(1); else if (frequency > 0) cur = secondaryStartDate.Value.AddDays(count * frequency); else cur = secondaryStartDate.Value.AddMonths(count * -1 * frequency); } } _billRepository.Add(bill); _unitOfWork.Commit(); return result; }
public ServiceResult<bool> DeleteTransaction(int transactionId) { // TODO handle cascading deletes var result = new ServiceResult<bool>(); // delete subtransactions _db.Delete<Subtransaction>(Predicates.Field<Subtransaction>(x => x.TransactionId, Operator.Eq, transactionId)); var deletionResult = _db.Delete<Transaction>(Predicates.Field<Transaction>(x => x.Id, Operator.Eq, transactionId)); if (!deletionResult) { result.AddError(ErrorType.NotFound, "Transaction {0} not found", transactionId); return result; } _accountService.UpdateAccountBalances(); result.Result = deletionResult; return result; }
public ServiceResult<Bill> UpdateBill(int billId, string name, decimal amount, int billGroupId, int? categoryId, int? vendorId, DateTime startDate, DateTime endDate, int frequency, bool updateExisting, DateTime? secondaryStartDate, DateTime? secondaryEndDate) { ServiceResult<Bill> result = new ServiceResult<Bill>(); var bill = _billRepository.GetById(billId); if (bill == null) { result.AddError(ErrorType.NotFound, "Bill {0} not found", billId); return result; } // TODO do we need to do exist checks for billGroupId, categoryId, vendorId? if (categoryId.HasValue && categoryId.Value == 0) categoryId = null; if (vendorId.HasValue && vendorId.Value == 0) vendorId = null; if (updateExisting) { if (bill.StartDate != startDate || bill.EndDate != endDate || bill.RecurrenceFrequency != frequency || bill.StartDate2 != secondaryStartDate || bill.EndDate2 != secondaryEndDate) { List<BillTransaction> existing = _billTransactionRepository.GetMany(x => x.BillId == billId).ToList(); List<BillTransaction> expected = new List<BillTransaction>(); #region Generate expected transactions int count = 0; DateTime cur = new DateTime(startDate.Year, startDate.Month, startDate.Day); while (cur <= endDate) { BillTransaction trx = new BillTransaction() { Amount = amount, OriginalAmount = amount, CategoryId = categoryId, OriginalCategoryId = categoryId, VendorId = vendorId, OriginalVendorId = vendorId, Timestamp = cur, OriginalTimestamp = cur }; expected.Add(trx); count++; if (frequency == 0) cur = endDate.AddDays(1); else if (frequency > 0) cur = startDate.AddDays(count * frequency); else cur = startDate.AddMonths(count * -1 * frequency); } if (secondaryStartDate.HasValue) { if (secondaryEndDate.HasValue) endDate = secondaryEndDate.Value; count = 0; cur = new DateTime(secondaryStartDate.Value.Year, secondaryStartDate.Value.Month, secondaryStartDate.Value.Day); while (cur <= endDate) { BillTransaction trx = new BillTransaction() { Amount = amount, OriginalAmount = amount, CategoryId = categoryId, OriginalCategoryId = categoryId, VendorId = vendorId, OriginalVendorId = vendorId, Timestamp = cur, OriginalTimestamp = cur }; expected.Add(trx); count++; if (frequency == 0) cur = endDate.AddDays(1); else if (frequency > 0) cur = secondaryStartDate.Value.AddDays(count * frequency); else cur = secondaryStartDate.Value.AddMonths(count * -1 * frequency); } } #endregion List<BillTransaction> reused = new List<BillTransaction>(); while (existing.Any() && expected.Any()) { var existingProjections = existing.Select(e => new { Item = e, Comparisons = expected.Select(x => new { Item = x, Days = Math.Abs((x.Timestamp - e.Timestamp).TotalDays) }) }); var bestExisting = existingProjections.OrderBy(x => x.Comparisons.Min(y => y.Days)).FirstOrDefault(); if (bestExisting != null) { // shift existing record's timestamp to closest match in expected var bestMatch = bestExisting.Comparisons.OrderBy(x => x.Days).FirstOrDefault().Item; bestExisting.Item.Timestamp = bestMatch.Timestamp; bestExisting.Item.OriginalTimestamp = bestMatch.OriginalTimestamp; expected.Remove(bestMatch); existing.Remove(bestExisting.Item); reused.Add(bestExisting.Item); } } // delete unused transactions var complete = reused.Union(expected).Select(x => x.Id); _billTransactionRepository.Delete(x => x.BillId == billId && !complete.Contains(x.Id)); //reused.ForEach(x => bill.BillTransactions.Add(x)); expected.ForEach(x => bill.BillTransactions.Add(x)); } if (bill.Amount != amount || bill.CategoryId != categoryId || bill.VendorId != vendorId) { var billTransasctions = _billTransactionRepository.GetMany(x => x.BillId == billId); if (billTransasctions != null) { foreach (var trx in billTransasctions) { if (bill.Amount != amount) { // only update a transaction amount if it hadn't been edited from it's original value (ie don't change modified amounts) if (trx.Amount == trx.OriginalAmount) trx.Amount = amount; trx.OriginalAmount = amount; } if (bill.CategoryId != categoryId) trx.CategoryId = categoryId; if (bill.VendorId != vendorId) trx.VendorId = vendorId; } } } } bill.Name = name; bill.Amount = amount; bill.BillGroupId = billGroupId; bill.CategoryId = categoryId; bill.VendorId = vendorId; bill.StartDate = startDate; bill.EndDate = endDate; bill.StartDate2 = secondaryStartDate; bill.EndDate2 = secondaryEndDate; bill.RecurrenceFrequency = frequency; _unitOfWork.Commit(); result.Result = bill; return result; }
public ServiceResult<bool> DeleteBill(int billId) { var result = new ServiceResult<bool>(); var bill = _billRepository.GetById(billId); if (bill == null) { result.Result = false; result.AddError(ErrorType.NotFound, "Bill {0} not found", billId); return result; } _billTransactionRepository.Delete(x => x.BillId == billId); _billRepository.Delete(bill); _unitOfWork.Commit(); return result; }
public async Task<IServiceResult> DeleteSpentTime(int id) { var result = new ServiceResult<SpentTimeEditViewModel>(); try { var spentTime = await context.SpentTimes.FindAsync(id); if(spentTime == null) { result.AddError("", "Ez a munkaidő nem létezik"); return result; } context.SpentTimes.Remove(spentTime); await context.SaveChangesAsync(); } catch (Exception e) { result.AddError("", e.Message); } return result; }
public ServiceResult<Vendor> RecategorizeVendor(int vendorId, int? defaultCategoryId) { ServiceResult<Vendor> result = new ServiceResult<Vendor>(); if (defaultCategoryId.HasValue && defaultCategoryId.Value == 0) defaultCategoryId = null; // does this vendor even exist? var vendor = _vendorRepository.GetById(vendorId); if (vendor == null) { result.AddError(ErrorType.NotFound, "Vendor with Id {0} not found", vendorId); return result; } vendor.DefaultCategoryId = defaultCategoryId; result.Result = vendor; _unitOfWork.Commit(); return result; }
public async Task<IServiceResult> UpdateSpentTime(SpentTimeEditViewModel model) { var result = new ServiceResult<SpentTimeEditViewModel>(); try { var spentTime = model.Id.HasValue ? await context.SpentTimes .Include(s => s.Issue) .Include(s => s.User) .FirstOrDefaultAsync(s => s.Id == model.Id.Value) : null; if(spentTime == null) { result.AddError("", "Nem létezik a munkaidő"); } if (model.UserId != spentTime.User.Id) { result.AddError("", "Csak az módosíthatja a munkaidőt aki felvette"); } var issue = await context.Issues.FindAsync(model.IssueId); if (issue == null) { result.AddError(m => m.IssueId, "Ez a feladat nem létezik"); } if (result.Succeeded) { spentTime.Date = model.Date; spentTime.Description = model.Description; spentTime.Hour = model.Hour; spentTime.Issue = issue; await context.SaveChangesAsync(); } } catch (Exception e) { result.AddError("", e.Message); } return result; }
public ServiceResult<Vendor> RenameVendor(int vendorId, string name) { ServiceResult<Vendor> result = new ServiceResult<Vendor>(); // does this vendor even exist? var vendor = _vendorRepository.GetById(vendorId); if (vendor == null) { result.AddError(ErrorType.NotFound, "Vendor with Id {0} not found", vendorId); return result; } // see if a vendor with this name already exists var existingVendor = _vendorRepository.Get(x => x.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase)); if (existingVendor != null && existingVendor != vendor) { foreach (var trx in vendor.Transactions) { trx.VendorId = existingVendor.Id; } foreach (var bill in vendor.Bills) { foreach (var billTrx in bill.BillTransactions) { if (billTrx.OriginalVendorId == vendorId) { billTrx.OriginalVendorId = existingVendor.Id; } if (billTrx.VendorId == vendorId) { billTrx.VendorId = existingVendor.Id; } } bill.VendorId = existingVendor.Id; } _vendorRepository.Delete(vendor); // keep track of the rename in the mappings table existingVendor.ImportDescriptionVendorMaps.Add(new ImportDescriptionVendorMap() { Description = vendor.Name }); result.Result = existingVendor; } else { // if there's not an existing vendor with this name, just rename the one we have // keep track of the rename in the mappings table vendor.ImportDescriptionVendorMaps.Add(new ImportDescriptionVendorMap() { Description = vendor.Name }); vendor.Name = name; result.Result = vendor; } _unitOfWork.Commit(); return result; }
public ServiceResult<bool> SetReconciled(int transactionId, bool isReconciled) { var result = new ServiceResult<bool>(); var trx = _transactionRepository.GetById(transactionId); if (trx == null) { result.AddError(ErrorType.NotFound, "Transaction {0} not found", transactionId); return result; } trx.IsReconciled = isReconciled; _unitOfWork.Commit(); result.Result = true; return result; }
public ServiceResult<bool> DeleteAccountGroup(int accountGroupId) { // TODO handle cascading deletes var result = new ServiceResult<bool>(); var deletionResult = _db.Delete<AccountGroup>(Predicates.Field<AccountGroup>(x => x.Id, Operator.Eq, accountGroupId)); if (!deletionResult) { result.AddError(ErrorType.NotFound, "AccountGroup {0} not found", accountGroupId); return result; } result.Result = deletionResult; return result; }
public ServiceResult<bool> DeleteVendor(int vendorId) { ServiceResult<bool> result = new ServiceResult<bool>(); var vendor = _vendorRepository.GetById(vendorId); if (vendor == null) { result.Result = false; result.AddError(ErrorType.NotFound, "Vendor {0} not found", vendorId); return result; } foreach (var trx in vendor.Transactions) { trx.Vendor = null; } _importDescriptionVendorMapRepository.Delete(x => x.VendorId == vendorId); _vendorRepository.Delete(vendor); _unitOfWork.Commit(); return result; }
public ServiceResult<bool> DeleteCategory(int categoryId) { var result = new ServiceResult<bool>(); var category = _categoryRepository.GetById(categoryId); if (category == null) { result.Result = false; result.AddError(ErrorType.NotFound, "Category {0} not found", categoryId); return result; } foreach (var trx in category.Subtransactions) { trx.CategoryId = null; } foreach (var vendor in category.VendorDefaults) { vendor.DefaultCategory = null; } _categoryRepository.Delete(category); _unitOfWork.Commit(); return result; }
public ServiceResult<Category> GetCategory(int categoryId) { var result = new ServiceResult<Category>(); result.Result = _categoryRepository.GetById(categoryId); if (result.Result == null) { result.AddError(ErrorType.NotFound, "Category {0} not found", categoryId); } return result; }
public ServiceResult<Transaction> GetTransaction(int transactionId) { var result = new ServiceResult<Transaction>(); var transactionsResult = GetTransactions(new Filter<int>(transactionId)); if (transactionsResult.HasErrors) { result.AddErrors(transactionsResult); return result; } if (transactionsResult.Result.Count() > 1) { result.AddError(ErrorType.Generic, "More than one transaction with Id {0} found", transactionId); return result; } result.Result = transactionsResult.Result.First(); return result; }
public ServiceResult<BillTransaction> UpdateBillTransaction(int billTransactionId, decimal? amount, DateTime? date, bool? isPaid, int? transactionId) { var result = new ServiceResult<BillTransaction>(); var billTransaction = _billTransactionRepository.GetById(billTransactionId); if (billTransaction == null) { result.AddError(ErrorType.NotFound, "Bill transaction {0} not found", billTransactionId); return result; } if (amount.HasValue) billTransaction.Amount = amount.Value; if (date.HasValue) billTransaction.Timestamp = date.Value; if (isPaid.HasValue) billTransaction.IsPaid = isPaid.Value; if (transactionId.HasValue) { var transaction = _transactionRepository.GetById(transactionId.Value); if (transaction != null) transaction.BillTransactionId = billTransactionId; } _unitOfWork.Commit(); return result; }
public ServiceResult<Vendor> GetVendor(int vendorId) { var result = new ServiceResult<Vendor>(); result.Result = _vendorRepository.GetById(vendorId); if (result.Result == null) { result.AddError(ErrorType.NotFound, "Vendor {0} not found", vendorId); } return result; }
public ServiceResult<List<Tuple<Transaction, double>>> PredictBillTransactionMatch(int billTransactionId) { var result = new ServiceResult<List<Tuple<Transaction, double>>>(); var billTransaction = _billTransactionRepository.GetById(billTransactionId); if (billTransaction == null) { result.AddError(ErrorType.NotFound, "Bill transaction {0} not found", billTransactionId); return result; } // find predictions if it's not paid, or there are no associated transactions to indicate the paid status if (!billTransaction.IsPaid || !billTransaction.Transactions.Any()) { var timestampLower = billTransaction.Timestamp.AddMonths(-2); var timestampUpper = billTransaction.Timestamp.AddMonths(2); var amountLower = billTransaction.Amount / 5.0M; var amountUpper = billTransaction.Amount * 5.0M; var amount = amountUpper; amountUpper = Math.Max(amountLower, amountUpper); amountLower = Math.Min(amount, amountLower); // find reasonable predictions var predictions = _transactionRepository.GetMany(x => (x.Amount > amountLower && x.Amount < amountUpper) && (x.Timestamp > timestampLower && x.Timestamp < timestampUpper)).ToList(); // calculate confidence level var billTransactionVendorName = billTransaction.Vendor == null ? "" : billTransaction.Vendor.Name; var confidences = predictions.Select(x => new Tuple<Transaction, double>(x, (.1 * Math.Exp(-1 * Math.Pow((double)((x.Amount - billTransaction.Amount) / billTransaction.Amount), 2.0) / 2.0) + .2 * Math.Exp(-1 * Math.Pow(((x.Timestamp - billTransaction.Timestamp).TotalDays / 60.0), 2.0)) + .2 * (x.Timestamp.Month == billTransaction.Timestamp.Month ? 1 : 0) + .2 * ((x.VendorId.HasValue && (x.VendorId == billTransaction.VendorId)) ? 1 : 0) + .3 * Math.Exp(-1 * Math.Pow(LevenshteinDistance.Compute(x.Vendor == null ? "" : x.Vendor.Name, billTransactionVendorName) / 20.0, 2.0))) * (x.BillTransaction == null ? 1.0 : 0.0) )); // debug //Debug.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}", "", billTransaction.Amount, billTransaction.Timestamp, billTransaction.VendorId, billTransactionVendorName, LevenshteinDistance.Compute(billTransactionVendorName, billTransactionVendorName)); //predictions.ForEach(p => //{ // var vendorName = p.Vendor == null ? "" : p.Vendor.Name; // Debug.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}", p.Id, p.Amount, p.Timestamp, p.VendorId, vendorName, LevenshteinDistance.Compute(vendorName, billTransactionVendorName)); //}); // order by confidence result.Result = confidences .OrderByDescending(x => x.Item2) .Take(5) .ToList(); } return result; }