//initial
        public static void initialData(HouseContext context)
        {
            //student Initializer
            var students = new List <Student>
            {
                new Student {
                    Username = "******", Password = "******", Birthday = DateTime.Parse("1994-05-02")
                },
                new Student {
                    Username = "******", Password = "******", Birthday = DateTime.Parse("1995-08-12")
                },
            };

            students.ForEach(s => context.Students.Add(s));
            context.SaveChanges();

            //staff Initializer
            var universityStaffs = new List <UniversityStaff>
            {
                new UniversityStaff {
                    Username = "******", Password = "******", Birthday = DateTime.Parse("1975-11-12")
                }
            };

            universityStaffs.ForEach(s => context.UniversityStaffs.Add(s));
            context.SaveChanges();

            //Landlord Initializer
            var landlords = new List <Landlord>
            {
                new Landlord {
                    Username = "******", Password = "******", Birthday = DateTime.Parse("1979-01-12")
                }
            };

            landlords.ForEach(s => context.Landlords.Add(s));
            context.SaveChanges();

            //advertisements Initializer
            var advertisements = new List <Advertisement>
            {
                new Advertisement {
                    LandlordID = 1, Pass = 0, Title = "Good price", Description = "Initial Data(wait):city center!Welcome to southampton, just 75/week!"
                },
                new Advertisement {
                    LandlordID = 1, Pass = 1, Title = "Near the sear house", Description = "Initial Data(pass):close to the university of southampton, just 115/week!"
                },
                new Advertisement {
                    LandlordID = 1, Pass = 2, Title = "4 Room big house", Description = "Initial Data(Fail):asdasfjkakj1danjsk asdjaksdask", RefuseReason = "wrong description!"
                }
            };

            advertisements.ForEach(s => context.Advertisements.Add(s));
            context.SaveChanges();
        }
        public ActionResult Create([Bind(Include = "ID,Username,Password,Birthday")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(student));
        }
示例#3
0
        ////approve the advertisement by detail
        //public ActionResult PassByDetail(Advertisement advertisement) {
        //    if (advertisement != null)
        //    {
        //        //?? need find again or other method to update?????
        //        advertisement = db.Advertisements.Find(advertisement.ID);
        //        advertisement.Pass = 1;
        //        db.Advertisements.Add(advertisement);
        //        db.SaveChanges();
        //        return RedirectToAction("Index");
        //    }
        //    return View();
        //}

        //approve the advertisement by main page
        public ActionResult Pass(string id)
        {
            if (id != null && !id.Equals(""))
            {
                Advertisement advertisement = db.Advertisements.Find(int.Parse(id));
                advertisement.Pass            = 1;
                db.Entry(advertisement).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View());
        }
        /// <summary>
        /// Удаление дома
        /// </summary>
        /// <param name="id">ID дома</param>
        /// <returns>Результат удаления дома.</returns>
        public string RemoveHouseById(int id)
        {
            var house = GetHousesById(id);

            if (house == null)
            {
                return("House Not Fount.");
            }

            _context.Houses.Remove(house);
            _context.SaveChanges();
            return("OK");
        }
示例#5
0
        // https://stackoverflow.com/questions/42471866/how-to-create-roles-in-asp-net-core-and-assign-them-to-users

        private async Task CreateUserRoles(IServiceProvider serviceProvider)
        {
            RoleManager <IdentityRole> roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();
            HouseContext Context = serviceProvider.GetRequiredService <HouseContext>();

            IdentityResult roleResult;

            bool roleCheck = await roleManager.RoleExistsAsync("Admin");

            if (!roleCheck)
            {
                roleResult = await roleManager.CreateAsync(new IdentityRole("Admin"));
            }

            IdentityUser user = Context.Users.FirstOrDefault(u => u.Email == "*****@*****.**");

            if (user != null)
            {
                DbSet <IdentityUserRole <string> > roles = Context.UserRoles;
                IdentityRole adminRole = Context.Roles.FirstOrDefault(r => r.Name == "Admin");
                if (adminRole != null)
                {
                    if (!roles.Any(ur => ur.UserId == user.Id && ur.RoleId == adminRole.Id))
                    {
                        roles.Add(new IdentityUserRole <string>()
                        {
                            UserId = user.Id, RoleId = adminRole.Id
                        });
                        Context.SaveChanges();
                    }
                }
            }
        }
 public IActionResult Register(Reg newUser)
 {
     System.Console.WriteLine("-----------------------------------");
     System.Console.WriteLine(newUser);
     if (ModelState.IsValid)
     {
         // If a User exists with provided email
         if (dbContext.Users.Any(u => u.Email == newUser.Email))
         {
             // Manually add a ModelState error to the Email field, with provided
             // error message
             ModelState.AddModelError("Email", "Email already in use!");
             return(View("Log-Reg"));
             // You may consider returning to the View at this point
         }
         else
         {
             // Initializing a PasswordHasher object, providing our User class as its
             PasswordHasher <Reg> Hasher = new PasswordHasher <Reg>();
             newUser.Password = Hasher.HashPassword(newUser, newUser.Password);
             dbContext.Add(newUser);
             dbContext.SaveChanges();
             HttpContext.Session.SetInt32("UId", newUser.UserId);
             HttpContext.Session.SetString("UName", newUser.Username);
         }
         return(RedirectToAction("Main", "Main"));
     }
     else
     {
         System.Console.WriteLine("-----------------------------------");
         System.Console.WriteLine("User not created");
         return(View("Log-Reg"));
     }
 }
示例#7
0
        public IActionResult Post([FromBody] Interior entity)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (entity.DefinitionID == 0)
            {
                ModelState.AddModelError <Interior>(e => e.Definition, "Could not determine type of interior, please specify the type.");
                return(BadRequest(ModelState));
            }

            entity.ID = 0;
            _context.Add(entity);
            _context.SaveChanges();
            return(Created(entity));
        }
 public static void DeleteImagesByAdvertisementID(this HouseContext db, int id)
 {
     foreach (Image i in db.Images)
     {
         if (i.AdvertisementID == id)
         {
             db.Images.Remove(i);
         }
     }
     db.SaveChanges();
 }
        public IActionResult Pic(string ProfilePic)
        {
            ViewBag.Id = HttpContext.Session.GetInt32("UId");
            Reg user = dbContext.Users
                       .FirstOrDefault(p => p.UserId == HttpContext.Session.GetInt32("UId"));

            user.ProfilePic = ProfilePic;
            System.Console.WriteLine("-------------------------------");
            System.Console.WriteLine(user.ProfilePic);
            dbContext.SaveChanges();
            return(RedirectToAction("Account"));
        }
        //// GET: Landlord/Create
        //public ActionResult Create()
        //{
        //    return View();
        //}


        public ActionResult CreateToDatabase(string description, string title, string address)
        {
            if (HttpContext.Session["ID"] != null && !HttpContext.Session["ID"].ToString().Equals(""))
            {
                //????must set both of two????
                Landlord landlord = db.Landlords.Find((int)HttpContext.Session["ID"]);
                //NULL?????
                Advertisement advertisement = new Advertisement();
                advertisement.Description = description;
                advertisement.Title       = title;
                advertisement.address     = address;
                // System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                HttpRequest        request = System.Web.HttpContext.Current.Request;
                HttpFileCollection files   = request.Files;
                int s = 3;
                if (files.Count > 0)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile FileSave = files[i];  //用key获取单个文件对象HttpPostedFile

                        if (FileSave != null && FileSave.FileName.Length > 0)
                        {
                            Image im = new Image
                            {
                                AdvertisementID = landlord.ID,
                                ImageData       = new byte[FileSave.ContentLength],
                                ImageMimeType   = FileSave.ContentType,
                                Description     = Request.Form[s]
                            };
                            FileSave.InputStream.Read(im.ImageData, 0, im.ImageData.Length);
                            if (advertisement.Images == null)
                            {
                                List <Image> imgs = new List <Image>();
                                imgs.Add(im);
                                advertisement.Images = imgs;
                            }
                            else
                            {
                                advertisement.Images.Add(im);
                            }
                        }
                        s++;
                    }
                }


                if (landlord.Advertisements == null)
                {
                    List <Advertisement> advs = new List <Advertisement>();
                    advs.Add(advertisement);
                    landlord.Advertisements = advs;
                }
                else
                {
                    landlord.Advertisements.Add(advertisement);
                }
                db.Entry(landlord).State = EntityState.Modified;
                db.SaveChanges();
                //advertisement.LandlordID = landlord.ID;
                ViewBag.messages = "Submit succefully!";
                return(RedirectToAction("Index", "Landlord"));
            }
            else
            {
                ViewBag.message = "please login in again!";
                return(RedirectToAction("Login", "Login"));
            }
        }
示例#11
0
        private void AddTestData(HouseContext context)
        {
            // NOTE: save changes inbetween ensure we have IDs for our entities

            // Add interior definitions for chairs and tables:

            // class Chair
            // {
            //     public string Manufacturer {get;set;}
            //     public string Model {get;set;}
            //     public int Year {get;set;}
            //     public double Weight {get;set;}
            // }

            var chairDefinition = new InteriorDefinition
            {
                Name = "Chair",
            };

            context.Add(chairDefinition);
            context.SaveChanges();

            context.Add(new InteriorPropertyDefinition
            {
                Name         = "Manufacturer",
                PropertyType = InteriorPropertyType.String,
                PropertyName = nameof(IUserDefinedPropertyBag.StringProperty1),
                DefinitionID = chairDefinition.ID,
                Definition   = chairDefinition,
            });
            context.Add(new InteriorPropertyDefinition
            {
                Name         = "Model",
                PropertyType = InteriorPropertyType.String,
                PropertyName = nameof(IUserDefinedPropertyBag.StringProperty2),
                DefinitionID = chairDefinition.ID,
                Definition   = chairDefinition,
            });
            context.Add(new InteriorPropertyDefinition
            {
                Name         = "Year",
                PropertyType = InteriorPropertyType.Int,
                PropertyName = nameof(IUserDefinedPropertyBag.IntProperty1),
                DefinitionID = chairDefinition.ID,
                Definition   = chairDefinition,
            });

            context.Add(new InteriorPropertyDefinition
            {
                Name         = "Weight",
                PropertyType = InteriorPropertyType.Double,
                PropertyName = nameof(IUserDefinedPropertyBag.DoubleProperty1),
                DefinitionID = chairDefinition.ID,
                Definition   = chairDefinition,
            });
            context.SaveChanges();


            // class Table
            // {
            //     public string Manufacturer {get;set;}
            //     public string Model {get;set;}
            //     public int ExpansionPanels {get;set;}
            //     public int SuitablePersonCount {get;set;}
            //     public double Width {get;set;}
            //     public double Height {get;set;}
            //     public double Depth {get;set;}
            // }

            var tableDefinition = new InteriorDefinition
            {
                Name = "Table",
            };

            context.Add(tableDefinition);
            context.SaveChanges();

            context.Add(new InteriorPropertyDefinition
            {
                Name         = "Manufacturer",
                PropertyType = InteriorPropertyType.String,
                PropertyName = nameof(IUserDefinedPropertyBag.StringProperty1),
                DefinitionID = tableDefinition.ID,
                Definition   = tableDefinition,
            });
            context.Add(new InteriorPropertyDefinition
            {
                Name         = "Model",
                PropertyType = InteriorPropertyType.String,
                PropertyName = nameof(IUserDefinedPropertyBag.StringProperty2),
                DefinitionID = tableDefinition.ID,
                Definition   = tableDefinition,
            });
            context.Add(new InteriorPropertyDefinition
            {
                Name         = "ExpansionPanels",
                PropertyType = InteriorPropertyType.Int,
                PropertyName = nameof(IUserDefinedPropertyBag.IntProperty1),
                DefinitionID = tableDefinition.ID,
                Definition   = tableDefinition,
            });
            context.Add(new InteriorPropertyDefinition
            {
                Name         = "SuitablePersonCount",
                PropertyType = InteriorPropertyType.Int,
                PropertyName = nameof(IUserDefinedPropertyBag.IntProperty2),
                DefinitionID = tableDefinition.ID,
                Definition   = tableDefinition,
            });
            context.Add(new InteriorPropertyDefinition
            {
                Name         = "Width",
                PropertyType = InteriorPropertyType.Double,
                PropertyName = nameof(IUserDefinedPropertyBag.DoubleProperty1),
                DefinitionID = tableDefinition.ID,
                Definition   = tableDefinition,
            });
            context.Add(new InteriorPropertyDefinition
            {
                Name         = "Height",
                PropertyType = InteriorPropertyType.Double,
                PropertyName = nameof(IUserDefinedPropertyBag.DoubleProperty2),
                DefinitionID = tableDefinition.ID,
                Definition   = tableDefinition,
            });
            context.Add(new InteriorPropertyDefinition
            {
                Name         = "Depth",
                PropertyType = InteriorPropertyType.Double,
                PropertyName = nameof(IUserDefinedPropertyBag.DoubleProperty3),
                DefinitionID = tableDefinition.ID,
                Definition   = tableDefinition,
            });
            context.SaveChanges();

            // Add some test houses and rooms (random data)

            var deskManufacturers = new[] { "Desk Inc.", "Desktopia", "Desk4You", "WeLoveDesks" };
            var deskModels        = new[] { "Dining Table", "Couch Table", "Pool Table", "Table Football Table", "Poker Table" };

            var chairManufacturers = new[] { "Chair Inc.", "Chairtopia", "Chair4You", "WeLoveChairs" };
            var chairModels        = new[] { "Armchair", "Rocking Chair", "Stool", "Wheelchair", "Deckchair" };

            var random = new Random();

            for (int houseIndex = 0; houseIndex < random.Next(1, 5); houseIndex++)
            {
                var house = new House
                {
                    Name    = "House " + houseIndex,
                    Address = "Main Street " + random.Next(1, 100)
                };
                context.Add(house);
                context.SaveChanges();

                for (int roomIndex = 0; roomIndex < random.Next(1, 10); roomIndex++)
                {
                    var room = new Room
                    {
                        Name    = house.Name + " - Room " + roomIndex,
                        House   = house,
                        HouseID = house.ID
                    };
                    context.Add(room);
                    context.SaveChanges();

                    for (int tableIndex = 0; tableIndex < random.Next(1, 5); tableIndex++)
                    {
                        var table = new Interior
                        {
                            Definition   = tableDefinition,
                            DefinitionID = tableDefinition.ID,
                            Room         = room,
                            RoomId       = room.ID,

                            StringProperty1 = deskManufacturers[random.Next(deskManufacturers.Length)],
                            StringProperty2 = deskModels[random.Next(deskModels.Length)],
                            IntProperty1    = random.Next(0, 2),         // ExpansionPanels
                            IntProperty2    = random.Next(4, 10),        // SuitablePersonCount
                            DoubleProperty1 = random.NextDouble() * 300, // Width (0-300cm)
                            DoubleProperty2 = random.NextDouble() * 120, // Height (0-120cm)
                            DoubleProperty3 = random.NextDouble() * 800, // Depth (0-800cm)
                        };
                        context.Add(table);
                    }
                    context.SaveChanges();

                    for (int chairIndex = 0; chairIndex < random.Next(1, 10); chairIndex++)
                    {
                        var chair = new Interior
                        {
                            Definition   = chairDefinition,
                            DefinitionID = chairDefinition.ID,
                            Room         = room,
                            RoomId       = room.ID,

                            StringProperty1 = chairManufacturers[random.Next(deskManufacturers.Length)],
                            StringProperty2 = chairModels[random.Next(deskModels.Length)],
                            IntProperty1    = random.Next(2000, DateTime.Now.Year + 1), // Year
                            DoubleProperty1 = 500 + random.NextDouble() * 500,          // Weight (500-1000g)
                        };
                        context.Add(chair);
                    }
                    context.SaveChanges();
                }
            }
        }