Exemplo n.º 1
0
        /// <summary>
        /// Create gateway in particular boundary, return true if successfully created else return false
        /// </summary>
        /// <param name="gatewayName">GatewayName</param>
        /// <param name="gatewayMAC">GatewayMAC</param>
        /// <param name="createdBy">CreatedBy</param>
        /// <param name="boundaryId">BoundaryId</param>
        /// <param name="isEnable">IsEnable</param>
        /// <returns>True if gateway successfully created</returns>
        /// Author = Ali Abbas, version 1.0

        public bool CreateGateway(string gatewayName, string gatewayMAC, string createdBy, int boundaryId, bool isEnable)
        {
            try
            {
                Gateway gateway = new Gateway()
                {
                    GatewayName  = gatewayName,
                    GatewayMAC   = gatewayMAC,
                    CreatedBy    = createdBy,
                    BoundaryId   = boundaryId,
                    IsEnable     = isEnable,
                    CreatedDate  = DateTime.Now,
                    ModifiedDate = DateTime.Now
                };
                using (db.Database.BeginTransaction())
                {
                    db.Entry(gateway).State = EntityState.Added;
                    db.Gateways.Add(gateway);
                    db.SaveChanges();
                    db.Database.CommitTransaction();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                db.Database.RollbackTransaction();
                throw ex;
            }
        }
Exemplo n.º 2
0
        public ActionResult Send(SendMessageViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                Message m = new Message(User.Identity.GetUserId(), viewModel.Subject, viewModel.Body);
                Db.Messages.Add(m);
                try
                {
                    string[] gReceivers = viewModel.GroupReceivers.Split(',');
                    foreach (string r in gReceivers)
                    {
                        Group grp = Db.Groups.Where(g => g.Name.Equals(r)).First();
                        m.GroupReceivers.Add(grp);
                        Db.SaveChanges();
                    }
                }
                catch (Exception e) {}

                try
                {
                    string[] uReceivers = viewModel.UserReceivers.Split(',');
                    foreach (string r in uReceivers)
                    {
                        ApplicationUserMessage user_message = new ApplicationUserMessage(m.Id, (Db.Users.First(u => u.Email.Equals(r)).Id.ToString()));
                        Db.ApplicationUserMessages.Add(user_message);
                        Db.SaveChanges();
                    }
                }catch (Exception e) {}

                return(RedirectToAction("Sent"));
            }
            return(View());
        }
Exemplo n.º 3
0
 public Role Add(Role t)
 {
     if (t != null)
     {
         _context.Roles.Add(t);
         _context.SaveChanges();
     }
     return(t);
 }
Exemplo n.º 4
0
 public User Add(User t)
 {
     if (t != null)
     {
         _context.Users.Add(t);
         _context.SaveChanges();
     }
     return(t);
 }
Exemplo n.º 5
0
        public virtual void Delete(TObject TObject, bool batch = true)
        {
            this.DbSet.Remove(TObject);

            if (!batch)
            {
                Context.SaveChanges();
            }
        }
Exemplo n.º 6
0
 public Task <IdentityResult> Create(Role role)
 {
     return(Task <IdentityResult> .Run(() =>
     {
         role.ID = Guid.NewGuid().ToString();
         Context.Set <Role>().Add(role);
         Context.SaveChanges();
         return IdentityResult.Success;
     }));
 }
Exemplo n.º 7
0
 /// <summary>
 /// 新增一个用户
 /// </summary>
 /// <param name="user"></param>
 /// <returns></returns>
 public Task CreateAsync(User user)
 {
     return(Task.Run(() =>
     {
         user.Id = Guid.NewGuid().ToString();
         Context.User.Add(user);
         int i = Context.SaveChanges();
         return i;
     }));
 }
Exemplo n.º 8
0
        private void Check5StarMedal(string name)
        {
            var user = context.Users.Include(x => x.Medals).FirstOrDefault(x => x.UserName == name);

            if (guidecontext.GetGuides(guidecontext, user.Id).Any(x => x.Ratings.Any(r => r.OwnerRating == 5)) && !user.Medals.Any(x => x.MedalId == 8))
            {
                AddMedal(8, user);
            }
            CheckSuperMedal(name);
            context.SaveChanges();
        }
Exemplo n.º 9
0
        public ActionResult Create(CreateGroupViewModel gvm)
        {
            Group group = new Group();

            group.Users = new List <ApplicationUser>();
            ApplicationUser currentUser = Db.Users.Find(User.Identity.GetUserId());

            group.Name = gvm.Name;
            Db.Groups.Add(group);
            group.Users.Add(currentUser);
            Db.SaveChanges();
            return(View());
        }
        public IActionResult AddCategory(string Name)
        {
            User     CurrUser    = GetCurrentUserAsync().Result;
            Category NewCategory = new Category
            {
                Name   = Name,
                UserId = CurrUser.Id,
            };

            _context.Add(NewCategory);
            _context.SaveChanges();

            return(RedirectToAction("Index"));
        }
Exemplo n.º 11
0
        // GET: /<controller>/
        public IActionResult StoreMessage(MessageViewModel model)
        {
            var           userId  = HttpContext.User.Identity.Name;
            MessagesModel message = new MessagesModel
            {
                Message  = model.Message,
                SendTo   = model.SendTo,
                SendFrom = userId
            };

            IdentityContext.Messages.Add(message);
            IdentityContext.SaveChanges();

            return(RedirectToAction("ShowChat", new { Id = model.SendTo }));
        }
Exemplo n.º 12
0
 public Task CreateAsync(Permission role)
 {
     return(Task.Run(() =>
     {
         var per = FindByNameAsync(role.Name);
         if (per.Result != null)
         {
             throw new Exception("权限已经存在");
         }
         role.Id = Guid.NewGuid().ToString();
         role.IsBasic = false;
         Context.Set <Permission>().Add(role);
         Context.SaveChanges();
     }));
 }
Exemplo n.º 13
0
        // GET: /<controller>/
        public IActionResult Index()
        {
            var user1 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**"
            };
            var user2 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**"
            };

            _userManager.CreateAsync(user2, "Password01!");
            _userManager.CreateAsync(user1, "Password01!");

            JobModel wordpress = new JobModel {
                Title = "Wordpress Developer", Description = "We are looking for a new wordpress developer that has a lot of good experience writing his own plugins. we need this to customize websites for our customers to give them the post possible results!", Website = "https://wordpress.com", Employment = "40", Skills = "PHP, CSS, JS, HMTL", Price = 60
            };
            JobModel appsec = new JobModel {
                Title = "Application security specialist", Description = "We are looking for an expert security specialist to help us with doing security testing on our web applications. It is a pre id you know OWASP and ASVS and how to set up security test automation in CI/CD pipelines", Website = "https://owasp.org", Employment = "40", Skills = "Docker, OWASP, Appsec", Price = 150
            };

            IdentityContext.Jobs.Add(wordpress);
            IdentityContext.Jobs.Add(appsec);

            IdentityContext.SaveChanges();

            return(RedirectToAction("Index", "Home"));
        }
        public void GetAccountById_Return_Account()
        {
            // Arrange
            var options = GetContextOptions();
            var email   = "*****@*****.**";
            var account = new AccountModel
            {
                Login    = "******",
                Email    = email,
                Password = "******",
                Role     = 1,
                IsActive = true
            };

            AccountViewModel result;

            // Act
            using (var context = new IdentityContext(options))
            {
                context.Accounts.Add(account);
                context.SaveChanges();

                var accoundGuid = context.Accounts.LastOrDefault().Id;

                IAccountService accountService = new AccountService(_options, context, _mapper);
                result = accountService.GetAccountByIdAsync(accoundGuid).GetAwaiter().GetResult();
            }

            // Assert
            Assert.Equal(account.Login, result.Login);
            Assert.Equal(account.Email, result.Email);
            Assert.Equal(account.Password, result.Password);
            Assert.Equal(account.Role, result.Role);
            Assert.Equal(account.IsActive, result.IsActive);
        }
Exemplo n.º 15
0
 public IActionResult Post([FromBody] CsrfViewModel value)
 {
     if (ModelState.IsValid)
     {
         CsrfModel csrf = new CsrfModel {
             PrivateData = value.PrivateData, PrivateDateTime = DateTime.Now
         };
         _myContext.Csrf.Add(csrf);
         _myContext.SaveChanges();
         return(Ok("New value was stored succesfull!"));
     }
     else
     {
         return(BadRequest("Storing the item has failed!"));
     }
 }
        public void CanUserBeAuthenticated_Return_UserTokenModel()
        {
            // Arrange
            var options = GetContextOptions();
            var account = new AccountModel
            {
                Login    = "******",
                Email    = "*****@*****.**",
                Password = "******",
                Role     = 1,
                IsActive = true
            };
            var loginViewModel = new LoginViewModel
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            UserTokenModel result;

            // Act
            using (var context = new IdentityContext(options))
            {
                context.Accounts.Add(account);
                context.SaveChanges();

                IAccountService accountService = new AccountService(_options, context, _mapper);
                result = accountService.AuthenticateAsync(loginViewModel).GetAwaiter().GetResult();
            }

            // Assert
            Assert.Equal(account.Login, result.UserName);
            Assert.Equal(account.Role.ConvertRole(), result.Role);
        }
Exemplo n.º 17
0
        public static void SeedEmploys(IServiceProvider serviceProvider)
        {
            using (var context = new IdentityContext(serviceProvider.GetRequiredService <DbContextOptions <IdentityContext> >())){
                if (context.Employ.Any())
                {
                    return;   // DB has been seeded
                }
                ;

                Technician QueryTechnician = context.Technician
                                             .Where(s => s.Name == "Rodrigo Kan")
                                             .FirstOrDefault <Technician>();

                Project QueryProject = context.Project
                                       .Where(s => s.Title == "Toy Story 5")
                                       .FirstOrDefault <Project>();

                var Employs = new Employ[] {
                    new Employ {
                        Project      = QueryProject,
                        Technician   = QueryTechnician,
                        TechnicianID = QueryTechnician.TechnicianID,
                        ProjectID    = QueryProject.ProjectID,
                    }
                };

                foreach (Employ e in Employs)
                {
                    context.Employ.Add(e);
                }
                context.SaveChanges();
            }
        }
Exemplo n.º 18
0
        public void LeaveBoard()
        {
            _currentUser.Kleur = Kleur.Geen;
            string roomtoken = _currentUser.SpelToken;

            _currentUser.SpelToken = null;

            bool playersStillInRoom = false;

            foreach (Users user in identityContext.Users.ToList())
            {
                if (user.SpelToken == roomtoken)
                {
                    playersStillInRoom = true;
                    break;
                }
            }

            if (!playersStillInRoom)
            {
                context.Remove(_context);
            }

            context.SaveChanges();
            identityContext.SaveChanges();
        }
Exemplo n.º 19
0
        public ApiResponse <User> Update(User userData)
        {
            //Prevent changing the ID
            userData.Id = Guid.Empty;
            var userToChange = GetUserFromIdAsync(userData.Id).Result;

            // Can only update an existing user
            if (userToChange == null)
            {
                return(new ApiResponse <User>(ApiResponseCode.UnAuthenticated, null));
            }

            // Update the user
            if (!string.IsNullOrWhiteSpace(userData.PasswordHash) && userData.PasswordHash != userToChange.PasswordHash)
            {
                //If the password is unchanged or empty, this does not update the password
                userData.PasswordHash = userToChange.PasswordHash;
            }
            // Automapper is configured to only overwrite the fields that are not null
            _mapper.Map(userData, userToChange);

            _identityContext.Update(userToChange);
            _identityContext.SaveChanges();

            return(new ApiResponse <User>(ApiResponseCode.OK, userToChange));
        }
        public ActionResult DeleteConfirmSecurityGroup(string id)
        {
            ApplicationSecurityGroup securityGroup = IdentityContext.SecurityGroups
                                                     .Include(x => x.Roles).Include(x => x.Users)
                                                     .FirstOrDefault(x => x.Id == id);

            securityGroup.Users.ForEach(u =>
            {
                securityGroup.Roles.ForEach(role =>
                {
                    // Silinecek role başka bir sec grp da var mı? Varsa kullanıcıdan silmemeliyiz.
                    bool hasAnotherSecGroupThatRoleForUser =
                        u.SecurityGroups.Where(x => x.Id != id).ToList()
                        .Any(x => x.Roles.Any(r => r.Id == role.Id));

                    if (hasAnotherSecGroupThatRoleForUser == false)
                    {
                        UserManager.RemoveFromRole(u.Id, role.Name);
                    }
                });
            });

            IdentityContext.SecurityGroups.Remove(securityGroup);
            IdentityContext.SaveChanges();

            return(JavaScript("deletesecuritygroup_success();"));
        }
Exemplo n.º 21
0
 public ActionResult EditUser(ApplicationUser User1)
 {
     if (ModelState.IsValid)
     {
         UserManager <ApplicationUser> UserManager1 = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new IdentityContext()));
         //جهت فعال کردن امکان ثبت نام فارسی
         UserManager1.UserValidator = new UserValidator <ApplicationUser>(UserManager1)
         {
             AllowOnlyAlphanumericUserNames = false
         };
         if ((UserManager1.FindByName(User1.UserName) == null) ||
             (UserManager1.FindById(User1.Id).UserName == User1.UserName))
         {
             IdentityContext IdentityContext1 = new IdentityContext();
             IdentityContext1.Entry(User1).State = System.Data.Entity.EntityState.Modified;
             IdentityContext1.SaveChanges();
             //return RedirectToAction("AllUsers");
             return(Json(new { success = true }));
         }
         else
         {
             ModelState.AddModelError("", "نام" + User1.UserName + "قبلا انتخاب شده است.");
         }
     }
     else
     {
         ModelState.AddModelError("", "داده های وارد شده نامعتبراند");
     }
     return(PartialView("_EditUser", User1));
 }
Exemplo n.º 22
0
 public UserId AddIdentity(UserId userId)
 {
     userId.IId = Guid.NewGuid();
     _identityContext.IdentityUser.Add(userId);
     _identityContext.SaveChanges();
     return(userId);
 }
Exemplo n.º 23
0
 public ActionResult DeleteRoleConfirmed(string id)
 {
     try
     {
         IdentityContext IdentityContext1           = new IdentityContext();
         UserManager <ApplicationUser> UserManager1 = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new IdentityContext()));
         IdentityUser IdentityUser1 = new IdentityUser();
         var          IdentityUsers = IdentityContext1.Users.Where(u => u.Roles.Any(r => r.RoleId == id));
         foreach (IdentityUser user1 in IdentityUsers)
         {
             UserManager1.RemoveFromRole(user1.Id, id);
         }
         //RoleManager<IdentityRole> RoleManager1 = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
         IdentityRole IdentityRole1 = new IdentityRole();
         IdentityRole1 = IdentityContext1.Roles.Find(id);
         IdentityContext1.Roles.Remove(IdentityRole1);
         IdentityContext1.SaveChanges();
         //return RedirectToAction("AllRoles");
         return(Json(new { success = true }));
     }
     catch (Exception ex)
     {
         ModelState.AddModelError("", ex.Message);
         return(PartialView("_DeleteRole", id));
     }
 }
Exemplo n.º 24
0
 public ActionResult DeleteUserConfirmed(string id = null)
 {
     try
     {
         IdentityContext IdentityContext1           = new IdentityContext();
         ApplicationUser IdentityUser1              = IdentityContext1.Users.First(x => x.Id == id);
         UserManager <ApplicationUser> UserManager1 = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new IdentityContext()));
         foreach (string UserRole1 in UserManager1.GetRoles(id))
         {
             UserManager1.RemoveFromRole(id, UserRole1);
         }
         foreach (System.Security.Claims.Claim UserClaim1 in UserManager1.GetClaims(id))
         {
             UserManager1.RemoveClaim(id, UserClaim1);
         }
         foreach (UserLoginInfo UserLoginInfo1 in UserManager1.GetLogins(id))
         {
             UserManager1.RemoveLogin(id, UserLoginInfo1);
         }
         IdentityContext1.Users.Remove(IdentityUser1);
         IdentityContext1.SaveChanges();
         //return RedirectToAction("AllUsers");
         return(Json(new { success = true }));
     }
     catch (Exception ex)
     {
         return(Content(ex.Message));
     }
 }
Exemplo n.º 25
0
        public ActionResult EditRole(string id, string Name)
        {
            string RoleNameNew = Name;

            if (ModelState.IsValid)
            {
                RoleManager <IdentityRole> RoleManager1 = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new IdentityContext()));
                if (!RoleManager1.RoleExists(RoleNameNew))
                {
                    IdentityContext IdentityDbContext1 = new IdentityContext();
                    IdentityRole    Role1 = IdentityDbContext1.Roles.First(x => x.Id == id);
                    Role1.Name = RoleNameNew;
                    IdentityDbContext1.Entry(Role1).State = System.Data.Entity.EntityState.Modified;
                    IdentityDbContext1.SaveChanges();
                    //return RedirectToAction("AllRoles");
                    return(Json(new { success = true }));
                }
                else
                {
                    ModelState.AddModelError("", "گروه جدید قبلا ساخته شده است.");
                }
            }
            else
            {
                ModelState.AddModelError("", "داده های وارد شده معتبر نیستند.");
            }
            return(PartialView("_EditRole", RoleNameNew));
        }
Exemplo n.º 26
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            Customers addCustomers = new Customers();

            addCustomers.EmailOfCustomer = model.Email;
            addCustomers.Citi            = model.Citi;
            addCustomers.NameOfComany    = model.NameOfComany;
            addCustomers.NIP             = model.NIP;
            addCustomers.Street          = model.Street;
            addCustomers.PhoneNumber     = model.PhoneNumber;
            addCustomers.NameOfCustomer  = model.NameOfCustomer;
            _context.Add(addCustomers);
            try
            {
                _context.SaveChanges();
            }
            catch (DbUpdateException)
            {
                return(Content("Brak dostepu do Bazy"));
            }
            RegisterModel addNewUser = new RegisterModel();

            addNewUser.Email          = model.Email;
            addNewUser.Login          = model.Login;
            addNewUser.RepeatPassword = model.RepeatPassword;
            addNewUser.Password       = model.Password;
            if (ModelState.IsValid)
            {
                var identity = new UserModel(addNewUser.Login);
                identity.Email       = addNewUser.Email;
                identity.CustomersID = addCustomers.Id;
                var result = await _signInManager.UserManager.CreateAsync(identity, addNewUser.Password);

                if (result.Succeeded)
                {
                    await _signInManager.PasswordSignInAsync(model.Login,
                                                             model.Password, false, false);

                    return(RedirectToAction("Index", "Account"));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return(View());
        }
        public async Task OnPostEditProyectosPersonales_VerSiRealmenteEdita()
        {
            // Arrange
            //Preparamos un contexto que guarde la base de datos en memoria ram.
            var OptionsBuilder = new DbContextOptionsBuilder <IdentityContext>()
                                 .UseInMemoryDatabase("InMemoryDb");

            IdentityContext  TestIdentityContext = new IdentityContext(OptionsBuilder.Options);
            ProyectoPersonal ProyectoPersonal    = new ProyectoPersonal()
            {
                ID = 4, Descripcion = "Book", FechaComienzo = DateTime.Parse("2019/02/12"), FechaFinalizacion = DateTime.Parse("2019/02/12"), TipoDeProyecto = "Foto"
            };

            //Guardamos un Proyecto Personal en bd
            TestIdentityContext.ProyectoPersonal.Add(ProyectoPersonal);
            TestIdentityContext.SaveChanges();

            //Creo una instancia de Proyecto Personal para comparar más adelante
            ProyectoPersonal ProyectoPersonalEsperado = new ProyectoPersonal()
            {
                ID = 4, Descripcion = "Camara", FechaComienzo = DateTime.Parse("2019/03/12"), FechaFinalizacion = DateTime.Parse("2019/04/12"), TipoDeProyecto = "camara"
            };

            // Act
            //Creamos una pagina de tipo EditModel (de Proyectos Personales), la cual es la que se encarga de la logica
            //de editar Proyectos Personales en bd.
            EditModel PageEditModel = new EditModel(TestIdentityContext);

            //Simulamos haber hecho el edit en un Proyectos Personales con el id
            await PageEditModel.OnGetAsync(ProyectoPersonal.ID);

            //Modificamos los valores de los atributos de la instancia "ProyectoPersonal" de Proyecto Personal
            PageEditModel.ProyectoPersonal.Descripcion       = ProyectoPersonalEsperado.Descripcion;
            PageEditModel.ProyectoPersonal.FechaComienzo     = ProyectoPersonalEsperado.FechaComienzo;
            PageEditModel.ProyectoPersonal.FechaFinalizacion = ProyectoPersonalEsperado.FechaFinalizacion;
            PageEditModel.ProyectoPersonal.TipoDeProyecto    = ProyectoPersonalEsperado.TipoDeProyecto;

            //Simulamos un post que envíe el formulario de la pagina y por ende guarda los cambios de la edicion
            await PageEditModel.OnPostAsync();

            // Assert
            //Buscamos si aún esta en bd el Proyecto Personal que debió haber sido editada por la pagina
            ProyectoPersonal ProyectoPersonalRecibida = await TestIdentityContext.ProyectoPersonal.FindAsync(ProyectoPersonal.ID);


            Assert.Equal(
                ProyectoPersonalEsperado.Descripcion.ToString(),
                ProyectoPersonalRecibida.Descripcion.ToString());
            Assert.Equal(
                ProyectoPersonalEsperado.FechaComienzo.ToString(),
                ProyectoPersonalRecibida.FechaComienzo.ToString());
            Assert.Equal(
                ProyectoPersonalEsperado.FechaFinalizacion.ToString(),
                ProyectoPersonalRecibida.FechaFinalizacion.ToString());
            Assert.Equal(
                ProyectoPersonalEsperado.TipoDeProyecto.ToString(),
                ProyectoPersonalRecibida.TipoDeProyecto.ToString());
            //Si se ejecuta correctamente, significa que el programa modifica correctamente Proyectos Personales
        }
Exemplo n.º 28
0
 public IActionResult Post([FromBody] IdorViewModel idor)
 {
     if (ModelState.IsValid)
     {
         string    username = _httpContextAccessor.HttpContext.Request.Cookies.FirstOrDefault(x => x.Key == "User").Value.ToString();
         IdorModel value    = new IdorModel {
             IdorValue = idor.IdorValue, Owner = username
         };
         _myContext.Idor.Add(value);
         _myContext.SaveChanges();
         return(Ok("New value was stored succesfull!"));
     }
     else
     {
         return(BadRequest("Storing the item has failed!"));
     }
 }
Exemplo n.º 29
0
        public static void SeedProjects(IServiceProvider serviceProvider)
        {
            using (var context = new IdentityContext(serviceProvider.GetRequiredService <DbContextOptions <IdentityContext> >()))
            {
                if (context.Project.Any())
                {
                    return;       // DB has been seeded
                }
                ;

                var Projects = new Project[] {
                    new Project {
                        Title       = "Reclame UCU Enseña", Date = DateTime.Parse("2019-02-01"),
                        Description = "Reclame de 5 minutos", CompletionStatus = false
                    },
                    new Project {
                        Title       = "Propaganda Copa América", Date = DateTime.Parse("2019-03-02"),
                        Description = "Titulares y Highlights de la Copa 2015", CompletionStatus = false
                    },
                    new Project {
                        Title       = "Kung Fu Panda 5", Date = DateTime.Parse("2019-07-03"),
                        Description = "Trailer de la nueva Película", CompletionStatus = false
                    },
                    new Project {
                        Title       = "Open Fing Clases", Date = DateTime.Parse("2019-11-04"),
                        Description = "Grabar Curso 779283 completo ", CompletionStatus = false
                    },
                    new Project {
                        Title       = "Toy Story 5", Date = DateTime.Parse("2019-12-05"),
                        Description = "Trailer de la Nueva Pelicula de Pixar", CompletionStatus = false
                    },
                    new Project {
                        Title       = "Mi Villano Favorito", Date = DateTime.Parse("2019-10-04"),
                        Description = "Mindstorming de la nueva Película", CompletionStatus = false
                    },
                    new Project {
                        Title       = "Podcast con Alumnos", Date = DateTime.Parse("2019-04-06"),
                        Description = "Entrevistas casuales acerca de la vida estudiantil en UCU", CompletionStatus = true
                    },
                    new Project {
                        Title       = "VideoClip Musical Survivors", Date = DateTime.Parse("2019-09-07"),
                        Description = "Filmar el nuevo videoclip para Survivors", CompletionStatus = false
                    }
                };

                foreach (Project p in Projects)
                {
                    Client query = context.Client
                                   .Where(s => s.Name == "ESPN")
                                   .FirstOrDefault <Client>();
                    p.Client   = query;
                    p.ClientID = query.ClientID;
                    context.Project.Add(p);
                }
                ;
                context.SaveChanges();
            }
        }
Exemplo n.º 30
0
        public IActionResult AddRoom(RoomDescriptionModel roomDescription)
        {
            var listFromDataBase = _context.RoomDescriptionModels
                                   .Where(x => x.NameOfRoom == roomDescription.NameOfRoom)
                                   .ToList();

            //for (int i = 0; i < listFromDataBase.Count; i++)
            //{
            //    string name = listFromDataBase[i].NameOfRoom;
            //    if (name == roomDescription.NameOfRoom)
            //    {
            //        TempData["Massege"] = "Sala o podanej nazwie juz istneje";
            //        return AddRoom();
            //    }

            //}
            //if (listFromDataBase.Contains(name))
            //{

            //}

            //if (string.IsNullOrEmpty(roomDescription.NameOfRoom))
            //{
            //    return Content("Prosze podać nazwę sali");
            //}
            if (ModelState.IsValid)
            {
                _context.Add(roomDescription);

                try
                {
                    _context.SaveChanges();
                }
                catch (DbUpdateException)
                {
                    if (roomDescription.Id != default(int))
                    {
                        roomDescription.Id = default(int);
                        _context.SaveChanges();
                    }
                }
            }
            return(AddRoom());
        }