Exemple #1
0
        public static void SeedDishesTest(UlloContext context, ApplicationUser firstUser)
        {
            context.Database.ExecuteSqlCommand("DELETE FROM Categories DBCC CHECKIDENT ('dbo.Categories', RESEED, 1)");
            context.Database.ExecuteSqlCommand("DELETE FROM Dishes DBCC CHECKIDENT ('dbo.Dishes', RESEED, 1)");
            context.Database.ExecuteSqlCommand("DELETE FROM Posts DBCC CHECKIDENT ('dbo.Posts', RESEED, 1)");
            context.Database.ExecuteSqlCommand("DELETE FROM Pictures DBCC CHECKIDENT ('dbo.Pictures', RESEED, 1)");
            context.Database.ExecuteSqlCommand("DELETE FROM Votes");

            string[] categoryNames = { "Piadine",                                  "Primi piatti in promo", "Primi piatti",                    "Secondi piatti caldi", "Secondi piatti di pesce caldi e freddi",
                                       "Secondi piatti freddi",                    "Insalatoni",            "Insalatoni fino a 5 ingredienti", "Contorni freddi",
                                       "Contorni caldi ordinabili entro le 11:00", "Desserts" };

            List <Category> categories = new List <Category>();

            foreach (string category in categoryNames)
            {
                categories.Add(new Category {
                    Name = category, Route = IdentityModels.getNameAsRoute(category)
                });
            }
            context.Categories.AddOrUpdate(categories.ToArray());
            context.SaveChanges();

            List <Dish> dishes = new List <Dish>();

            string[] dishNames = { "Penne con Sugo di Salsiccia e Panna", "Spaghetti con Pesto alla Genovese", "Spaghetti con Aglio, Olio e Peperoncino" };
            foreach (string dish in dishNames)
            {
                Dish d = new Dish {
                    Name = dish, Route = IdentityModels.getNameAsRoute(dish), Price = 3.20M, Created = DateTime.Now
                };
                d.User = firstUser;
                d.Categories.Add(categories[1]);
                d.Pictures.Add(new Picture {
                    Name      = dish,
                    Route     = String.Format("/Media/{0}.jpg", IdentityModels.getNameAsRoute(dish)),
                    Guid      = Guid.NewGuid(),
                    Created   = DateTime.Now,
                    AssetType = Picture.assetTypeEnum.Picture
                });
                dishes.Add(d);
            }
            context.Dishes.AddOrUpdate(dishes.ToArray());
            context.SaveChanges();

            for (int i = 1; i <= 100; i++)
            {
                // int r = randomizer.Next(dishes.Count);
                Dish randomDish = dishes.ElementAt(i % dishes.Count);

                Post p = new Post {
                    Created = DateTime.Now
                };
                p.User    = firstUser;
                p.Dish    = randomDish;
                p.Picture = randomDish.Pictures.ElementAt(0);
                context.Posts.AddOrUpdate(p);
            }
            context.SaveChanges();
        }
Exemple #2
0
        public async Task <ActionResult> Login(IdentityModels model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // No cuenta los errores de inicio de sesión para el bloqueo de la cuenta
            // Para permitir que los errores de contraseña desencadenen el bloqueo de la cuenta, cambie a shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToAction("Index", "Home"));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Intento de inicio de sesión no válido.");
                return(View(model));
            }
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new IdentityModels
                {
                    UserName = model.Email,
                    Email    = model.Email,
                    Name     = model.Name
                };

                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemple #4
0
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                using (IdentityModels entities = new IdentityModels())
                {
                    var userStore = new UserStore <User>(entities);

                    var manager = new UserManager <User>(userStore);

                    var user = manager.FindByEmail(model.EmailAddress);

                    if (manager.CheckPassword(user, model.Password))
                    {
                        FormsAuthentication.SetAuthCookie(model.EmailAddress, true);
                        //Something similar to this should redirect the user to the Create Review page once they log in. TempData likely not the way to go, unless you perhaps
                        //changed it. Sam mentioned using Filters, global filters just something like that
                        //if (TempData["ReviewAttempted"] != null)
                        //{
                        //    return RedirectToAction("Create", "Reviews", new { name = TempData["ThisProductName"], id = TempData["ThisProductID"] });
                        //}
                        return(RedirectToAction("Index", "Home"));
                    }
                    ModelState.AddModelError("EmailAddress", "Invalid username and/or password.");
                }
            }
            return(View(model));
        }
Exemple #5
0
        // GET: Blog

        public ActionResult Index()
        {
            IdentityModels db       = new IdentityModels();
            List <Blog>    bloglist = db.dbBlog.ToList();

            return(View("index", bloglist));
        }
Exemple #6
0
        // GET: Ticket/Create
        public async System.Threading.Tasks.Task <ActionResult> Acheter()
        {
            TicketViewModels ticketViewModels = new TicketViewModels();

            ticketViewModels.nbTicket = 0;
            IdentityModels userIdentity = await UserManager.FindByEmailAsync(User.Identity.Name);

            if (userIdentity != null)
            {
                var cartes = userIdentity.CarteModels;
                if (cartes != null && cartes.Count > 0)
                {
                    CarteModels carte = cartes.ElementAt(0);
                    if (carte.TicketModels != null)
                    {
                        ticketViewModels.nbTicket = (uint)carte.TicketModels.Count;
                        if (carte.TicketModels.Count > 0)
                        {
                            TicketModels ticket = carte.TicketModels.First();
                            ticketViewModels.prixTicket = ticket.TarifModels.prix;
                        }
                        else
                        {
                            double prix = bdd.TarifModels.ToList().Find(t => t.type.Contains("ticket")).prix;
                            ticketViewModels.prixTicket = prix;
                        }
                    }
                }
            }
            return(View(ticketViewModels));
        }
Exemple #7
0
        public async Task <ActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                using (IdentityModels entities = new IdentityModels())
                {
                    var userStore = new UserStore <User>(entities);

                    var manager = new UserManager <User>(userStore);
                    manager.UserTokenProvider = new EmailTokenProvider <User>();

                    var user = new User()
                    {
                        UserName = model.EmailAddress,
                        Email    = model.EmailAddress
                    };

                    IdentityResult result = manager.Create(user, model.Password);

                    if (result.Succeeded)
                    {
                        User u = manager.FindByName(model.EmailAddress);

                        // Creates customer record in Braintree
                        string merchantId  = ConfigurationManager.AppSettings["Braintree.MerchantID"];
                        string publicKey   = ConfigurationManager.AppSettings["Braintree.PublicKey"];
                        string privateKey  = ConfigurationManager.AppSettings["Braintree.PrivateKey"];
                        string environment = ConfigurationManager.AppSettings["Braintree.Environment"];
                        Braintree.BraintreeGateway braintree = new Braintree.BraintreeGateway(environment, merchantId, publicKey, privateKey);
                        Braintree.CustomerRequest  customer  = new Braintree.CustomerRequest();
                        customer.CustomerId = u.Id;
                        customer.Email      = u.Email;

                        var r = await braintree.Customer.CreateAsync(customer);

                        string confirmationToken = manager.GenerateEmailConfirmationToken(u.Id);

                        string sendGridApiKey = ConfigurationManager.AppSettings["SendGrid.ApiKey"];

                        SendGrid.SendGridClient client = new SendGrid.SendGridClient(sendGridApiKey);
                        SendGrid.Helpers.Mail.SendGridMessage message = new SendGrid.Helpers.Mail.SendGridMessage();
                        message.Subject = string.Format("Please confirm your account");
                        message.From    = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Will Mabrey");
                        message.AddTo(new SendGrid.Helpers.Mail.EmailAddress(model.EmailAddress));
                        SendGrid.Helpers.Mail.Content contents = new SendGrid.Helpers.Mail.Content("text/html", string.Format("<a href=\"{0}\">Confirm Account</a>", Request.Url.GetLeftPart(UriPartial.Authority) + "/MyAccount/Confirm/" + confirmationToken + "?email=" + model.EmailAddress));

                        message.AddContent(contents.Type, contents.Value);
                        SendGrid.Response response = await client.SendEmailAsync(message);

                        return(RedirectToAction("ConfirmSent"));
                    }
                    else
                    {
                        ModelState.AddModelError("EmailAddress", "Unable to register with this email address.");
                    }
                }
            }
            return(View(model));
        }
Exemple #8
0
        public async System.Threading.Tasks.Task <ActionResult> Acheter(TicketViewModels ticketvm)
        {
            try
            {
                uint           nbTicketSurLaCarte = 0;
                IdentityModels userIdentity       = await UserManager.FindByEmailAsync(User.Identity.Name);

                if (userIdentity != null)
                {
                    var         cartes = userIdentity.CarteModels;
                    CarteModels carte  = cartes.ElementAt(0);
                    nbTicketSurLaCarte = (uint)carte.TicketModels.Count;
                    if (carte != null)
                    {
                        ICollection <TicketModels> ticketList;
                        if (carte.TicketModels == null)
                        {
                            ticketList = new List <TicketModels>();
                        }
                        else
                        {
                            ticketList = carte.TicketModels;
                        }
                        for (int i = 0; i < ticketvm.nbTicket; i++)
                        {
                            TicketModels ticket = new TicketModels();
                            ticket.CarteModelsID = carte.Id;
                            int tarifId = bdd.TarifModels.ToList().Find(t => t.type.Contains("ticket")).Id;
                            ticket.TarifModelsID = tarifId;
                            ticketList.Add(ticket);
                            bdd.TicketModels.Add(ticket);
                        }
                        //carte.TicketModels = ticketList;
                        // bdd.CarteModels.Add(carte);
                        bdd.SaveChanges();
                    }
                }
                ticketvm.nbTicket   = (uint)ticketvm.nbTicket + nbTicketSurLaCarte;
                ticketvm.prixTicket = bdd.TarifModels.Find(3).prix;
                //return RedirectToAction("Index");
                return(View(ticketvm));
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}",
                                               validationError.PropertyName,
                                               validationError.ErrorMessage);
                    }
                }
                return(View(ticketvm));
            }
        }
        public CarteModels findCarteByUser(string email)
        {
            IdentityModels userIdentity = userManager.FindByEmail(email);

            if (userIdentity != null)
            {
                var cartes = userIdentity.CarteModels;
                if (cartes != null && cartes.Count > 0)
                {
                    return(cartes.First());
                }
            }
            throw new Exception("L'utilisateur n'a pas de carte");
        }
Exemple #10
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var         userStore   = new UserStore <IdentityModels>(db);
                    var         userManager = new UserManager <IdentityModels>(userStore);
                    CarteModels carte       = new CarteModels {
                    };
                    carte.dateCreation = DateTime.Today;
                    var user = new IdentityModels {
                        UserName = model.Email, Email = model.Email
                    };
                    user.CarteModels.Add(carte);
                    var result = await UserManager.CreateAsync(user, model.Password);

                    userManager.AddToRole(user.Id, "user");
                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        // Pour plus d'informations sur l'activation de la confirmation du compte et la réinitialisation du mot de passe, consultez http://go.microsoft.com/fwlink/?LinkID=320771
                        // Envoyer un message électronique avec ce lien
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // await UserManager.SendEmailAsync(user.Id, "Confirmez votre compte", "Confirmez votre compte en cliquant <a href=\"" + callbackUrl + "\">ici</a>");

                        return(RedirectToAction("Index", "Home"));
                    }
                    AddErrors(result);
                }

                // Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
                return(View(model));
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}",
                                               validationError.PropertyName,
                                               validationError.ErrorMessage);
                    }
                }
                return(View(model));
            }
        }
Exemple #11
0
        public async Task <HttpResponseMessage> Signup(UserSignUp model)
        {
            if (model == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No Data"));
            }
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName        = model.UserName,
                    Email           = model.Email,
                    FirstName       = model.FirstName,
                    LastName        = model.LastName,
                    FacebookId      = model.FacebookId,
                    FacebookPicture = model.FacebookPicture,
                    FacebookToken   = model.FacebookToken,
                    Route           = IdentityModels.getNameAsRoute(model.UserName),
                };
                var result = await users.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInHelper.SignInAsync(user, true, false);

                    var account = new UserDetail();
                    account.UserName        = user.UserName;
                    account.FirstName       = user.FirstName;
                    account.LastName        = user.LastName;
                    account.FacebookId      = user.FacebookId;
                    account.isAuthenticated = true;
                    account.Route           = user.Route;
                    var rolesForUser = users.GetRoles(user.Id);
                    account.isAdmin = rolesForUser.Contains("Admin");
                    return(Request.CreateResponse(account));
                    // var code = await users.GenerateEmailConfirmationTokenAsync(user.Id);
                    // send email confirmation token
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, result.Errors.FirstOrDefault()));
                }
            }
            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
        }
Exemple #12
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (IdentityModels entities = new IdentityModels())
                {
                    var userStore = new UserStore <User>(entities);
                    var manager   = new UserManager <User>(userStore);

                    manager.UserTokenProvider = new EmailTokenProvider <User>();

                    var user = manager.FindByName(model.Email);
                    // If user has to activate his email to confirm his account, the use code listing below
                    //if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                    //{
                    //    return Ok();
                    //}


                    string code = await manager.GeneratePasswordResetTokenAsync(user.Id);


                    string sendGridKey             = System.Configuration.ConfigurationManager.AppSettings["SendGrid.ApiKey"];
                    SendGrid.SendGridClient client = new SendGrid.SendGridClient(sendGridKey);
                    SendGrid.Helpers.Mail.SendGridMessage message = new SendGrid.Helpers.Mail.SendGridMessage();
                    message.Subject = string.Format("Reset Password");
                    message.From    = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Will Mabrey");
                    message.AddTo(new SendGrid.Helpers.Mail.EmailAddress(model.Email));

                    SendGrid.Helpers.Mail.Content contents = new SendGrid.Helpers.Mail.Content("text/html", string.Format("<a href=\"{0}\">Reset Password</a>", Request.Url.GetLeftPart(UriPartial.Authority) + "/MyAccount/ResetPassword/" + code + "?EmailAddress=" + model.Email));

                    message.AddContent(contents.Type, contents.Value);
                    SendGrid.Response response = await client.SendEmailAsync(message);

                    //await client.SendEmailAsync(user.Id, "Reset Password", $"Please reset your password by using this {code}");
                    return(RedirectToAction("ResetSent"));
                }
            }
            return(View());

            // If we got this far, something failed, redisplay form
        }
Exemple #13
0
        //ajasdjasdj
        public ActionResult save(cms.Models.Blog blg)
        {
            #region old

            /*if (ModelState.IsValid)
             * {
             *  string FileName = ab.fileName;
             *  string data = ab.Content;
             *  Markdown md = new Markdown();
             *  var html = md.Transform(data);
             *  StreamWriter sr = new StreamWriter(Server.MapPath("/blogFiles/" + FileName + ".htm"), true);
             *  sr.WriteAsync(html);
             *  sr.Close();
             *
             *  string str;
             *  using (StreamReader sreader = new StreamReader(Server.MapPath("/blogFiles/blog.dat")))
             *  {
             *      str = sreader.ReadToEnd();
             *  }
             *  string[] frs = str.Split('|');
             *  int a = Convert.ToInt32(frs[0]);
             *  a++;
             *  System.IO.File.Delete(Server.MapPath("/blogFiles/blog.dat"));
             *  string today = DateTime.Now.ToShortDateString();
             *  using (StreamWriter swriter = new StreamWriter(Server.MapPath("/blogFiles/blog.dat"), false))
             *  {
             *      string strn = a + "|" + FileName + "|" + FileName + "|" + FileName + ".htm" + "|" + today;
             *      swriter.Write(strn);
             *      swriter.Write(Environment.NewLine);
             *      swriter.Write(str);
             *  }
             * }*/
            #endregion
            IdentityModels db      = new IdentityModels();
            Blog           objBlog = new Blog();
            objBlog.title       = blg.title;
            objBlog.description = blg.description;
            db.dbBlog.Add(objBlog);
            db.SaveChanges();
            return(View("AddBlog"));
        }
Exemple #14
0
        public ActionResult Confirm(string id, string email)
        {
            using (IdentityModels entities = new IdentityModels())
            {
                var userStore = new UserStore <User>(entities);

                var manager = new UserManager <User>(userStore);
                manager.UserTokenProvider = new EmailTokenProvider <User>();
                var user = manager.FindByName(email);
                if (user != null)
                {
                    var result = manager.ConfirmEmail(user.Id, id);
                    if (result.Succeeded)
                    {
                        TempData.Add("AccountConfirmed", true);
                        return(RedirectToAction("Login"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new IdentityModels {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
Exemple #16
0
        public ActionResult ResetPassword(ResetPasswordViewModel model)
        {
            using (IdentityModels entities = new IdentityModels())
            {
                var userStore = new UserStore <User>(entities);

                var manager = new UserManager <User>(userStore);
                var user    = manager.FindByName(model.EmailAddress);

                manager.UserTokenProvider = new EmailTokenProvider <User>();

                if (user != null)
                {
                    var result = manager.ResetPassword(user.Id, model.Code, model.NewPassword);
                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Login"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
Exemple #17
0
 public WorkController()
 {
     _context = new IdentityModels();
 }
Exemple #18
0
        public async Task <HttpResponseMessage> AddDish([FromBody] DishAddView model)
        {
            if (model == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No Data"));
            }
            var user = db.Users.SingleOrDefault(u => u.UserName == User.Identity.Name);

            if (user == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.MethodNotAllowed, "Unknown User"));
                // throw new HttpResponseException(HttpStatusCode.MethodNotAllowed);
            }
            if (ModelState.IsValid)
            {
                Picture picture = Picture.getPictureFromBase64(model.PictureBase64);
                if (picture == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No Picture"));
                }
                try
                {
                    foreach (Category category in model.Categories)
                    {
                        db.Categories.Attach(category);
                    }
                    decimal Price = 0.0M;
                    Decimal.TryParse(model.Price.Replace(",", "."), NumberStyles.Currency, CultureInfo.InvariantCulture, out Price);
                    Dish dish = new Dish {
                        Categories      = model.Categories,
                        Name            = model.Name,
                        Route           = IdentityModels.getNameAsRoute(model.Name),
                        Price           = Price,
                        isVeganFriendly = model.isVeganFriendly,
                        Created         = DateTime.Now
                    };
                    dish.Pictures.Add(picture);
                    dish.User = user;
                    db.Dishes.Add(dish);
                    await db.SaveChangesAsync();

                    return(Request.CreateResponse(HttpStatusCode.OK, new DishView {
                        Id = dish.Id,
                        Name = dish.Name,
                        Price = dish.Price,
                        isVeganFriendly = dish.isVeganFriendly,
                        Yes = dish.Yes,
                        No = dish.No,
                        Categories = dish.Categories.Select(c => new CategoryView {
                            Id = c.Id,
                            Name = c.Name,
                        }).ToList(),
                        Pictures = dish.Pictures.Select(c => new PictureView {
                            Id = c.Id,
                            Name = c.Name,
                            Route = c.Route,
                            Created = c.Created,
                        }).ToList(),
                    }));
                } catch (Exception ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
                }
            }
            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
        }
Exemple #19
0
        public static void SeedDishes(UlloContext context, ApplicationUser firstUser)
        {
            context.Database.ExecuteSqlCommand("DELETE FROM Categories DBCC CHECKIDENT ('dbo.Categories', RESEED, 1)");
            context.Database.ExecuteSqlCommand("DELETE FROM Dishes DBCC CHECKIDENT ('dbo.Dishes', RESEED, 1)");
            context.Database.ExecuteSqlCommand("DELETE FROM Posts DBCC CHECKIDENT ('dbo.Posts', RESEED, 1)");
            context.Database.ExecuteSqlCommand("DELETE FROM Pictures DBCC CHECKIDENT ('dbo.Pictures', RESEED, 1)");
            context.Database.ExecuteSqlCommand("DELETE FROM Votes");

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.

            /** CATEGORIES **/
            List <Category> categories = new List <Category>();

            /*
             * Category[] categories = {
             *  new Category { Name = "Piadine", Route = Identity.getNameAsRoute("Piadine") },
             *  new Category { Name = "Primi piatti in promo" },
             *  new Category { Name = "Primi piatti" },
             *  new Category { Name = "Secondi piatti caldi" },
             *  new Category { Name = "Secondi piatti di pesce caldi e freddi" },
             *  new Category { Name = "Secondi piatti freddi" },
             *  new Category { Name = "Insalatoni" },
             *  new Category { Name = "Insalatoni fino a 5 ingredienti" },
             *  new Category { Name = "Contorni freddi" },
             *  new Category { Name = "Contorni caldi" },
             *  new Category { Name = "Contorni caldi ordinabili entro le 11:00" },
             *  new Category { Name = "Desserts" }
             * };
             * context.Categories.AddOrUpdate(categories);
             */
            string[] categoryNames = { "Piadine",                                  "Primi piatti in promo", "Primi piatti",                    "Secondi piatti caldi", "Secondi piatti di pesce caldi e freddi",
                                       "Secondi piatti freddi",                    "Insalatoni",            "Insalatoni fino a 5 ingredienti", "Contorni freddi",
                                       "Contorni caldi ordinabili entro le 11:00", "Desserts" };
            foreach (string category in categoryNames)
            {
                categories.Add(new Category {
                    Name = category, Route = IdentityModels.getNameAsRoute(category)
                });
            }
            context.Categories.AddOrUpdate(categories.ToArray());
            context.SaveChanges();

            /** DISHES **/

            /*
             * Dish[] dishes = {
             *  new Dish { Name = "Penne con Sugo di Salsiccia e Panna", Price = 3.20M },
             *  new Dish { Name = "Spaghetti con Pesto alla Genovese", Price = 3.20M },
             *  new Dish { Name = "Spaghetti con Aglio, Olio e Peperoncino", Price = 3.20M }
             * };
             * dishes[0].Categories.Add(categories[1]);
             * dishes[1].Categories.Add(categories[1]);
             * dishes[2].Categories.Add(categories[1]);
             * context.Dishes.AddOrUpdate(dishes);
             */
            string[] dishNames = { "Penne con Sugo di Salsiccia e Panna", "Spaghetti con Pesto alla Genovese", "Spaghetti con Aglio, Olio e Peperoncino" };
            foreach (string dish in dishNames)
            {
                Dish d = new Dish {
                    Name = dish, Route = IdentityModels.getNameAsRoute(dish), Price = 3.20M, Created = DateTime.Now
                };
                d.User = firstUser;
                d.Categories.Add(categories[1]);
                d.Pictures.Add(new Picture {
                    Name      = dish,
                    Route     = String.Format("/Media/{0}.jpg", IdentityModels.getNameAsRoute(dish)),
                    Guid      = Guid.NewGuid(),
                    Created   = DateTime.Now,
                    AssetType = Picture.assetTypeEnum.Picture
                });
                context.Dishes.AddOrUpdate(d);
            }
            context.SaveChanges();
        }
Exemple #20
0
        protected override void Seed(ManageSub.DAL.ManageSubContext context)
        {
            var roleManager = new RoleManager <RoleModels>(new RoleStore <RoleModels>(new ManageSubContext()));
            var roleresult  = roleManager.Create(new RoleModels("user"));
            var roleresult2 = roleManager.Create(new RoleModels("admin"));
            var tarifs      = new List <TarifModels>
            {
                new TarifModels {
                    Id = 400, prix = 10.0, type = "abonnement"
                },
                new TarifModels {
                    Id = 402, prix = 20.0, type = "abonnement"
                },
                new TarifModels {
                    Id = 403, prix = 1.70, type = "ticket"
                },
                new TarifModels {
                    Id = 404, prix = 1.40, type = "ticket"
                }
            };

            tarifs.ForEach(s => context.TarifModels.Add(s));

            var typeAbo = new List <TypeAbonnementModels>
            {
                new TypeAbonnementModels {
                    Id = 500, Intitule = "Etudiant", Conditon = "Posseder une carte étudiant", TarifModelsID = tarifs.First().Id
                },
                new TypeAbonnementModels {
                    Id = 501, Intitule = "Normal", Conditon = "Pas de condition", TarifModelsID = tarifs.Last().Id
                }
            };

            typeAbo.ForEach(s => context.TypeAbonnementModels.Add(s));



            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userStore     = new UserStore <IdentityModels>(context);
                var userManager   = new UserManager <IdentityModels>(userStore);
                var userToInsert2 = new IdentityModels {
                    UserName = "******", PhoneNumber = "0797697898", Email = "*****@*****.**", EmailConfirmed = true
                };
                userManager.Create(userToInsert2, "azerty");
                userManager.AddToRole(userToInsert2.Id, "user");

                var carte = new List <CarteModels>
                {
                    new CarteModels {
                        Id = 200, IdentityModels = userToInsert2, dateCreation = DateTime.Parse("2015-09-01")
                    }
                };
                carte.ForEach(s => context.CarteModels.Add(s));
                var ticketList = new List <TicketModels>
                {
                    new TicketModels {
                        Id = 700, CarteModelsID = carte.First().Id, TarifModelsID = tarifs.ElementAt(2).Id
                    }
                };
                ticketList.ForEach(s => context.TicketModels.Add(s));

                var abos = new List <AbonnementModels>
                {
                    new AbonnementModels {
                        AbonnementModelsId = 100, finDeValidite = DateTime.Now.AddYears(1), TypeAbonnementModelsID = typeAbo.First().Id, CarteModelsID = carte.First().Id
                    },
                    new AbonnementModels {
                        AbonnementModelsId = 101, finDeValidite = DateTime.Now.AddYears(1), TypeAbonnementModelsID = typeAbo.Last().Id, CarteModelsID = carte.First().Id
                    }
                };
                abos.ForEach(s => context.AbonnementModels.Add(s));
            }



            if (!(context.Users.Any(u => u.UserName == "admin")))
            {
                var userStore    = new UserStore <IdentityModels>(context);
                var userManager  = new UserManager <IdentityModels>(userStore);
                var userToInsert = new IdentityModels {
                    UserName = "******", PhoneNumber = "0897876565", Email = "*****@*****.**", EmailConfirmed = true
                };
                userManager.Create(userToInsert, "azerty");
                userManager.AddToRole(userToInsert.Id, "admin");

                var carte = new List <CarteModels>
                {
                    new CarteModels {
                        Id = 201, IdentityModels = userToInsert, dateCreation = DateTime.Parse("2015-09-24")
                    }
                };
                carte.ForEach(s => context.CarteModels.Add(s));
            }
            context.SaveChanges();
        }