예제 #1
0
        public async Task NewNegativeTest(ApplicationUser user, NegativeTest test)
        {
            if (!user.AtRisk)
            {
                throw new Exception("User not currently at risk");
            }

            test.ApplicationUserId = user.Id;

            if (test.TestDate > Time.Now())
            {
                throw new ModelException("Test can't be more recent than present date",
                                         (ModelState => { ModelState.AddModelError("TestDate", "La fecha de realización del test no puede ser posterior a la fecha actual."); })
                                         );
            }
            if (test.TestDate < user.TimeOfLastCondition)
            {
                throw new ModelException("Test should be more recent than last time put into risk",
                                         (ModelState => { ModelState.AddModelError("TestDate", "La fecha de realización del test debe ser posterior a la última vez que fue puesto en riesgo."); })
                                         );
            }

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

            await _userInfoManager.UpdateStatus(user, InfectionStatus.Healthy, null);
        }
예제 #2
0
 public void Register(Employee employee)
 {
     employee.Login.Password = RandomNumberGenerator.RandomString(8);
     _dbContext.Logins.Add(employee.Login);
     _dbContext.Add(employee);
     _dbContext.SaveChanges();
 }
        public IActionResult AddCustomer(Customer customer)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(customer));
            }

            customer.Created = DateTime.Now;
            databaseContext.Add(customer);
            databaseContext.SaveChanges();
            logger.LogInformation("A customer with name: " + customer.FirstName + " " + customer.LastName + " was added.");
            return(Ok(Customers));
        }
        public async Task <IActionResult> Create([Bind("pageId,Title")] PageCreate pageCreate)
        {
            if (ModelState.IsValid)
            {
                pageCreate.pageId = Guid.NewGuid();

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

                return(RedirectToAction("Edit", new { id = pageCreate.pageId }));
            }
            return(View(pageCreate));
        }
예제 #5
0
        private static void CriarGrupoPerfilUsuario(DBContext context)
        {
            //se não existir o grupo master
            var grupo = new Grupo
            {
                Descricao    = "Administrador Master",
                PerfisGrupos = ListaDePermissao.Listar
            };

            context.Add(grupo);
            context.SaveChanges();

            Console.WriteLine(@"********************************************************************************");
            Console.WriteLine(@"**************************Grupo e Perfil criados********************************");
            Console.WriteLine(@"********************************************************************************");


            if (!context.Usuarios.Any())
            {
                #region Usuario

                var usuario = new Usuario
                {
                    Login          = "******",
                    Senha          = Seguranca.GerarHash("1"),
                    Ativo          = "S",
                    GruposUsuarios = new GrupoUsuario[]
                    {
                        new GrupoUsuario
                        {
                            Grupo = grupo
                        }
                    }
                };

                context.Add(usuario);

                context.SaveChanges();



                #endregion

                Console.WriteLine(@"********************************************************************************");
                Console.WriteLine(@"************************************Usuário Criado******************************");
                Console.WriteLine(@"********************************************************************************");
            }
        }
예제 #6
0
 public ActionResult SignUp(SignUpModel model)
 {
     if (ModelState.IsValid)
     {
         using (DBContext context = new DBContext())
         {
             User lookupUser = context.Users.FirstOrDefault(u =>
                                                            u.UserLogin == model.Login || u.UserEMail == model.Email);
             if (lookupUser == null)
             {
                 context.Add(new User
                 {
                     UserLogin = model.Login,
                     UserName  = model.Name,
                     UserPass  = BCrypt.Net.BCrypt.HashPassword(model.Password),
                     UserEMail = model.Email
                 });
                 context.SaveChanges();
                 FormsAuthentication.SetAuthCookie(model.Login, true);
                 return(RedirectToAction("Index", "Home"));
             }
             else
             {
                 ModelState.AddModelError(string.Empty,
                                          "User with the same login or email already exists");
             }
         }
     }
     return(View(model));
 }
예제 #7
0
        public static async Task <ImageAsset> Create(DBContext context, ImagePostData post_data)
        {
            ImageAsset newImage = null;

            try
            {
                newImage             = new ImageAsset();
                newImage.Album       = context.Albums.Find(post_data.AlbumID);
                newImage.Name        = post_data.Name;
                newImage.Description = post_data.Description;
                newImage.Location    = post_data.Location;

                newImage.Tags = new List <ImageTag>();
                if (!string.IsNullOrEmpty(post_data.Tags))
                {
                    foreach (string tag in post_data.Tags.Split(' '))
                    {
                        newImage.Tags.Add(new ImageTag()
                        {
                            Tag = tag, Created = DateTime.Now, Updated = DateTime.Now
                        });
                    }
                }
                newImage.Created = DateTime.Now;
                newImage.Updated = DateTime.Now;

                context.Add(newImage);
                await context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return(newImage);
        }
예제 #8
0
        public async Task <IActionResult> Create([Bind("AssetID,AssetName,DepartmentID,DateCreated,LastUsed,UsefulLife,Price,DepreciationRate,DepreciatedAmount")] FixedAssets fixedAssets)
        {
            if (ModelState.IsValid)
            {
                var vidaUtil = fixedAssets.UsefulLife;
                var precio   = fixedAssets.Price;


                var depreRate = 1 / vidaUtil;
                depreRate = depreRate * 2;
                var depreAmount = precio * depreRate;

                fixedAssets.DepreciationRate  = depreRate;
                fixedAssets.DepreciatedAmount = depreAmount;

                fixedAssets.DateCreated = System.DateTime.Today;
                fixedAssets.LastUsed    = System.DateTime.Today;

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

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["DepartmentID"] = new SelectList(_context.Departments, "DepartmentID", "DepartmentID", fixedAssets.DepartmentID);
            return(View(fixedAssets));
        }
예제 #9
0
 public IActionResult AddNewProduct(NewProductViewModel newProductViewModel)
 {
     try
     {
         _context.Add(newProductViewModel.AliasSKU.Product);
         _context.SaveChangesAsync();
         newProductViewModel.AliasSKU.ProductID = newProductViewModel.AliasSKU.Product.ProductID;
         newProductViewModel.AliasSKU.IsMain    = true;
         _context.Add(newProductViewModel.AliasSKU);
         _context.SaveChangesAsync();
     }
     catch (Exception ex)
     {
     }
     return(RedirectToAction("Index"));
 }
예제 #10
0
        public async Task <Exam> Add(Exam t)
        {
            if (t == null)
            {
                throw new ArgumentNullException(nameof(t));
            }

            var professor = _context.Professors.Find(t.ProfessorId);

            if (professor.SubjectId != t.SubjectId)
            {
                throw new Exception("Regjisro lenden qe i perket profesorit adekuat!");
            }

            var exams = await GetAll();

            foreach (var item in exams)
            {
                if (item.StudentId == t.StudentId)
                {
                    if (item.ProfessorId == t.ProfessorId)
                    {
                        if (item.SubjectId == t.SubjectId)
                        {
                            throw new Exception("Ky provim eshte i regjistruar me heret");
                        }
                    }
                }
            }

            var task = Task.Run(() => _context.Add(t));
            await task.ContinueWith(task => _context.SaveChangesAsync());

            return(t);
        }
        public async Task <IActionResult> Create([Bind("Name,Surname,Email,PhoneNumber,Password,ConfirmPassword,DateOfBirth,AccountType")] UserReadModel userReadModel)
        {
            if (ModelState.IsValid)
            {
                //password check here
                var passwordValid = userReadModel.Password == userReadModel.ConfirmPassword;
                if (passwordValid == true)
                {
                    var myUser = new User();
                    myUser.Name        = userReadModel.Name;
                    myUser.Surname     = userReadModel.Surname;
                    myUser.Email       = userReadModel.Email;
                    myUser.PhoneNumber = userReadModel.PhoneNumber;
                    myUser.Password    = userReadModel.Password;
                    myUser.DateOfBirth = userReadModel.DateOfBirth;
                    myUser.AccountType = userReadModel.AccountType;

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

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

                else
                {
                    ModelState.Clear();
                    ModelState.AddModelError("ErrorMessage", "Passwords do not match! Try again.");
                    return(View());
                }
            }
            return(View());
        }
예제 #12
0
        public string AddFavoriteIcao(string userName, string icao)
        {
            int lengthIcao = 4;

            if (icao == String.Empty)
            {
                return(Message.MESSAGE_CAMPO_FAVORITAR_ICAO_VAZIO);
            }
            else if (icao.Length < lengthIcao || icao.Length > lengthIcao)
            {
                return(Message.MESSAGE_ICAO_INVALIDO);
            }

            var db = new DBContext();

            var userExisting = db.Users.FirstOrDefault(x => x.UserName == userName);

            var testeIcao = db.Icaos.Any(x => x.UserId == userExisting.Id);

            if (testeIcao == true)
            {
                return(Message.MESSAGE_ICAO_EXISTENTE_NA_CONTA);
            }
            else
            {
                db.Add(new Icao {
                    UserId   = userExisting.Id,
                    IcaoCode = icao
                });
                db.SaveChanges();

                return($"{Message.MESSAGE_ICAO_FAVORITADO_COM_SUCESSO}");
            }
        }
예제 #13
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    await _userManager.AddToRoleAsync(user, "Basic");

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");


                    UserAppInfo userInfo = new UserAppInfo
                    {
                        Id              = user.Id,
                        Email           = user.Email,
                        InfectionStatus = InfectionStatus.Healthy
                    };

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

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
예제 #14
0
        public async Task <ActionResult> incrementCount()
        {
            try
            {
                Like lk = _ct.Like.FirstOrDefault();
                if (lk != null)
                {
                    lk.qtdlikes         = lk.qtdlikes + 1;
                    _ct.Entry(lk).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                }
                else
                {
                    lk = new Like()
                    {
                        qtdlikes = 1
                    };

                    _ct.Add(lk);
                }

                await _ct.SaveChangesAsync();

                return(Ok(lk.qtdlikes));
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }
        }
 public void Add(T entity)
 {
     using (var database = new DBContext(_optionsBuilder.Options))
     {
         database.Add(entity);
         database.SaveChanges();
     };
 }
        public IActionResult Create(ClinicalDepartment clinicalDepartment, int?id)
        {
            // Если в контроллер пришёл id, значит требуется правка, а не создание.
            if (id != null)
            {
                // Если id не соответствуют, то, значит, такого нет, и возвращется HTTP-ответ с кодом 404 ("Не найдено").
                if (id != clinicalDepartment.ClinicalDepartmentId)
                {
                    return(NotFound());
                }

                // Проверка модели на правильность.
                if (ModelState.IsValid)
                {
                    try
                    {
                        // Отметка о том, что профиль активный (не удалённый).
                        clinicalDepartment.ClinicalDepartmentExistedFlag = true;
                        // Занесение сделанных правок в базу данных.
                        _context.Update(clinicalDepartment);
                        // Сохранение изменений в базе данных.
                        _context.SaveChanges();
                    }
                    // Проверка на конкурирующие запросы к базе данных.
                    catch (DbUpdateConcurrencyException)
                    {
                        // Если такого профиля нет, то возвращется HTTP-ответ с кодом 404 ("Не найдено").
                        if ((!ClinicalDepartmentExists(clinicalDepartment.ClinicalDepartmentId)) || (!clinicalDepartment.ClinicalDepartmentExistedFlag))
                        {
                            return(NotFound());
                        }
                        else
                        {
                            throw;
                        }
                    }
                    return(new EmptyResult());
                }
                return(PartialView(clinicalDepartment));
            }
            else
            {
                // Проверка модели на правильность.
                if (ModelState.IsValid)
                {
                    if (_context.ClinicalDepartment.Any(d => d.ClinicalDepartmentName == clinicalDepartment.ClinicalDepartmentName && d.ClinicalDepartmentExistedFlag))
                    {
                        return(BadRequest());
                    }
                    // Отметка о том, что теперь профиль существует и активен.
                    clinicalDepartment.ClinicalDepartmentExistedFlag = true;
                    _context.Add(clinicalDepartment);
                    _context.SaveChanges();
                    return(new EmptyResult());
                }
                return(PartialView(clinicalDepartment));
            }
        }
 public bool Add(UsuarioModel objeto)
 {
     if (objeto != null)
     {
         _context.Add(ModelToEntity(objeto, new Usuario()));
         return(_context.SaveChanges() == 1 ? true : false);
     }
     return(false);
 }
예제 #18
0
        public IActionResult Subcribe(string name, string email)
        {
            Subscriber subcribe = new Subscriber();

            subcribe.Name  = name;
            subcribe.Email = email;
            try
            {
                db.Add(subcribe);
                db.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }

            return(RedirectToAction("Index"));
        }
예제 #19
0
 public IActionResult Save(TBL_MS_HOSP_CODE hc)
 {
     if (hc.ORG_ID != null)
     {
         _context.Add(hc);
         _context.SaveChanges();
     }
     return(Json(new { success = true, message = "success" }));
 }
예제 #20
0
 public IActionResult CreateModule(Module module)
 {
     if (!IsLogged())
     {
         return(RedirectToAction("Modules"));
     }
     if (!IsAdmin())
     {
         return(RedirectToAction("Modules"));
     }
     if (ModelState.IsValid)
     {
         dbContext.Add(module);
         dbContext.SaveChanges();
         return(RedirectToAction("Modules"));
     }
     return(GetCreateModuleForm());
 }
예제 #21
0
        public async Task <string> Importar_eva_cat_edificios()
        {
            try
            {
                var GetRes = await GetCatEdificiosAPI();

                if (GetRes != null)
                {
                    foreach (eva_cat_edificios edificio in GetRes)
                    {
                        System.Diagnostics.Debug.WriteLine("Edificio\n" + edificio.Alias);
                        var existe = await ExisteEdificio(edificio);

                        if (existe != null)
                        {
                            try
                            {
                                DBLoContext.Entry(existe).State   = EntityState.Detached;
                                DBLoContext.Entry(edificio).State = EntityState.Modified;
                                await DBLoContext.SaveChangesAsync();

                                DBLoContext.Entry(edificio).State = EntityState.Detached;
                            }
                            catch (Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine("Exception\n" + e.Message.ToString());
                                return(e.Message.ToString());
                            }
                        }
                        else
                        {
                            try
                            {
                                DBLoContext.Add(edificio);
                                await DBLoContext.SaveChangesAsync();

                                DBLoContext.Entry(edificio).State = EntityState.Detached;
                            }
                            catch (Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine("ExceptionI\n" + e.Message.ToString());
                                return(e.Message.ToString());
                            }
                        }
                    }
                    return("OK");
                }
                else
                {
                    return("NO HAY DATOS");
                }
            }
            catch (Exception e)
            {
                return(e.Message.ToString());
            }
        }
예제 #22
0
        public async Task CreateNewLocation(Location location, ApplicationUser user)
        {
            try { CheckLocationFields(location); }
            catch { throw; }

            location.IdPropietario = user.Id;
            _context.Add(location);
            await _context.SaveChangesAsync();
        }
예제 #23
0
        // Inserts all jobs in our list into our DB table
        private void insertJobs()
        {
            foreach (var job in jobs)
            {
                _context.Add(job);
            }

            _context.SaveChanges();
        }
        public IActionResult Card(Card card)                    //Yeni kart eklenme işleminin yapıldığı psot metodu...
        {
            var service = new GuessService();

            card.guessedTime = service.Guess(card.description);     //iş süresi tahminini methodunun çağırılması...
            card.dateTime    = DateTime.Now;                        //kart ekleme tarihinin eklenmesi
            _dbcontext.Add(card);
            _dbcontext.SaveChanges();
            return(RedirectToAction("Board", "Taskboard"));          //Board sayfasına yönlendirme
        }
예제 #25
0
 public TblMstQuestions addQuestion(TblMstQuestions ques)
 {
     ques.CreatedBy = "19379";
     ques.CreatedOn = System.DateTime.Now;
     //Console.WriteLine(ques);
     iDBContext.Add(ques);
     iDBContext.SaveChanges();
     return(ques);
     //throw new NotImplementedException();
 }
예제 #26
0
        public void Post(Usage usage)
        {
            Usage result = _context.Usages.FirstOrDefault(p => p.userId == usage.userId);

            if (result == null)
            {
                _context.Add(usage);
                _context.SaveChanges();
            }
        }
예제 #27
0
 private void LoadDataBase()
 {
     DBContext.Add("DatabaseTest.db3", new List <Type>()
     {
         typeof(User),
         typeof(Client),
         typeof(BussinesUnit),
         typeof(Request)
     });
 }
 public IActionResult CreateComment(Comment comment)
 {
     if (ModelState.IsValid)
     {
         dbContext.Add(comment);
         dbContext.SaveChanges();
         return(RedirectToAction("Comments"));
     }
     return(GetCreateCommentForm());
 }
예제 #29
0
        public async Task <IActionResult> Create(MovieVM viewModel, int[] selectedActors)
        {
            // If Modal Validation Fails
            if (!ModelState.IsValid)
            {
                ViewData["ProducerId"] = new SelectList(
                    _context.Producers, "Id", "Name", viewModel.ProducerId);

                return(View(viewModel));
            }

            var movie = new Movie
            {
                MovieName  = viewModel.MovieName,
                Released   = viewModel.Released,
                Plot       = viewModel.Plot,
                Poster     = viewModel.Poster,
                ProducerId = viewModel.ProducerId
            };

            _context.Add(movie);

            if (selectedActors != null)
            {
                foreach (var item in selectedActors)
                {
                    Actor actor = _context.Actors.Find(item);

                    var actorMovieVM = new ActorMovie
                    {
                        MovieId = movie.MovieId,
                        ActorId = actor.ActorId
                    };

                    _context.Add(actorMovieVM);
                }
            }

            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
예제 #30
0
        public async Task <IActionResult> Create([Bind("Id,Name")] Department department)
        {
            if (ModelState.IsValid)
            {
                _context.Add(department);
                await _context.SaveChangesAsync();

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