public async Task <ActionResult <IEnumerable <Currency> > > GetCurrencies() { if (String.IsNullOrEmpty(HttpContext.Session.GetString("currencyCode"))) { HttpContext.Session.SetString("currencyCode", "SEK"); HttpContext.Session.SetString("currencyRate", "1"); } var currencyList = await _context.Currencies.ToListAsync(); if (currencyList.FirstOrDefault().LastUpdated.AddHours(24) < DateTimeOffset.UtcNow) { var currencyRates = await CurrencyManager.GetCurrencyRates(); var currencies = await _context.Currencies.ToListAsync(); currencies.ForEach(currency => { foreach (KeyValuePair <string, double> item in currencyRates.Rates) { if (item.Key == currency.CurrencyCode) { currency.CurrencyRate = item.Value; currency.LastUpdated = DateTimeOffset.UtcNow; } } }); await _context.SaveChangesAsync(); } return(currencyList); }
public async Task <IActionResult> AprovaUser(long id) { var user = await _context.Users.SingleAsync(s => s.Id == id); user.Status = Status.Aprovado; await _context.SaveChangesAsync(); return(Json(new { status = 200, mensagem = "Ok" })); }
public async Task <IActionResult> Create(JobCategory category) { if (ModelState.IsValid) { _context.Add(category); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(category)); }
public async Task <IActionResult> Create([Bind("ID,Title,Content,CreateTime,ImageUrl")] Blogposts blogposts) { if (ModelState.IsValid) { _context.Add(blogposts); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(blogposts)); }
public async Task <IActionResult> Create([Bind("Id,FirstName,LastName,Username,Password,StreetAdress,PostNumber,City,Country,Email,Currency,CreatedAt,PhoneNumber")] User user) { if (ModelState.IsValid) { _context.Add(user); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(user)); }
public async Task <IActionResult> Create([Bind("ID,CompanyName,Telephone,JobName,JobCategoryId,SubCategoryId,JobLocation,Salary,Description,Summary")] Jobs jobs) { if (ModelState.IsValid) { _context.Add(jobs); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["JobCategoryId"] = new SelectList(_context.Category, "Id", "Name", jobs.JobCategoryId); ViewData["JobLocation"] = new SelectList(_context.Set <JobLocation>(), "Id", "CityName", jobs.JobLocation); ViewData["SubCategoryId"] = new SelectList(_context.SubCategory, "Id", "Name", jobs.SubCategoryId); return(View(jobs)); }
public async Task <IActionResult> Create(SubCategoryAndCategoryViewModel model) { if (ModelState.IsValid) { var doesSubCategoryExists = _db.SubCategory.Where(s => s.Name == model.SubCategory.Name).Count(); var doesSubCatAndCatExists = _db.SubCategory.Where(s => s.Name == model.SubCategory.Name && s.CategoryId == model.SubCategory.CategoryId).Count(); if (doesSubCategoryExists > 0 && model.isNew) { //error StatusMessage = "Error : Sub Category Name already Exists"; } else { if (doesSubCategoryExists == 0 && !model.isNew) { //error StatusMessage = "Error : Sub Category does not exists"; } else { if (doesSubCatAndCatExists > 0) { //error StatusMessage = "Error : Category and Sub Cateogry combination exists"; } else { _db.Add(model.SubCategory); await _db.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } } } SubCategoryAndCategoryViewModel modelVM = new SubCategoryAndCategoryViewModel() { CategoryList = _db.Category.ToList(), SubCategory = model.SubCategory, SubCategoryList = _db.SubCategory.OrderBy(p => p.Name).Select(p => p.Name).ToList(), StatusMessage = StatusMessage }; return(View(modelVM)); }
public async Task <IActionResult> AddReviewToProduct(int productId, int stars, string description) { var currentUser = await GetCurrentUserAsync(); await _context.Reviews.AddAsync( new Review { ProductId = productId, UserId = currentUser.Id, Stars = stars, Description = description } ); await _context.SaveChangesAsync(); return(Redirect(Request.Headers["Referer"].ToString())); }
public async Task <bool> CadastrarClaimParaUsuario(IdentityUserClaim <Guid> userClaim) { if (!ExecutarValidacao(new UserClaimValidations(), userClaim)) { return(false); } if (await UsuarioPossuiClaim(userClaim.UserId, userClaim.ClaimType)) { var mensagemErro = "O usuário já possui este claim. Atualize o registro invés de cadastrar um novo"; _notificador.Handle(new Notificacao(mensagemErro)); return(false); } await _contexto.UserClaims.AddAsync(userClaim); await _contexto.SaveChangesAsync(); return(true); }
public async Task <ActionResult <Transaction> > PutTransaction(long id, Transaction transaction) { if (id != transaction.Id) { return(BadRequest()); } CategoryValidator validator = new CategoryValidator(); if (validator.CategoryIsValid(transaction)) { _context.Entry(transaction).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TransactionExists(id)) { return(NotFound()); } else { throw; } } return(transaction); } string errorMessage = validator.Message(transaction.Direction); return(BadRequest(new { error = errorMessage })); }
public async Task SeedAsync(IdentityAppContext context, IHostingEnvironment env, ILogger <IdentityDbContextSeed> logger, IOptions <AppSettings> settings, int?retry = 0) { int retryForAvaiability = retry.Value; try { var useCustomizationData = settings.Value.UserCustomizationData; var contentRootPath = env.ContentRootPath; var webroot = env.WebRootPath; if (!context.Users.Any()) { context.Users.AddRange(useCustomizationData ? GetUsersFromFile(contentRootPath, logger) : GetDefaultUser()); await context.SaveChangesAsync(); } if (useCustomizationData) { //GetPreconfiguredImages(contentRootPath, webroot, logger); } } catch (Exception ex) { if (retryForAvaiability < 10) { retryForAvaiability++; logger.LogError(ex.Message, $"There is an error migrating data for ApplicationDbContext"); await SeedAsync(context, env, logger, settings, retryForAvaiability); } } }
public async Task <IActionResult> Index(IndexViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var email = user.Email; if (model.Email != email) { var setEmailResult = await _userManager.SetEmailAsync(user, model.Email); if (!setEmailResult.Succeeded) { throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'."); } } var userInDb = _db.Users.Where(u => u.Email.Equals(model.Email)).FirstOrDefault(); userInDb.FirstName = model.FirstName; userInDb.LastName = model.LastName; userInDb.PhoneNumber = model.PhoneNumber; await _db.SaveChangesAsync(); StatusMessage = "Your profile has been updated"; return(RedirectToAction(nameof(Index))); }
public async Task SeedAsync(IdentityAppContext context, IHostingEnvironment env, ILogger <IdentityDbContextSeed> logger, IOptions <AppSettings> settings, UserManager <ApplicationUser> manager, RoleManager <IdentityRole> roleManager, int?retry = 0) { int retryForAvaiability = retry.Value; try { var useCustomizationData = settings.Value.UserCustomizationData; var contentRootPath = env.ContentRootPath; var webroot = env.WebRootPath; var defaultUsers = GetDefaultUser(); if (!context.Users.Any()) { context.Users.AddRange(useCustomizationData ? GetUsersFromFile(contentRootPath, logger) : defaultUsers); await context.SaveChangesAsync(); } var roles = new List <IdentityRole>() { new IdentityRole() { Name = "Admin" }, new IdentityRole() { Name = "HR" }, new IdentityRole() { Name = "Candidate" }, new IdentityRole() { Name = "Employee" }, new IdentityRole() { Name = "ExternalUser" }, }; if (!context.Roles.Any()) { foreach (var role in roles) { var result = await roleManager.CreateAsync(role); } var defaultAdmin = defaultUsers.FirstOrDefault(u => u.Email.ToLower().Contains("admin")); var asAdmin = await manager.AddToRoleAsync(defaultAdmin, "Admin"); } if (useCustomizationData) { //GetPreconfiguredImages(contentRootPath, webroot, logger); } } catch (Exception ex) { if (retryForAvaiability < 10) { retryForAvaiability++; logger.LogError(ex.Message, $"There is an error migrating data for ApplicationDbContext"); await SeedAsync(context, env, logger, settings, manager, roleManager, retryForAvaiability); } } }
public async Task <int> SaveAsync() { return(await _dbContext.SaveChangesAsync()); }
public async Task <ActionResult> Confirmation(string totalPrice, string paymentType, string deliveryTime, string email) { var sumTotalPrice = double.Parse(totalPrice); var currentUser = await GetCurrentUserAsync(); var userOrders = await _context.Orders.Where(x => x.User.Id == currentUser.Id).ToListAsync(); if (!HttpContext.User.IsInRole("KeyCustomer") && userOrders.Count() > 2) { await UserMgr.AddToRoleAsync(currentUser, "KeyCustomer"); } switch (deliveryTime) { case "2-5 days": sumTotalPrice += 60; break; case "5-10 days": sumTotalPrice += 40; break; case "30 days": sumTotalPrice += 20; break; } if (paymentType == "Invoice") { sumTotalPrice += 50; } if (await UserMgr.IsInRoleAsync(currentUser, "KeyCustomer")) { sumTotalPrice *= 0.9; ViewBag.keyCustomer = "You recived a 10% discount since you have been a loyal customer"; } order = new Order { User = await _context.Users.FindAsync(currentUser.Id), PaymentOption = paymentType, TotalAmount = sumTotalPrice, DeliveryOption = deliveryTime, Confirmed = true }; orderItems = new List <OrderItem>(); cartItems = HttpContext.Session.GetString("cartItems"); foreach (var id in cartItems) { if (!orderItems.Where(p => p.Product.Id == id - '0').Any()) { orderItems.Add( new OrderItem { Order = order, Product = await _context.Products.FindAsync(id - '0'), Quantity = cartItems.Count(p => p.ToString() == id.ToString()) }); } } await _context.AddRangeAsync(orderItems); await _context.SaveChangesAsync(); ReciveConfirmationViaEmail(orderItems, email); ViewBag.totalPrice = sumTotalPrice.ToString(); ViewBag.paymentType = paymentType; ViewBag.delivery = deliveryTime; ViewBag.orderId = order.Id; ViewBag.HideCurrencyConversion = true; HttpContext.Session.SetString("cartItems", ""); return(View(orderItems)); }
public async Task <IActionResult> Cadastro(CadastroSecretarioViewModel model) { if (ModelState.IsValid) { try { var distribuidorExiste = _context.Users.Include(a => a.DadosSecretario).Any(a => a.Email.Equals(model.Email)); if (distribuidorExiste) { return(View(model)); } Endereco endereco = new Endereco { Logradouro = model.Logradouro, Numero = model.Numero.ToString(), Complemento = model.Complemento, Bairro = model.Bairro, CEP = model.CEP.ToString(), Cidade = model.Cidade, Estado = model.Estado, CreatedAt = DateTime.Now }; AppUser admin = new AppUser { Nome = model.Nome, Email = model.Email, UserName = model.Email, DadosSecretario = new DadosSecretario { Nome = model.Nome, RG = model.RG, Telefone = model.Telefone, CreatedAt = DateTime.Now, }, Endereco = endereco, Ativo = true, EmailConfirmed = false, CreatedAt = DateTime.Now }; admin.Status = Status.Submetido; admin.Tipo = Tipo.Secretario; var result = await _userManager.CreateAsync(admin, model.Password); if (result.Succeeded) { string[] role = new string[] { ApplicationRoles.Secretario }; await _userManager.AddToRolesAsync(admin, role); //string confirmationToken = _userManager.GenerateEmailConfirmationTokenAsync(distribuidor).Result; //string confirmationLink = Url.Action("ConfirmEmail", "Account", new { userId = distribuidor.Id, token = confirmationToken }, protocol: HttpContext.Request.Scheme); //confirmationLink = confirmationLink.Replace("/Distribuidor/", "/"); //_emailSender.SendConfirmationEmail(distribuidor.Email, confirmationLink); await _context.SaveChangesAsync(); await _signInManager.SignInAsync(admin, false); } await _context.SaveChangesAsync(); return(RedirectToAction("Index", "Dashboard", new { Id = admin.Id, area = "Secretario" })); } catch (Exception e) { //erro ModelState.AddModelError("Oops", e.Message); return(View(model)); } } //erro return(View(model)); }
public async Task <ActionResult> Confirmation(string totalPrice, string paymentType, string deliveryTime, string email) { currentUser = await GetCurrentUserAsync(); double paymentDeliveryOptTotal = 0; switch (deliveryTime) { case "2-5 days": paymentDeliveryOptTotal = 60; break; case "5-10 days": paymentDeliveryOptTotal = 40; break; case "30 days": paymentDeliveryOptTotal = 20; break; } if (paymentType == "Invoice") { paymentDeliveryOptTotal += 50; } order = new Order { User = await _context.Users.FindAsync(currentUser.Id), PaymentOption = paymentType, TotalAmount = (double.Parse(totalPrice) + paymentDeliveryOptTotal), DeliveryOption = deliveryTime, Confirmed = true }; orderItems = new List <OrderItem>(); cartItems = HttpContext.Session.GetString("cartItems"); foreach (var id in cartItems) { if (!orderItems.Where(p => p.Product.Id == id - '0').Any()) { orderItems.Add( new OrderItem { Order = order, Product = await _context.Products.FindAsync(id - '0'), Quantity = cartItems.Count(p => p.ToString() == id.ToString()) }); } } await _context.AddRangeAsync(orderItems); await _context.SaveChangesAsync(); ReciveConfirmationViaEmail(orderItems, email); ViewBag.totalPrice = totalPrice; ViewBag.paymentType = paymentType; ViewBag.delivery = deliveryTime; ViewBag.orderId = order.Id; ViewBag.HideCurrencyConversion = true; HttpContext.Session.SetString("cartItems", ""); return(View(orderItems)); }
public async Task SaveChanges() { await _context.SaveChangesAsync(); }