Esempio n. 1
0
        public async Task <IActionResult> Create(SubCategoryAndCategoryViewModel model)
        {
            if (ModelState.IsValid)
            {
                var doesSubCategoryExists = _db.SubCategory.Include(s => s.Category).Where(s => s.Name == model.SubCategory.Name && s.Category.Id == model.SubCategory.CategoryId);

                if (doesSubCategoryExists.Count() > 0)
                {
                    //Error
                    StatusMessage = "Error: Sub Category exists under " + doesSubCategoryExists.First().Category.Name + " category. Please use another name.";
                }
                else
                {
                    _db.SubCategory.Add(model.SubCategory);
                    await _db.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            SubCategoryAndCategoryViewModel modelVM = new SubCategoryAndCategoryViewModel()
            {
                CategoryList    = await _db.Category.ToListAsync(),
                SubCategory     = model.SubCategory,
                SubCategoryList = await _db.SubCategory.OrderBy(p => p.Name).Select(p => p.Name).ToListAsync(),
                StatusMessage   = StatusMessage
            };

            return(View(modelVM));
        }
Esempio n. 2
0
        public async Task <IActionResult> Create(Coupon coupons)
        {
            if (ModelState.IsValid)
            {
                var files = HttpContext.Request.Form.Files;
                if (files.Count > 0)
                {
                    byte[] p1 = null;
                    using (var fs1 = files[0].OpenReadStream())
                    {
                        using (var ms1 = new MemoryStream())
                        {
                            fs1.CopyTo(ms1);
                            p1 = ms1.ToArray();
                        }
                    }
                    coupons.Picture = p1;
                }
                _db.Coupon.Add(coupons);
                await _db.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(coupons));
        }
        public virtual async Task <bool> RemoveAsync(object id)
        {
            var resource = await GetAsync(id);

            DbSet.Remove(resource);
            await Context.SaveChangesAsync();

            return(true);
        }
        public async Task <IActionResult> Create([Bind("Id,NomeAluno,SenhaAluno,Matricula")] Aluno aluno)
        {
            if (ModelState.IsValid)
            {
                _context.Add(aluno);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(aluno));
        }
        public async Task <IActionResult> Create([Bind("Id,NomeAdministrador,SenhaAdministrador")] Administrador administrador)
        {
            if (ModelState.IsValid)
            {
                _context.Administrador.Add(administrador);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(administrador));
        }
        public async Task <IActionResult> Create([Bind("Id,NomeProfessor,SenhaProfessor,Cpf")] Professor professor)
        {
            if (ModelState.IsValid)
            {
                _context.Add(professor);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(professor));
        }
Esempio n. 7
0
        public async Task <IActionResult> Create(Category category)
        {
            if (ModelState.IsValid)
            {
                //if valid
                _db.Category.Add(category);
                await _db.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(category));
        }
Esempio n. 8
0
        [ValidateAntiForgeryToken] // Security mechanism that .net implmented for us. Gets added to request and server checks if the request is not altered on the way
        public async Task <IActionResult> Create(Models.ProductTypes productTypes)
        {
            if (ModelState.IsValid)
            {
                _db.Add(productTypes);
                await _db.SaveChangesAsync();

                //return RedirectToAction("Index"); //This can have typo
                return(RedirectToAction(nameof(Index)));
            }
            return(View(productTypes));
        }
Esempio n. 9
0
        public async Task <IActionResult> Agree(int?id)
        {
            var review1 =
                await _context.Reviews.FirstOrDefaultAsync(m => m.Agree == id);

            if (ModelState.IsValid)
            {
                review1.Agree++;
                _context.Update(review1);
                await _context.SaveChangesAsync();
            }
            return(RedirectToAction("Reviews"));
        }
Esempio n. 10
0
 public async Task SaveDiscordToken(SecurityToken token)
 {
     if (_context.SecurityTokens.Where(st => st.service == token.service).Count() == 0)
     {
         _context.SecurityTokens.Add(token);
     }
     else
     {
         var oldtoken = _context.SecurityTokens.Where(st => st.service == token.service).FirstOrDefault();
         oldtoken.token = token.ClientID;
     }
     await _context.SaveChangesAsync();
 }
Esempio n. 11
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            Departamento.DepartamentoNome       = Request.Form["Departamento.DepartamentoNome"].ToString().ToUpper();
            Departamento.LastUpdatedAt          = DateTime.UtcNow.Date;
            Departamento.LastUpdatedBy          = User.Identity.Name.ToString();
            _context.Attach(Departamento).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DepartamentoExists(Departamento.DepartamentoId))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
Esempio n. 12
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }
            Models.Recipe recipeToDelete = await _context.Recipes
                                           .Include(r => r.RecipeCategories)
                                           .SingleAsync(r => r.Id == id);

            if (recipeToDelete.PhotoPath != null)
            {
                var imgPath = Path.Combine(_hostEnvironment.WebRootPath, recipeToDelete.PhotoPath.TrimStart('\\'));
                if (System.IO.File.Exists(imgPath))
                {
                    System.IO.File.Delete(imgPath);
                }
            }
            if (recipeToDelete != null)
            {
                _context.Recipes.Remove(recipeToDelete);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
Esempio n. 13
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            Horario.LastUpdatedAt          = DateTime.UtcNow.Date;
            Horario.LastUpdatedBy          = User.Identity.Name.ToString();
            _context.Attach(Horario).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!HorarioExists(Horario.HorarioId))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
Esempio n. 14
0
        public async Task Save(FlightLog flightLog)
        {
            // Add the new FlightLog
            await db.FlightLogs.AddAsync(flightLog);

            // Update Entity used in the FlightLog
            var entity = db.Entities.FindAsync(flightLog.EntityId).Result;

            entity.TotalFlightCycles++;
            entity.TotalFlightDurationInSeconds += flightLog.SecondsFlown;
            entity.CyclesSinceLastMaintenance++;
            entity.FlightSecondsSinceLastMaintenance += flightLog.SecondsFlown;

            db.Entities.Update(entity);

            // Update all components in the Entity
            var components = db.Components
                             .Where(x => x.EntityId == flightLog.EntityId)
                             .ToList();

            foreach (var component in components)
            {
                component.TotalFlightCycles++;
                component.TotalFlightDurationInSeconds += flightLog.SecondsFlown;
                component.CyclesSinceLastMaintenance++;
                component.FlightSecondsSinceLastMaintenance += flightLog.SecondsFlown;
            }
            db.Components.UpdateRange(components);

            // Save changes
            await db.SaveChangesAsync();
        }
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.Attach(Product).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(Product.Id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
Esempio n. 16
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var _config = _context.AppPerfil
                          .Include(x => x.AppConfiguracoes)
                          .Include(x => x.AppConfiguracoes.AppConfiguracoes_Aplicativo)
                          .Include(y => y.AppConfiguracoes.AppConfiguracoes_Azure)
                          .FirstOrDefault();

            if (Construtora.Imagem != null)
            {
                var _imagemLogotipo =
                    await VerificadoresRetornos
                    .EnviarImagemAzure(Construtora.Imagem, 307200, 0, 0, _config.AppConfiguracoes.AppConfiguracoes_Azure._azureblob_AccountName, _config.AppConfiguracoes.AppConfiguracoes_Azure._azureblob_AccountKey, _config.AppConfiguracoes.AppConfiguracoes_Azure._azureblob_ContainerRaiz);

                if (_imagemLogotipo.ToLower().Trim().Contains("blob.core.windows.net"))
                {
                    Construtora.Logotipo = _imagemLogotipo;
                }
            }

            _context.Construtoras.Add(Construtora);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
Esempio n. 17
0
        public async Task <IActionResult> Create([Bind("GiveAwayItemId,Title,Key,SteamID,Link,Views,Owner,Receiver")] GiveAwayItem item)
        {
            if (ModelState.IsValid)
            {
                //TODO: Attribute Verification aka if links are links and etc
                var user = await _manager.GetUserAsync(HttpContext.User);

                user       = _context.ChatUserModels.Where(x => x.Id == user.Id).Include(x => x.OwnedItems).FirstOrDefault();
                item.Owner = user;
                _context.Add(item);
                await _context.SaveChangesAsync();
            }
            else
            {
                return(View(item));
            }
            return(RedirectToAction(nameof(Index)));
        }
Esempio n. 18
0
        public async Task <IActionResult> CreatePOST()
        {
            MenuItemVM.MenuItem.SubCategoryId = Convert.ToInt32(Request.Form["SubCategoryId"].ToString());

            if (!ModelState.IsValid)
            {
                return(View(MenuItemVM));
            }

            _db.MenuItem.Add(MenuItemVM.MenuItem);
            await _db.SaveChangesAsync();

            //Work on the image saving section

            string webRootPath = _hostingEnvironment.WebRootPath;
            var    files       = HttpContext.Request.Form.Files;

            var menuItemFromDb = await _db.MenuItem.FindAsync(MenuItemVM.MenuItem.Id);

            if (files.Count > 0)
            {
                //files have been uploaded
                var uploads   = Path.Combine(webRootPath, "images");
                var extension = Path.GetExtension(files[0].FileName);

                using (var filesStream = new FileStream(Path.Combine(uploads, MenuItemVM.MenuItem.Id + extension), FileMode.Create))
                {
                    files[0].CopyTo(filesStream);
                }
                menuItemFromDb.Image = @"\images\" + MenuItemVM.MenuItem.Id + extension;
            }
            else
            {
                //no file was uploaded, so use default
                var uploads = Path.Combine(webRootPath, @"images\" + SD.DefaultFoodImage);
                System.IO.File.Copy(uploads, webRootPath + @"\images\" + MenuItemVM.MenuItem.Id + ".png");
                menuItemFromDb.Image = @"\images\" + MenuItemVM.MenuItem.Id + ".png";
            }

            await _db.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
        public async Task <IActionResult> CreateAuthor(AuthorPostDTO authorToBeCreated)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Check if author already exists.
            Author existingAuthor = await _db.Authors.FirstOrDefaultAsync(a =>
                                                                          a.Praenomen == authorToBeCreated.Praenomen &&
                                                                          a.Nomen == authorToBeCreated.Nomen &&
                                                                          a.Cognomen == authorToBeCreated.Cognomen);

            if (existingAuthor != null)
            {
                return(Conflict(new { message = _errorMessageAuthorExists }));
            }

            try
            {
                int    userId    = (int)_userCtx.GetId();
                Author newAuthor = AuthorPostDTO.ToModel(authorToBeCreated, userId);

                await _db.Authors.AddAsync(newAuthor);

                await _db.SaveChangesAsync();

                string locationUri = $"{_baseUrl}/api/v1/authors/{newAuthor.AuthorId}";

                // Prepare response.
                AuthorGetDTO newAuthorResponse = AuthorGetDTO.FromModel(newAuthor);

                // Trigger webhook for new author event.
                TriggerAuthorWebhook(Event.NewAuthor, newAuthorResponse, userId);

                return(Created(locationUri, AuthorGetDTO.FromModel(newAuthor)));
            }
            catch (DbUpdateException)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError,
                                  _errorMessageSavingData));
            }
        }
        public async Task <IActionResult> RegisterAsNGO([Bind(nameof(NGO.Name))] NGO ngo)
        {
            if (ModelState.IsValid)
            {
                Identity identity = ControllerContext.GetIdentity();

                ngo.ID          = Guid.NewGuid();
                ngo.CreatedByID = identity.ID;
                ngo.NGOStatus   = NGOStatus.PendingVerification;

                applicationDbContext.Add(ngo);

                await applicationDbContext.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            return(View(ngo));
        }
        public async Task <IActionResult> Edit(string id, [Bind("Id,Role_Name,User_Id,First_Name,Last_Name,Email,Address,Created_At,Updated_At")] User_RoleModel user_RoleModel, string Role_Name)
        {
            if (id != user_RoleModel.User_Id)
            {
                return(NotFound());
            }

            /* To return the selected application user and application role from the database if it exists*/
            var applicationuser = await _context.Users.SingleOrDefaultAsync(x => x.Id == id);

            var new_application_role = await _context.Roles.SingleOrDefaultAsync(r => r.Id == Role_Name);

            var old_application_role = await _context.UserRoles.SingleOrDefaultAsync(ru => ru.UserId == applicationuser.Id);

            var old_RoleName = await _context.Roles.SingleOrDefaultAsync(r => r.Id == old_application_role.RoleId);

            if (ModelState.IsValid)
            {
                try
                {
                    applicationuser.FirstName = user_RoleModel.First_Name;
                    applicationuser.LastName  = user_RoleModel.Last_Name;
                    applicationuser.Email     = user_RoleModel.Email;
                    applicationuser.Address   = user_RoleModel.Address;

                    // To set the system time for record update
                    applicationuser.Updated_At = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Trim());
                    _context.Update(applicationuser);
                    _context.Entry(applicationuser).Property(x => x.Created_At).IsModified = false; // To prevent the datetime property to be set as null on update operation

                    // To update the role of the user by deleting the old role and assigning new role to the user
                    if (old_application_role.RoleId != Role_Name)
                    {
                        await _userManager.RemoveFromRoleAsync(applicationuser, old_RoleName.Name);

                        await _userManager.AddToRoleAsync(applicationuser, new_application_role.Name);
                    }
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ApplicationUserExists(applicationuser.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(AdminIndex)).WithSuccess("Success", "Successfully Updated User Details"));
            }
            return(View(user_RoleModel));
        }
Esempio n. 22
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.TaxasGLOBAIS.Add(taxaglobal);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
Esempio n. 23
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.AppConfiguracoes_Azure.Add(AppConfiguracoes_Azure);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
Esempio n. 24
0
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.Product.Add(Product);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
        public async Task <IActionResult> Login([FromBody] UserPostDTO userAttemptingToLogin)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Check if username even exists.
            User existingUser = await _db.Users.FirstOrDefaultAsync(u => u.Username == userAttemptingToLogin.Username);

            if (existingUser == null)
            {
                return(Unauthorized());
            }

            // Check if password matches.
            User user = await _db.Users.FirstOrDefaultAsync(u => u.Username == userAttemptingToLogin.Username);

            if (!Crypto.VerifyHashedPassword(user.Password, userAttemptingToLogin.Password))
            {
                return(Unauthorized());
            }

            try
            {
                // Generate JWT.
                string accessToken = GenerateJWT(user);
                user.LastLoginDate = DateTime.Now;
                await _db.SaveChangesAsync();

                return(Ok(new { access_token = accessToken }));
            }
            catch (DbUpdateException)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError,
                                  _errorMessageSavingData));
            }
        }
Esempio n. 26
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            Horario.CreatedAt = DateTime.UtcNow.Date;
            Horario.CreatedBy = User.Identity.Name.ToString();
            _context.Horarios.Add(Horario);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
Esempio n. 27
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"无法加载ID为'{_userManager.GetUserId(User)}'的用户。"));
            }

            RequirePassword = await _userManager.HasPasswordAsync(user);

            if (RequirePassword)
            {
                if (!await _userManager.CheckPasswordAsync(user, Input.Password))
                {
                    ModelState.AddModelError(string.Empty, "密码错误。");
                    return(Page());
                }
            }

            var result = await _userManager.DeleteAsync(user);

            var userId = await _userManager.GetUserIdAsync(user);

            if (!result.Succeeded)
            {
                throw new InvalidOperationException($"删除ID为“ {userId}”的用户时发生意外错误。");
            }


            IQueryable <Article> articles = from a in _context.Article where a.AuthorId == userId select a;

            foreach (Article a in articles)
            {
                IQueryable <Comment> comments = from c in _context.Comment where c.ArticleId == a.Id select c;
                foreach (Comment c in comments)
                {
                    _context.Comment.Remove(c);
                }
                await _context.SaveChangesAsync();

                _context.Article.Remove(a);
            }

            await _signInManager.SignOutAsync();

            _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);

            return(Redirect("~/"));
        }
Esempio n. 28
0
        public async Task <IActionResult> PostStudent([FromBody] Student Student)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            try
            {
                var user = await GetCurrentUserAsync();

                var userId = user?.Id;
                Student.IdentityId = userId;
                session.SetString("image", Student.Profile);
                Student.IsApproved = false;
                //if (Student.CityId == null && Student.City != null)
                //{
                //    City objNewCity = new City();
                //    objNewCity.Name = Student.City.Name;
                //    objNewCity.StateId = Student.City.StateId;
                //    _context.City.Add(objNewCity);
                //    _context.SaveChanges();
                //    var cityList = _context.City.OrderByDescending(c => c.Id).Take(1).FirstOrDefault();
                //    Student.CityId = cityList.Id;

                //}
                _context.Student.Add(Student);
                await _context.SaveChangesAsync();
            }

            catch (Exception e)
            {
                Console.WriteLine(e);
                return(Ok(0));
            }
            return(Ok(Student));
            //return CreatedAtAction("GetStudent", new { id = Student.Id }, Student);
        }
Esempio n. 29
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            Funcao.FuncaoNome    = Request.Form["Funcao.FuncaoNome"].ToString().ToUpper();
            Funcao.LastUpdatedAt = DateTime.UtcNow.Date;
            Funcao.LastUpdatedBy = User.Identity.Name.ToString();
            _context.Funcoes.Add(Funcao);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
Esempio n. 30
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            Contrato.ContratoTipo = Request.Form["Contrato.ContratoTipo"].ToString().ToUpper();
            Contrato.CreatedAt    = DateTime.UtcNow.Date;
            Contrato.CreatedBy    = User.Identity.Name.ToString();
            _context.Contratos.Add(Contrato);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }