public async Task <IActionResult> Post(MemberViewModel userModel) { var identity = await _userManager.FindByNameAsync(userModel.Email); if (identity == null) { var result = await AddUserIdentity(userModel); if (result.Succeeded == true) { var user = _mapper.Map <MemberViewModel, Member>(userModel); user.IdentityID = _userManager.FindByNameAsync(user.Email).Result.Id; _context.Add(user); await _context.SaveChangesAsync(); await AddTrainingPersonel(user); return(Ok(new RegisterResult { Successful = true })); } else { return(Ok(new RegisterResult { Successful = false, Error = ViewResources.Register_Failure })); } } else { return(Ok(new RegisterResult { Successful = false, Error = ViewResources.User_Exists })); } }
public async Task <IActionResult> Create(ToTrinhDto requestData) { if (requestData.MaToChuc <= 0 || requestData.MaDonViHanhChinh <= 0) { throw new Exception(); } if (ModelState.IsValid) { // Tạo mẫu quan trắc var quanTrac = new QuanTrac() { MucNuocDong = requestData.MucNuocDong, MucNuocTinh = requestData.MucNuocTinh, LuuLuong = requestData.LuuLuongNuoc, ChatLuongNuoc = requestData.ChatLuongNuoc }; _context.Add(quanTrac); await _context.SaveChangesAsync(); // Tạo tờ trình requestData.NgayTao = DateTime.Now; requestData.MaQuanTrac = quanTrac.Id; var model = this.mapper.Map <ToTrinh>(requestData); _context.Add(model); await _context.SaveChangesAsync(); return(Redirect("/ToTrinh/Index")); } return(View(requestData)); }
public async Task SeedDatabaseWithSimulations() { List <Trainee> trainees = _context.Trainees.ToList(); List <Scenario> scenarios = _context.Scenarios.ToList(); foreach (var trainee in trainees) { int seed = GenerateRandomInt(3, 6); int seed2 = 0; foreach (var scenario in scenarios) { for (int i = 1; i < 12; i++) { DateTime day = new DateTime(2020, i, GenerateRandomInt(1, 30)); var traineeSim = new Simulation { TraineeID = trainee.ID, InstructorID = 1, ScenarioID = scenario.ID, Date = day, GradeSum = seed + i + seed2 }; _context.Add(traineeSim); await _context.SaveChangesAsync(); var assignedTemplates = await _context.ScenarioGradesTemplates.Where(x => x.ScenarioID == scenario.ID && x.Assigned == true).ToListAsync(); var gradeTemplates = new List <GradeTemplate>(); foreach (var assignedTemplate in assignedTemplates) { gradeTemplates.Add(assignedTemplate.GradeTemplate); } foreach (var assignedTemplate in gradeTemplates) { var grade = new Grade { TemplateID = assignedTemplate.ID, SimulationID = traineeSim.ID, Points = GenerateRandomInt(0, assignedTemplate.MaxPoints), TimeTaken = GenerateRandomInt(0, (assignedTemplate.OptimalTime + 5)), GradeTemplate = null, Simulation = null }; _context.Add(grade); await _context.SaveChangesAsync(); } } seed2++; } } }
public IActionResult Index() { var author = new Visits_counter { Date = DateTime.Now.ToString(), Role = "Anonymous", }; _context.Add(author); _context.SaveChanges(); return(View()); }
public async Task <IActionResult> Register(RegisterViewModel viewModel) { Wallet w = new Wallet() { Balance = 100 }; _dbContext.Add(w); await _dbContext.SaveChangesAsync(); WalletTransactions t = new WalletTransactions() { Name = "Initial", Amount = 100 }; t.WalletId = w.Id; _dbContext.Add(t); await _dbContext.SaveChangesAsync(); //w.Transactions = new List<WalletTransactions>(); //w.Transactions.Add(t); w.Balance = 150; _dbContext.Update(w); WalletTransactions transaction2 = new WalletTransactions() { Name = "Add Fifty", Amount = 50, WalletId = w.Id }; _dbContext.Add(transaction2); await _dbContext.SaveChangesAsync(); MoneroUser user = new MoneroUser() { Email = viewModel.Email, UserName = viewModel.Username, WalletId = w.Id }; IdentityResult result = await _userManager.CreateAsync(user, viewModel.Password); if (result.Succeeded) { return(RedirectToAction("Index", "Home")); } return(View(viewModel)); }
public async Task <IActionResult> Post(Playlist playlist, string username) { var next_id = _context.Playlist.OrderBy(p => p.id).Last().id + 1; playlist.id = next_id; UsersPlaylist up = new UsersPlaylist { id = playlist.id, username = username }; _context.Add(up); _context.Add(playlist); await _context.SaveChangesAsync(); return(Ok(playlist.title)); }
public async Task <IActionResult> SubmitStockPost(int id, int Quantity, [Optional] string newItem) { int closing_stock = Quantity; //var combineList = _context.Add_item.Where(x => x.id == id); var allFields = await _context.Add_item.FindAsync(id); int database_stock = allFields.Quantity; int itemSold = database_stock - closing_stock; int newQuantity = Quantity; if (itemSold < 0) { TempData["StockUpdateStatus1"] = "Submitted closing stock value for " + allFields.Item_name + " is incorrect."; } else { AddSession(itemSold.ToString(), itemSold.ToString()); var query = _context.Add_item.Where(x => x.id == id).Single(); //LETS UPDATE VALUES IN DATABASE query.Quantity = newQuantity; query.DateTime = DateTime.Now.ToString("yyyy-MM-dd"); _context.Update(query); await _context.SaveChangesAsync(); //LETS CALCULATE CASH MADE float price = query.Item_price; float cashMade = price * itemSold; Guid g = Guid.NewGuid(); //LETS ADD SUBMITTED STOCK TO THEIR RESPECTIVE TABLES var submitted = new Submited_stock() { item_id = id, DateTime = DateTime.Now.ToString("yyyy-MM-dd"), item_sold = itemSold, Cash_made = cashMade, User_id = g.ToString() }; _context.Add(submitted); _context.SaveChanges(); TempData["StockUpdateStatus"] = query.Item_name + " has been submitted successfully! \n Initial stock: " + database_stock + "\n Item sold: " + itemSold + "\n New stock: " + Quantity; bindSubmitItems(); } return(RedirectToAction(nameof(SubmitStock))); }
public async Task <IActionResult> Post(User user) { _context.Add(user); await _context.SaveChangesAsync(); return(Ok(user.username)); }
public async Task <ActionResult> InsertUser([FromBody] RegisterViewModel model) { try { Guid newGuid = Guid.NewGuid(); var user = new IdentityUser { Email = model.Email, UserName = model.Username, SecurityStamp = newGuid.ToString(), }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "Child"); } ChildData currentChild = getChildData(model, user.Id, newGuid); _context.Add(currentChild); await _context.SaveChangesAsync(); return(Ok(new { Username = user.UserName, response = true })); } catch (Exception e) { return(Ok(new { Error = e.Message, response = false })); } }
public async Task <IActionResult> Create(Page page) { if (ModelState.IsValid) { page.Slug = page.Title.ToLower().Replace(" ", "-"); page.Sorting = 100; var slug = await context.Pages.FirstOrDefaultAsync(x => x.Slug == page.Slug); if (slug != null) { ModelState.AddModelError("", "The page already exists."); return(View(page)); } context.Add(page); await context.SaveChangesAsync(); TempData["Success"] = "The page has been added!"; return(RedirectToAction("Index")); } return(View(page)); }
public async Task <ActionResult> Creacion([FromForm] ActorCreacionDTO actorCreacion) { var entidad = _mapper.Map <Actor>(actorCreacion); if (actorCreacion.Foto != null) { using (var memoryString = new MemoryStream()) { await actorCreacion.Foto.CopyToAsync(memoryString); var contenido = memoryString.ToArray(); var extension = Path.GetExtension(actorCreacion.Foto.FileName); entidad.Foto = await almacenadorArchivos.GuardarArchivo(contenido, extension, contenedor, actorCreacion.Foto.ContentType); } } _context.Add(entidad); await _context.SaveChangesAsync(); var dto = _mapper.Map <ActorDTO>(entidad); return(new CreatedAtRouteResult("obtenerActor", new { id = entidad.Id }, dto)); }
public IActionResult OnPostMarkCompleted(int id, int stageID) { PatientLog patientStage = db.PatientLogs.FirstOrDefault(p => p.PatientID == id && p.StageID == stageID); Stage currentstage = db.Stage.Find(stageID); if (patientStage == null) { return(NotFound()); } patientStage.Completed = DateTime.Now; //get the next stage Stage nextStage = db.Stage.Where(s => s.OrderNumber > currentstage.OrderNumber).OrderBy(s => s.OrderNumber).First(); if (nextStage != null) { PatientLog newLog = new PatientLog() { PatientID = id, StageID = nextStage.Id, EnteredIn = DateTime.Now, }; db.Add(newLog); } db.Attach(patientStage); db.SaveChanges(); return(RedirectToPage("/Patients/index", new { id = stageID })); }
public async Task <ActionResult> Post([FromForm] WorkoutCreateDTO workoutCreate) { var entity = mapper.Map <Workout>(workoutCreate); if (workoutCreate.ImageFile != null) { using var memoryStream = new MemoryStream(); await workoutCreate.ImageFile.CopyToAsync(memoryStream); var content = memoryStream.ToArray(); var extension = Path.GetExtension(workoutCreate.ImageFile.FileName); var url = await storage.SaveFile(content, extension, CONTAINER, workoutCreate.ImageFile.ContentType); entity.Images = new List <WorkoutImages> { new WorkoutImages { Url = url } }; } context.Add(entity); await context.SaveChangesAsync(); var entityDTO = mapper.Map <WorkoutDTO>(entity); return(new CreatedAtRouteResult("GetWorkout", new { id = entity.Id }, entityDTO)); }
public async Task <CourseInstance> Create(CourseInstance instance) { _context.Add(instance); await _context.SaveChangesAsync(); return(instance); }
private void Seed() { using (var context = new ApplicationDBContext(ContextOptions)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); var MovieRatingEntry = new MovieRating(); MovieRatingEntry.MovieID = 2; MovieRatingEntry.Rating = 6; context.Add(MovieRatingEntry); context.SaveChanges(); //var one = new Item("ItemOne"); //one.AddTag("Tag11"); //one.AddTag("Tag12"); //one.AddTag("Tag13"); //var two = new Item("ItemTwo"); //var three = new Item("ItemThree"); //three.AddTag("Tag31"); //three.AddTag("Tag31"); //three.AddTag("Tag31"); //three.AddTag("Tag32"); //three.AddTag("Tag32"); //context.AddRange(one, two, three); //context.SaveChanges(); } }
public async Task <IActionResult> Create([Bind("Full_name,Phone_number,Email,Password,Date,User_ID,Roles")] Log_in log_in) { if (ModelState.IsValid) { bool clientUsernameExists = _context.Log_in.Any(x => x.Phone_number == log_in.Phone_number); if (clientUsernameExists) { ViewBag.MessageError = "A user has been registered with above phone number.Please use another phone number!"; return(View()); } else { _context.Add(log_in); await _context.SaveChangesAsync(); ViewBag.MessageSuccess = "User created successfully please log in to proceed!"; return(View()); } //return RedirectToAction(nameof(Index)); } else { return(View()); } }
/// <summary> /// Launchs a new new for all the users /// </summary> /// <param name="message">The info</param> /// See <see cref="Areas.Admin.Models.Message"/> to see the param info /// <returns>The IActionResult of the launch new action</returns> public IActionResult launchNew([FromBody] Message message) { User user = TokenUserManager.getUserFromToken(HttpContext, _context); if (!AdminPolicy.isAdmin(user, _context)) { return(BadRequest("notAllowed")); } try { _context.Add(new New { title = "Aviso de los administradores!", message = message.message }); _context.SaveChanges(); List <NewMessage> retMessage = GetNews.getStandNews(true, _context); return(Ok(retMessage)); } catch (Exception) { return(StatusCode(500)); } }
/// <summary> /// Manages the interaction of a user with a group /// </summary> /// <param name="user">The user who has interacted with the group</param> /// <param name="group">The group</param> /// <param name="type">The interaction id</param> /// <param name="dbContext">The database context</param> public static void manageInteraction(User user, Group group, interactionType type, ApplicationDBContext dbContext) { List <GroupInteraction> interactions = dbContext.GroupInteractions.Where(gi => gi.groupid == group.id && gi.userid == user.id).ToList(); bool leftTheGroup = type == interactionType.LEAVED ? true : false; bool wasKickedFromTheGroup = type == interactionType.KICKED ? true : false; try { if (interactions.Count() != 1) { GroupInteraction gi = new GroupInteraction { Group = group, User = user, kicked = wasKickedFromTheGroup, leaved = leftTheGroup }; dbContext.Add(gi); } else { GroupInteraction gi = interactions.First(); gi.dateLeave = DateTime.Now; gi.kicked = wasKickedFromTheGroup; gi.leaved = leftTheGroup; } dbContext.SaveChanges(); } catch (Exception) { } }
public async Task <IActionResult> Create([Bind("BookTitle,BookISBN,PageCount,CompletionDate,FixedPay,SalesForRoyalties,RoyaltyRate,Notes,CompanyApproval,CompanyApprovalDate,AuthorApproval,AuthorApprovalDate,CreationDate,AuthorId,RepresentativeId")] Contract contract) { if (ModelState.IsValid) { if (contract.CompanyApprovalDate.Date >= contract.CreationDate.Date) { if (contract.AuthorApprovalDate.Date >= contract.CreationDate.Date) { _context.Add(contract); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } else { TempData["Error"] = "Author Approval Date cannot be earlier than Creation Date."; } } else { TempData["Error"] = "Company Approval Date cannot be earlier than Creation Date."; } } ViewData["AuthorId"] = new SelectList(_context.Authors, "Id", "FullName", contract.AuthorId); ViewData["RepresentativeId"] = new SelectList(_context.Representatives, "Id", "FullName", contract.RepresentativeId); return(View(contract)); }
public async Task <ActionResult> Post([FromBody] RatingDTO ratingDTO) { var email = HttpContext.User.Claims.FirstOrDefault(x => x.Type == "email").Value; var user = await userManager.FindByEmailAsync(email); var userId = user.Id; var currentRating = await context.Ratings .FirstOrDefaultAsync(x => x.movieId == ratingDTO.movieId && x.userId == userId); if (currentRating == null) { var rating = new Rating(); rating.movieId = ratingDTO.movieId; rating.score = ratingDTO.score; rating.userId = userId; context.Add(rating); } else { currentRating.score = ratingDTO.score; } await context.SaveChangesAsync(); return(NoContent()); }
public async Task <IActionResult> Post(Developer developer) { _context.Add(developer); await _context.SaveChangesAsync(); return(Ok(developer.Id)); }
public async Task <IActionResult> Create([Bind("Id,FirstName,LastName,Telephone,EMail")] Author author) { if (ModelState.IsValid) { if (Regex.Match(author.Telephone, @"^\(\d{3}\)\d{3}-\d{4}$").Success) { try { var addr = new System.Net.Mail.MailAddress(author.EMail); } catch { TempData["Error"] = "Invalid email address."; return(View(author)); } _context.Add(author); await _context.SaveChangesAsync(); return(RedirectToAction("Create", "Contracts")); } else { TempData["Error"] = "Telephone number must be in the following format: (###)###-####"; } } return(View(author)); }
public async Task <IActionResult> Post(SpriteMap spriteMap) { _context.Add(spriteMap); await _context.SaveChangesAsync(); return(Ok(spriteMap.Id)); }
public async Task <IActionResult> Create(PDF_Refference pDF_Refference, [Optional] int id) { if (ModelState.IsValid) { string refcover = "Refferences/" + Guid.NewGuid().ToString() + pDF_Refference.Image.FileName; string serverFolder1 = Path.Combine(_webHostEnvironment.WebRootPath, refcover); await pDF_Refference.Image.CopyToAsync(new FileStream(serverFolder1, FileMode.Create)); PDF_Refference pdfdoc = new PDF_Refference { Doc_id = pDF_Refference.Doc_id, Description = pDF_Refference.Description, Refference_url = refcover, Date_modified = DateTime.Now.ToString() }; _context.Add(pdfdoc); await _context.SaveChangesAsync(); ViewBag.status = "Refference has been uploaded successfully!"; ViewBag.imageURL = "/" + refcover; ViewBag.Description = pDF_Refference.Description; } var posts = _context.Pdf_refference.Where(w => w.Doc_id.ToString() == HttpContext.Session.GetString("docid")).ToList(); ViewBag.relatedPost = posts; return(View()); }
public async Task <ActionResult <int> > Post(Genero genero) { context.Add(genero); await context.SaveChangesAsync(); return(genero.Id); }
public async Task <IActionResult> Post(TodoItem todoItem) { _context.Add(todoItem); await _context.SaveChangesAsync(); return(Ok(todoItem.Id)); }
public async Task <IActionResult> Post(Appointment appointment) { _context.Add(appointment); await _context.SaveChangesAsync(); return(Ok(appointment.Id)); }
public void AddAccount(SignupModel user) { var model = _mapper.Map <User>(user); bool userExist = _context.Users.Any(x => x.Username == model.Username); bool emailExist = _context.Users.Any(x => x.Email == model.Email); if (userExist == true || emailExist == true) { throw new Exception(emailExist == true ? "Email is already in use." : "Username is already in use."); } byte[] salt = new byte[16]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } model.Salt = Convert.ToBase64String(salt); string hashedPassword = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: model.Password, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 16)); model.Password = hashedPassword; _context.Add(model); _context.SaveChanges(); }
public async Task <ActionResult> Post([FromBody] Usuario user) { //TODO: Adicionar novo usuario (user) uma lista try { var newUser = new Usuario { Title = user.Title, FirstName = user.FirstName, LastName = user.LastName, DateBirth = user.DateBirth, Email = user.Email, Password = user.Password, ConfirmPassword = user.ConfirmPassword, Accept = user.Accept }; db.Add(newUser); await db.SaveChangesAsync(); return(Ok()); } catch (Exception e) { return(View(e)); } }
public async Task <ActionResult> Post(UserFavourite userFavourite) { context.Add(userFavourite); await context.SaveChangesAsync(); return(Ok()); }