public void Initialize() { Database.SetInitializer <ShopDBContext>(null); try { using (var context = new ShopDBContext()) { if (!context.Database.Exists()) { ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } WebSecurity.InitializeDatabaseConnection("ShopDB", "Users", "UserId", "Email", autoCreateTables: true); SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider; SimpleMembershipProvider memberships = (SimpleMembershipProvider)Membership.Provider; if (!roles.RoleExists("Admin")) { roles.CreateRole("Admin"); } if (memberships.GetUser("*****@*****.**", false) == null) { memberships.CreateUserAndAccount("*****@*****.**", "qwerty1234"); roles.AddUsersToRoles(new[] { "*****@*****.**" }, new[] { "Admin" }); } } catch (Exception ex) { throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex); } }
public void save_order(orders order) { ShopDBContext db = new ShopDBContext(); db.Orders.Add(order); db.SaveChanges(); }
private void GetData() { ShopDBContext db = new ShopDBContext(); itemList = db.Inventory.ToList(); clientList = db.AspNetUsers.ToList(); }
public IActionResult OutLogin([FromBody] OutLoginInfo info) { var returnUrl = HttpContext.Request.Cookies["returnUrl"]; using (var db = new ShopDBContext()) { var user = db.Users.FirstOrDefault(u => u.UserID.Equals(info.email)); if (user == null) { user = new User() { UserID = info.email, Facebook = "Y" }; db.Users.Add(user); db.SaveChanges(); } user = db.Users.FirstOrDefault(u => u.UserID.Equals(info.email)); HttpContext.Session.SetInt32("Login_User", user.UserNo); ReturnUrl rUrl = new ReturnUrl { url = returnUrl }; return(Json(rUrl)); //return Ok(Json(new {url = returnUrl })); } }
public string update_product(int id, Product product) { try { ShopDBContext db = new ShopDBContext(); //Fetching objects from database Product p = db.Products.Find(id); p.Name = product.Name; p.Price = product.Price; p.AvailableQuantity = product.AvailableQuantity; p.Description = product.Description; p.CategoryID = product.CategoryID; p.DateUpdated = product.DateUpdated; p.size = product.size; p.Description = product.Description; if (product.Image != null) { p.Image = product.Image; } db.SaveChanges(); return(product.Name + "was successfully updated"); } catch (Exception e) { return("Error" + e); } }
public void save_order_items(ordered_items items) { ShopDBContext db = new ShopDBContext(); db.Orderd_items.Add(items); db.SaveChanges(); }
//[Authorize] use this for forcing user to login with Identity Framework. public IActionResult Shop() { ShopDBContext db = new ShopDBContext(); return(View("Shop", db)); }
public void Insert_userinfo(Users info) { ShopDBContext db = new ShopDBContext(); db.Users.Add(info); db.SaveChanges(); }
public IActionResult MakeNewUser(Users U) { using (var db = new ShopDBContext()) { var newUser = new Users { Email = U.Email, FirstName = U.FirstName, LastName = U.LastName, UserName = U.UserName, PassWord = U.PassWord, Funds = 100 }; db.Users.Add(newUser); if (db.SaveChanges() > 0) { //Do the work to create new user; //if successful return view Register Success; if not (go back to register page or another view) return(View("RegisterSuccess")); } else { // Was not able to save user to database for whatever reason. ViewBag.ErrorMessage("Was not successful."); return(View("Register")); } } }
public IActionResult MakeNewUser(Users u) { using (var db = new ShopDBContext()) { var newUser = new Users { Email = u.Email, FirstName = u.FirstName, LastName = u.LastName, UserName = u.UserName, PassWord = u.PassWord, Funds = 100 }; db.Users.Add(newUser); if (db.SaveChanges() > 0) { return(View("RegisterSuccess")); } else { ViewBag.ErrorMessage("Was not successful."); return(View("Register")); } } }
void CreateUser(ShopDBContext context) { var manager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ShopDBContext())); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ShopDBContext())); var user = new ApplicationUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true, Birthday = DateTime.Now, FullName = "Hoang Thuc" }; manager.Create(user, "thuc0533"); if (!roleManager.Roles.Any()) { roleManager.Create(new IdentityRole { Name = "Admin" }); roleManager.Create(new IdentityRole { Name = "User" }); } var adminUser = manager.FindByEmail("*****@*****.**"); manager.AddToRoles(adminUser.Id, new string[] { "Admin", "User" }); }
void CreateProductCategory(ShopDBContext context) { if (context.ProductCategories.Count() == 0) { List <ProductCategory> l = new List <ProductCategory>() { new ProductCategory() { Name = "Iphone6", Description = "Dien thoai apple", Status = false }, new ProductCategory() { Name = "Iphone7", Description = "Dien thoai apple", Status = true }, new ProductCategory() { Name = "Iphone8", Description = "Dien thoai apple", Status = true }, new ProductCategory() { Name = "IphoneX", Description = "Dien thoai apple", Status = true } }; context.ProductCategories.AddRange(l); context.SaveChanges(); } }
private void GetData() { ShopDBContext db = new ShopDBContext(); itemlist = db.Items.ToList(); userlist = db.Users.ToList(); }
private void CreateContactDetail(ShopDBContext context) { if (context.ContactDetails.Count() == 0) { try { var contactDetail = new ContactDetail() { Name = "Shop Ipug sell iphone ", Address = "120 Lê Duẩn, Thạch Thang, Q. Hải Châu, Đà Nẵng", Email = "*****@*****.**", Lat = 16.07086, Lng = 108.2159, Phone = "0999666999", Website = "http://IpugMobile.com.vn", Other = "", Status = true }; context.ContactDetails.Add(contactDetail); context.SaveChanges(); } catch (DbEntityValidationException ex) { foreach (var eve in ex.EntityValidationErrors) { Trace.WriteLine($"Entity of type \"{eve.Entry.Entity.GetType().Name}\" in state \"{eve.Entry.State}\" has the following validation error."); foreach (var ve in eve.ValidationErrors) { Trace.WriteLine($"- Property: \"{ve.PropertyName}\", Error: \"{ve.ErrorMessage}\""); } } } } }
public IActionResult Login(string username, string password) { using (var db = new ShopDBContext()) { var user = db.Users.FirstOrDefault(u => u.UserName == username); if (user != null) { //check password if user is not null if (password == user.PassWord) { HttpContext.Session.SetString("session_username", user.UserName); //TODO: CHANGE TO APPROPRIATE VIEW TO GO TO return(View("RegisterSuccess")); //RegisterSuccess returned here originally } else { ViewBag.ErrorMessage = "Password is incorrect"; return(View()); } } else // user was Null, not found in database { ViewBag.ErrorMessage = "User not Found"; return(View()); } } }
public IActionResult Shop(string username) { // Use my context class to pull in my DataBase data ShopDBContext db = new ShopDBContext(); // make an indiviodual Person object to store my result in Users matchedUser = new Users(); // make an indiviodual Person object to store my result in TempData["Registered"] = false; // i need to find my result in my DB foreach (Users user in db.Users) { // as i iterate through the collection, I want to find the correct result if (user.Username == username) { // if you find a match, assign that value to your temp Person object matchedUser = user; //you found a match, set your TempData to true //this allows us to display certain HTML TempData["Registered"] = true; } } // pass the object with the data to the view to be displayed return(View(matchedUser)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews() .AddNewtonsoftJson() .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; options.JsonSerializerOptions.WriteIndented = true; }); services.AddDbContext <ApplicationDBContext>(opt => opt.UseNpgsql(Configuration.GetConnectionString("NpgsqlConection"), b => b.MigrationsAssembly("DatabaseTools")) ); ApplicationDBContext.ConfigureServices(services); services.AddDbContext <ShopDBContext>(opt => opt.UseNpgsql(Configuration.GetConnectionString("NpgsqlConection"), b => b.MigrationsAssembly("DatabaseTools")) ); ShopDBContext.ConfigureServices(services); services.AddMemoryCache(); services.AddScoped <ICacheBase, CacheBase>(); services.AddScoped <UserInfoCache>(); services.AddScoped <ConfigurationCache>(); services.AddHostedService <QueuedHostedService>(); services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>(); services.AddScoped <AppSettings>(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Login/Index/"; }); }
//[HttpPost] //[AllowAnonymous] public IActionResult Validate(string username, string password) { ShopDBContext db = new ShopDBContext(); //use object to access Users table Users users = new Users(); HttpContext.Session.SetString("UserInSession", "false"); var searchedUser = db.AspNetUsers.SingleOrDefault(u => u.UserName == username); foreach (Users user in db.Users) { if (user.UserName == username && user.Password == password) { //declare users (Users table) to match the user users = user; HttpContext.Session.SetString("UserInSession", "true"); HttpContext.Session.SetString("Funds", users.Funds.ToString()); HttpContext.Session.SetString("User", users.UserName.ToString()); HttpContext.Session.SetString("Id", users.Id.ToString()); return(RedirectToAction("Shop")); } else { return(RedirectToAction("Login")); } } return(View(users)); }
public IActionResult ValidateUser(Users user) { ShopDBContext db = new ShopDBContext(); var validateEmail = db.Users.Where(b => b.Email == user.Email).FirstOrDefault(); var validatePw = db.Users.Where(b => b.Email == user.Email && b.Password == user.Password).FirstOrDefault(); if (validateEmail != null && validatePw != null) { HttpContext.Session.SetInt32("current", validatePw.Id); return(RedirectToAction("Shop")); } else if (validateEmail == null) { TempData["IncorrectEmail"] = true; return(View("LoginPage")); } else if (validatePw == null) { TempData["IncorrectPw"] = true; return(View("LoginPage")); } else { return(View("LoginPage")); } }
public Category get_category_by_id(int id) { ShopDBContext db = new ShopDBContext(); Category c = db.Categories.Find(id); return(c); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (HttpContext.Current.Session["userid"] == null) { filterContext.Result = new RedirectResult("/Admin/Home/Login"); return; } // lay quyen trong co so du lieu string nameAction = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName + "Controller-" + filterContext.ActionDescriptor.ActionName; int userID = (int.Parse(HttpContext.Current.Session["userid"].ToString())); ShopDBContext DB = new ShopDBContext(); var user = DB.Accounts.Where(x => x.UserId == userID && x.Allowed == 1).FirstOrDefault(); if (user != null) { if (user.isAdmin == 1) { return; } else { var listMission = from p in DB.Permissions join g in DB.GantPermissions on p.PermissionId equals g.PermissionId where g.UserId == userID select p.PermissionName; if (!listMission.Contains(nameAction)) { filterContext.Result = new RedirectResult("~/Admin/Home/NotificationAuthorize"); } } } }
public void CreateProduct(Product product) { using (var dbc = new ShopDBContext()) { dbc.Add(product); dbc.SaveChanges(); } }
public IActionResult AddUser(Users user) { ShopDBContext db = new ShopDBContext(); db.Add(user); db.SaveChanges(); return(View(user)); }
public IActionResult PurchaseItem(Items item) { ShopDBContext db = new ShopDBContext(); Users founduser = new Users(); Items foundItem = new Items(); PurchasedItems foundPurchasedItem = new PurchasedItems(); foreach (Users u in db.Users) { if (u.Id == HttpContext.Session.GetInt32("current")) { founduser = u; } } foreach (Items i in db.Items) { if (i.ProductName == item.ProductName) { foundItem = i; } } foreach (PurchasedItems d in db.PurchasedItems) { if (d.ProductName == item.ProductName && d.UserId == founduser.Id) { foundPurchasedItem = d; } } if (founduser.Funds > foundItem.Price) { founduser.Funds -= foundItem.Price; foundItem.Quantity -= 1; PurchasedItems purchasedItem = new PurchasedItems() { UserId = founduser.Id, ProductName = foundItem.ProductName, Description = foundItem.Description, ItemType = foundItem.ItemType, Quantity = 1 }; UserItems useritem = new UserItems() { ItemId = foundItem.ProductName, UserId = founduser.Id, }; db.Add(useritem); if (foundPurchasedItem.ProductName != null) { foundPurchasedItem.Quantity += 1; } else { db.Add(purchasedItem); } db.SaveChanges(); return(View("Shop", db)); } else { return(InsufficientFunds(founduser.Funds.ToString(), foundItem.Price.ToString())); } }
public orders Get_order_userinfo(int id) { ShopDBContext db = new ShopDBContext(); orders info = (from x in db.Orders where x.id == id select x).FirstOrDefault(); return(info); }
public int available_quantity_product(int product) { ShopDBContext db = new ShopDBContext(); int quantity = (from x in db.Products where x.ID == product select x.AvailableQuantity).FirstOrDefault(); return(quantity); }
public Users Get_userinfo(string AuthID) { ShopDBContext db = new ShopDBContext(); Users info = (from x in db.Users where x.AuthID == AuthID select x).FirstOrDefault(); return(info); }
public int check_order_productid(string userID, int product) { ShopDBContext db = new ShopDBContext(); int orders = (from x in db.Purchases where x.UsersID == userID && product == x.ProductID select x.ProductID).FirstOrDefault(); return(orders); }
public IActionResult MakeNewUser(Users u) { //use this object to access db data ShopDBContext db = new ShopDBContext(); db.Add(u); db.SaveChanges(); return(View(u)); }
//public int get_amountofOrders(string userID) //{ // try // { // ShopDBContext db = new ShopDBContext(); // int totalprice = (from x in db.Purchases // where x.UsersID == userID // && x.IsInCart // select x.TotalPrice).Sum(); // return totalprice; // } // catch // { // return 0; // } //} public void update_quantity(int id, int quantity) { ShopDBContext db = new ShopDBContext(); Purchase purchase = db.Purchases.Find(id); purchase.Quantity = quantity; db.SaveChanges(); }