ActionOutput ICategoryManager.AddCategory(AddCategoryModel model) { ActionOutput res = new ActionOutput(); try { var already = Context.Categories.Where(p => p.Name == model.Name).Any(); if (!already) { Category _category = new Category(); _category.Description = model.Description; _category.IsDeleted = false; _category.Name = model.Name; _category.CreatedOn = DateTime.Now; Context.Categories.Add(_category); Context.SaveChanges(); return(SuccessResponse("Category Added Successfully")); } else { return(ErrorResponse("Category with the same name already exists.")); } } catch (Exception ex) { return(ErrorResponse("Some Error Occurred")); } }
ActionOutput IUserManager.UpdateUserDetails(UserDetailModel model) { ActionOutput res = new ActionOutput(); var Data = Context.UserTbls.Where(p => p.Id == model.UserID).FirstOrDefault(); var Exists = Context.UserTbls.Where(p => p.Id != model.UserID && p.Email == model.Email.Trim()).FirstOrDefault(); if (Exists == null) { Data.Email = model.Email; Data.FirstName = model.FirstName; Data.LastName = model.LastName; Context.SaveChanges(); return(new ActionOutput { Status = ActionStatus.Successfull, Message = "Updated Successfully" }); } else { return(new ActionOutput { Status = ActionStatus.Error, Message = "Email already exists." }); } //} //catch (Exception ex) //{ // res.Status = ActionStatus.Error; // res.Message = "Some Error Occurred"; //} return(res); }
public JsonResult ForgetPassword(ForgetPasswordModel model) { var data = new ActionOutput(); var user = _userManager.GetUserByEmail(model.UserEmail); if (user != null) { var resetPassword = _userManager.ResetPassword(user); if (resetPassword == true) { data.Message = "Please check your email"; data.Status = ActionStatus.Successfull; } else { data.Message = "Email sent request failed."; data.Status = ActionStatus.Error; } } else { data.Message = "This email doesnt exist"; data.Status = ActionStatus.Error; } return(Json(data, JsonRequestBehavior.AllowGet)); }
ActionOutput <UserModel> IUserManager.OTPLogin(LoginModel model) { ActionOutput <UserModel> res = new ActionOutput <UserModel>(); try { var exists = Context.UserTbls.Where(p => p.Phone == model.ContactNo && (p.Status == (int)UserStatuss.Approved || p.Status != (int)UserStatuss.Subscribed)).FirstOrDefault(); if (exists != null) { if (exists.OTP == model.OTP) { res.Object = new UserModel(exists); res.Status = ActionStatus.Successfull; res.Message = "Login Successfull"; } else { res.Message = "Invalid OTP"; res.Status = ActionStatus.Error; } } else { res.Status = ActionStatus.Error; res.Message = "Contact No. not registered."; } } catch (Exception ex) { res.Status = ActionStatus.Error; res.Message = "Some Error Occurred"; } return(res); }
ActionOutput IUserManager.UpdateUserProfile(UserModel model) { ActionOutput res = new ActionOutput(); try { var exists = Context.UserTbls.Where(p => p.Id == model.UserID).FirstOrDefault(); if (exists != null) { exists.LastName = model.LastName; exists.Latitute = model.Latitute; exists.Longitute = model.Longitute; exists.Province = model.Province; exists.Address = model.Address; exists.City = model.City; exists.Email = model.Email; exists.FirstName = model.FirstName; Context.SaveChanges(); res.Status = ActionStatus.Successfull; res.Message = "User Details updated successfully."; } else { res.Status = ActionStatus.Error; res.Message = "User doesn't exists"; } } catch (Exception ex) { res.Status = ActionStatus.Error; res.Message = "Some Error Occurred"; } return(res); }
public HttpResponseMessage ForgotPassword(ForgetPasswordModel model) { var data = new ActionOutput(); var user = _userManager.GetUserByEmail(model.UserEmail); if (user != null) { var resetPassword = _userManager.ResetPassword(user); if (resetPassword == true) { data.Message = "Please check your email"; data.Status = ActionStatus.Successfull; } else { data.Message = "Password reset process interrupted due to some reason. Please contact HelpDesk."; data.Status = ActionStatus.Error; } } else { data.Message = "This email doesnt exist"; data.Status = ActionStatus.Error; } return(new JsonContent(data.Message, data.Status).ConvertToHttpResponseOK()); }
/// <summary> /// 更新分类 /// </summary> /// <param name="id"></param> /// <param name="dto"></param> /// <returns></returns> public async Task <ActionOutput <string> > UpdateCategory(int id, CategoryDto dto) { using (var uow = UnitOfWorkManager.Begin()) { var output = new ActionOutput <string>(); var category = new Category { Id = id, CategoryName = dto.CategoryName, DisplayName = dto.DisplayName }; var result = await _categoryRepository.UpdateAsync(category); await uow.CompleteAsync(); if (result.IsNull()) { output.AddError("更新分类出错了~~~"); } else { output.Result = "success"; } return(output); } }
public ActionResult MyRecipient() { ActionOutput <RecipientGroupModel> modal = _recipientManager.GetRecipientByAlphabetic(LOGGEDIN_USER.UserID); ViewBag.Membership = _paymentManager.GetTransactionDetailsByUserID(LOGGEDIN_USER.UserID); return(View(modal)); }
public async Task <IOutput> Handle(ChangeRoleInput request, CancellationToken cancellationToken) { var currentUesrId = (await _currentUserProvider.GetCurrentUser()).Id; var user = await _userManager.FindByIdAsync(request.UserId.ToString()); if (user is null) { return(ActionOutput.Error("Пользователя не существует.")); } if (user.Id == currentUesrId) { return(ActionOutput.Error("Нельзя менять себе роль")); } var newRole = request.NewRole; var userRoles = await _userManager.GetRolesAsync(user); var addResult = await _userManager.AddToRoleAsync(user, Enum.GetName(newRole)); var removeResult = await _userManager.RemoveFromRolesAsync(user, userRoles); return(ActionOutput.Success); }
ActionOutput IMotherManager.UpdateMotherDishDailySchedule(List <MotherDishScheduleModel> model) { ActionOutput res = new ActionOutput(); try { int UserId = model.FirstOrDefault().UserId; var dishsch = (from p in Context.MotherDishDailySchedules join m in Context.MotherDishes on p.MotherDishId equals(m.Id) join mo in Context.MotherTbls on m.MotherId equals(mo.Id) where mo.UserId == UserId && p.Date == DateTime.Now select p).ToList(); if (dishsch.Count <= 0) { var MotherDetails = Context.MotherTbls.Where(p => p.UserId == UserId).FirstOrDefault(); if (MotherDetails != null) { List <MotherDishDailySchedule> list = new List <MotherDishDailySchedule>(); foreach (var item in model) { MotherDishDailySchedule mdds = new MotherDishDailySchedule(); mdds.Availabilty = item.Availabilty; mdds.Date = item.Date; mdds.MotherDishId = item.MotherDishId; mdds.Quantity = item.Quantity; mdds.Type = item.Type; list.Add(mdds); } Context.MotherDishDailySchedules.AddRange(list); Context.SaveChanges(); res.Status = ActionStatus.Successfull; res.Message = "Mother's Daily Dish Scheduled updated Successfully."; } else { res.Status = ActionStatus.Error; res.Message = "Mother doesn't exists"; } } else { foreach (var item in dishsch) { var partdata = model.Where(p => p.MotherDishId == item.MotherDishId).FirstOrDefault(); if (partdata != null) { item.Availabilty = partdata.Availabilty; item.Date = partdata.Date; item.Quantity = partdata.Quantity; item.Type = partdata.Type; } } Context.SaveChanges(); res.Status = ActionStatus.Successfull; res.Message = "Mother's Daily Dish Schedule updated Successfully."; } } catch (Exception ex) { res.Status = ActionStatus.Error; res.Message = "Some Error Occurred"; } return(res); }
ActionOutput IMotherManager.SaveMotherAnswers(List <MotherAnswer> model) { ActionOutput res = new ActionOutput(); try { foreach (var item in model) { MotherAnswer _motherans = new MotherAnswer(); _motherans.Answer = item.Answer; _motherans.MotherId = item.MotherId; _motherans.QuestionId = item.QuestionId; Context.MotherAnswers.Add(_motherans); } Context.SaveChanges(); res.Status = ActionStatus.Successfull; res.Message = "Your answers are submitted to admin."; } catch (Exception ex) { res.Status = ActionStatus.Error; res.Message = "Some Error Occurred"; } return(res); }
public static void EncryptNtag(string savePath, AmiiboTag amiibo) { const string missingSavePath = "Missing save path"; const string missingAmibo = "Can't encrypt amiibo if no amiibo was given, DUH!"; if (string.IsNullOrEmpty(savePath)) { Console.WriteLine(missingSavePath); ActionOutput?.Invoke(null, new ActionOutputEventArgs(false, missingSavePath)); return; } if (amiibo == null) { Console.WriteLine(missingAmibo); ActionOutput?.Invoke(null, new ActionOutputEventArgs(false, missingAmibo)); return; } try { byte[] encryptedNtagData = amiibo.EncryptWithKeys(); File.WriteAllBytes(savePath, encryptedNtagData); } catch (Exception ex) { string errorEncrypting = $"Error while encrypting {amiibo.Amiibo?.AmiiboSetName}"; ActionOutput?.Invoke(null, new ActionOutputEventArgs(false, errorEncrypting + Environment.NewLine + Environment.NewLine + ex.Message)); Console.WriteLine(errorEncrypting); Console.WriteLine(ex.Message); } }
public static AmiiboTag LoadAndDecryptNtag(string amiiboPath) { var amiiboFileNotFound = $"{amiiboPath} not found!"; if (!File.Exists(amiiboPath)) { Console.WriteLine(amiiboFileNotFound); ActionOutput?.Invoke(null, new ActionOutputEventArgs(false, amiiboFileNotFound)); return(null); } byte[] encryptedNtagData = File.ReadAllBytes(amiiboPath); try { return(AmiiboTag.DecryptWithKeys(encryptedNtagData)); } catch (Exception ex) { string errorDecrypting = $"Error while decrypting {amiiboPath}"; ActionOutput?.Invoke(null, new ActionOutputEventArgs(false, errorDecrypting + Environment.NewLine + Environment.NewLine + ex.Message)); Console.WriteLine(errorDecrypting); Console.WriteLine(ex.Message); } return(null); }
ActionOutput ICategoryManager.ModifyCategory(EditCategoryModel model) { ActionOutput res = new ActionOutput(); try { var exists = Context.Categories.Where(p => p.Id == model.id).FirstOrDefault(); if (exists != null) { var already = Context.Categories.Where(p => p.Name == model.Name && p.Id != model.id).Any(); if (!already) { exists.Description = model.Description; exists.Name = model.Name; Context.SaveChanges(); return(SuccessResponse("Category updated Successfully")); } else { return(ErrorResponse("Category already exists with Same Name")); } } else { return(ErrorResponse("Category doesn't exists")); } } catch (Exception ex) { return(ErrorResponse("Category doesn't exists")); } }
ActionOutput <EditDishModel> IDishManager.GetDishDetails(int Id) { ActionOutput <EditDishModel> res = new ActionOutput <EditDishModel>(); try { var exists = Context.Dishes.Where(p => p.Id == Id && p.IsDeleted == false).FirstOrDefault(); if (exists != null) { res.Object = new EditDishModel(exists); res.Status = ActionStatus.Successfull; res.Message = "Dish details fetched successfully."; } else { res.Status = ActionStatus.Error; res.Message = "Dish doesn't exists"; } } catch (Exception ex) { res.Status = ActionStatus.Error; res.Message = "Some Error Occurred"; } return(res); }
public async Task <IOutput> Handle(AddCommentInput request, CancellationToken cancellationToken) { var currentUser = await _currentUserProvider.GetCurrentUser(); if (currentUser is null) { return(ActionOutput.Error("Пользователь не найден")); } var lesson = await _context.Lessons.FirstOrDefaultAsync( x => x.Id == request.LessonId, cancellationToken : cancellationToken); if (lesson is null) { return(ActionOutput.Error("Урок не найден")); } var comment = new Entity.Comment(request.Text, currentUser, lesson); await _context.Comments.AddAsync(comment, cancellationToken); await _context.SaveChangesAsync(cancellationToken); return(ActionOutput.SuccessData(comment.Id)); }
ActionOutput IDishManager.AddDish(AddDishModel model) { ActionOutput res = new ActionOutput(); try { var already = Context.Dishes.Where(p => p.Name == model.Name).Any(); if (!already) { Dish _dish = new Dish(); _dish.CategoryId = model.CategoryId; _dish.Description = model.Description; _dish.IsDeleted = false; _dish.Name = model.Name; _dish.CreatedDate = DateTime.Now; Context.Dishes.Add(_dish); Context.SaveChanges(); res.Status = ActionStatus.Successfull; res.Message = "Dish Added Successfully"; } else { res.Status = ActionStatus.Error; res.Message = "Dish with the same name already exists."; } } catch (Exception ex) { res.Status = ActionStatus.Error; res.Message = "Some Error Occurred"; } return(res); }
public async Task <IOutput> Handle(GetUsersInput request, CancellationToken cancellationToken) { var search = request.Search ?? ""; var page = request.Page ?? 1; var limit = request.Limit ?? 16; var usersCount = await _context.Users .AsNoTracking() .WithRoles() .Include(x => x.SubjectSertificates) .Where(x => x.Mail.Contains(search) || x.Nick.Contains(search)) .CountAsync(cancellationToken: cancellationToken); _httpContextAccessor.HttpContext.Response.Headers.Add("X-Total-Count", usersCount.ToString()); var users = await _context.Users .AsNoTracking() .WithRoles() .Include(x => x.SubjectSertificates) .Where(x => x.Mail.Contains(search) || x.Nick.Contains(search)) .Skip((page - 1) * limit) .Take(limit) .ToListAsync(cancellationToken: cancellationToken); return(ActionOutput.SuccessData(_mapper.Map <List <Entity.User>, List <UserViewDetailed> >(users))); }
public async Task <IActionResult> DispatchAsync <TRequest>(TRequest request) where TRequest : IUseCaseInput { using var services = _serviceProvider.CreateScope(); var validator = services.ServiceProvider.GetService <IValidator <TRequest> >(); if (validator is null) { throw new Exception("Validator wasn't found"); } var validationResult = await validator.ValidateAsync(request, CancellationToken.None); if (!validationResult.IsValid) { var actionPresenter = services.ServiceProvider.GetService <IPresenter <ActionOutput> >(); return(actionPresenter.Present(ActionOutput.Error(validationResult.Errors.First().ErrorMessage))); } var result = await _mediator.Send(request); var presenterType = typeof(IPresenter <>).MakeGenericType(result.GetType()); var presenter = services.ServiceProvider.GetService(presenterType); if (presenter is null) { throw new Exception("Presenter for this output was not found " + result.GetType().Name); } var method = presenter.GetType().GetMethod(nameof(IPresenter <IOutput> .Present), new [] { result.GetType() }); return((IActionResult)method !.Invoke(presenter, new object[] { result })); }
public async Task <IOutput> Handle(GetPracticesInput request, CancellationToken cancellationToken) { var search = request.Search ?? ""; var limit = request.Limit ?? 16; var page = request.Page ?? 1; var practicesCount = await _context.PracticeOrders.AsNoTracking() .Include(x => x.Author) .Include(x => x.Lesson) .Where(x => x.IsDone == false && x.Author.Nick.Contains(search)) .OrderBy(x => x.CreatedDate) .CountAsync(cancellationToken); _httpContextAccessor.HttpContext.Response.Headers.Add("X-Total-Count", practicesCount.ToString()); var practices = await _context.PracticeOrders .AsNoTracking() .Include(x => x.Author) .Include(x => x.Lesson) .Where(x => x.IsDone == false && x.Author.Nick.Contains(search)) .OrderBy(x => x.CreatedDate) .Skip((page - 1) * limit) .Take(limit) .ToListAsync(cancellationToken); return(ActionOutput.SuccessData( _mapper.Map <List <Entity.PracticeOrder>, List <GetPracticesOutput> >(practices))); }
public JsonResult Login(LoginModal model) { //to do: Implement user login //var data = _userManager.AdminLogin(model); var data = new ActionOutput <UserDetails>(); var adminLogin = _userManager.AdminLogin(model); if (adminLogin != null) { data.Status = ActionStatus.Successfull; data.Object = new UserDetails { UserID = adminLogin.UserId, FirstName = model.UserName, UserName = model.UserName, IsAuthenticated = true }; } else { data.Status = ActionStatus.Error; data.Message = "Invalid Credentials."; } if (data.Status == ActionStatus.Successfull) { var user_data = data.Object; CreateCustomAuthorisationCookie(model.UserName, false, new JavaScriptSerializer().Serialize(user_data)); } return(Json(data, JsonRequestBehavior.AllowGet)); }
private void EncodeAction() { ActionOutput.SafeCopyToDevice(); Array.Copy(new int[MyTicTacToeWorld.NO_POSITIONS], ActionOutput.Host, MyTicTacToeWorld.NO_POSITIONS); ActionOutput.Host[m_selectedAction] = (int)Me; ActionOutput.SafeCopyToDevice(); }
ActionOutput <UserModel> IUserManager.AuthenticateUser(LoginModel model) { ActionOutput <UserModel> res = new ActionOutput <UserModel>(); try { var HashPass = UtilitiesHelp.EncryptPassword(model.ContactNo, true); var exists = Context.UserTbls.Where(p => p.Phone == model.ContactNo && p.Password == HashPass && (p.Status == (int)UserStatuss.Approved || p.Status != (int)UserStatuss.Subscribed)).FirstOrDefault(); if (exists != null) { res.Object = new UserModel(exists); res.Status = ActionStatus.Successfull; res.Message = "Login Successfull"; } else { res.Status = ActionStatus.Error; res.Message = "User doesn't exists"; } } catch (Exception ex) { res.Status = ActionStatus.Error; res.Message = "Some Error Occurred"; } return(res); }
public async Task <ActionOutput <Notes> > UpdateNote(Notes note) { var result = new ActionOutput <Notes>(); var existingNote = await context.StickyNotes.FindAsync(note.NoteId); if (existingNote != null) { existingNote.NoteTitle = note.NoteTitle; existingNote.NoteBody = note.NoteBody; existingNote.NoteFooter = note.NoteFooter; existingNote.UpdatedOn = DateTime.Now; existingNote.NoteForeGroundColor = note.NoteForeGroundColor; existingNote.NoteBackGroundColor = note.NoteBackGroundColor; await context.SaveChangesAsync(); result.Status = ActionStatus.Successfull; result.Message = "Sticky Note has been updated successfully"; result.Object = existingNote; } else { result.Status = ActionStatus.Error; result.Message = "Sticky Note has not been updated"; } return(result); }
ActionOutput <UserDetailModel> IUserManager.GetUserDetails(int Id) { ActionOutput <UserDetailModel> res = new ActionOutput <UserDetailModel>(); try { var exists = Context.UserTbls.Where(p => p.Id == Id).FirstOrDefault(); if (exists != null) { res.Object = new UserDetailModel(exists); res.Status = ActionStatus.Successfull; res.Message = "User Details fetched successfully."; } else { res.Status = ActionStatus.Error; res.Message = "User doesn't exists"; } } catch (Exception ex) { res.Status = ActionStatus.Error; res.Message = "Some Error Occurred"; } return(res); }
/// <summary> /// 根据Id获取文章详细数据 /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task <ActionOutput <GetPostForAdminDto> > GetPostForAdmin(int id) { var output = new ActionOutput <GetPostForAdminDto>(); using (var uow = UnitOfWorkManager.Begin()) { var post = await _postRepository.FirstOrDefaultAsync(x => x.Id == id); if (post.IsNull()) { output.AddError("找了找不到了~~~"); return(output); } var tags = from post_tags in await _postTagRepository.GetAllListAsync() join tag in await _tagRepository.GetAllListAsync() on post_tags.TagId equals tag.Id where post_tags.PostId == post.Id select tag.TagName; await uow.CompleteAsync(); var result = post.MapTo <GetPostForAdminDto>(); result.Tags = string.Join(",", tags); result.Url = result.Url.Split("/").Where(x => x.IsNotNullOrEmpty()).Last(); output.Result = result; return(output); } }
/// <summary> /// 批量添加热榜 /// </summary> /// <param name="dtos"></param> /// <returns></returns> public async Task <ActionOutput <string> > BulkInsertHotNews(IList <InsertHotNewsInput> dtos) { using (var uow = UnitOfWorkManager.Begin()) { var output = new ActionOutput <string>(); await _hotNewsRepository.DeleteAsync(x => x.SourceId == dtos.FirstOrDefault().SourceId); var hotNews = dtos.Select(x => new Core.Domain.HotNews.HotNews { Id = GenerateGuid(), Title = x.Title, Url = x.Url, SourceId = x.SourceId, Time = DateTime.Now }).ToList(); var result = await _hotNewsRepository.BulkInsertHotNewsAsync(hotNews); await uow.CompleteAsync(); if (result) { output.Result = "success"; } else { output.AddError("新增HotNews出错了~~~"); } return(output); } }
ActionOutput IDishManager.DeleteDish(int id) { ActionOutput res = new ActionOutput(); try { var exists = Context.Dishes.Where(p => p.Id == id && p.IsDeleted == false).FirstOrDefault(); if (exists != null) { exists.IsDeleted = true; Context.SaveChanges(); res.Status = ActionStatus.Successfull; res.Message = "Dish Deleted Successfully"; } else { res.Status = ActionStatus.Error; res.Message = "Dish doesn't exists"; } } catch (Exception ex) { res.Status = ActionStatus.Error; res.Message = "Some Error Occurred"; } return(res); }
/// <summary> /// 新增标签日志 /// </summary> /// <param name="dto"></param> /// <returns></returns> public async Task <ActionOutput <string> > InsertSignatureLog(SignatureLogDto dto) { using (var uow = UnitOfWorkManager.Begin()) { var output = new ActionOutput <string>(); var log = new SignatureLog { Name = dto.Name, Type = dto.Type, Url = dto.Url, Ip = dto.Ip, Time = DateTime.Now }; var result = await _signatureLogRepository.InsertAsync(log); await uow.CompleteAsync(); if (result.IsNull()) { output.AddError("新增标签出错了~~~"); } else { output.Result = "success"; } return(output); } }
/// <summary> /// 新增好文 /// </summary> /// <param name="dto"></param> /// <returns></returns> public async Task <ActionOutput <string> > InsertNiceArticle(NiceArticleDto dto) { using (var uow = UnitOfWorkManager.Begin()) { var output = new ActionOutput <string>(); var niceArticle = new Core.Domain.NiceArticle.NiceArticle { Title = dto.Title, Author = dto.Author, Source = dto.Source, Url = dto.Url, CategoryId = dto.CategoryId, Time = dto.Time }; var result = await _niceArticleRepository.InsertAsync(niceArticle); await uow.CompleteAsync(); if (result.IsNull()) { output.AddError("新增标签出错了~~~"); } else { output.Result = "success"; } return(output); } }