コード例 #1
0
        public ActionResult Create([Bind(Exclude = "ReportDate, ", Include = "ReviewID,Rating,Comment, JobID, Reviewee")] Review review, int?job, string employer)
        {
            review.ReportDate = DateTime.UtcNow;
            //review.Reviewee = Reviewee;
            UserReviews rv = new UserReviews();

            rv.ReviewID = review.ReviewID;
            rv.UserID   = User.Identity.GetUserId();

            if (ModelState.IsValid)
            {
                db.Reviews.Add(review);
                db.UserReviews.Add(rv);
                db.SaveChanges();
                TempData["ReviewSuccess"] = "Review successfully submitted";
                return(RedirectToRoute("Default", new { controller = "Jobs", action = "Index" }));
            }

            var userID = User.Identity.GetUserId();

            if (employer != null)
            {
                var jobs = db.Jobs.Where(w => w.JobID == job).Include(e => e.Employer).Include(e => e.Employer.ApplicationUser).Where(e => e.EmployerID == employer);
                ViewBag.JList = jobs;
            }
            else
            {
                var jobs = db.Jobs.Where(w => w.JobID == job).Include(e => e.Employer).Include(e => e.Employer.ApplicationUser).Where(e => e.EmployerID == userID);
                ViewBag.JList = jobs;
            }
            var workers = db.JobApplications.Include(j => j.Job).Include(j => j.Worker).Include(j => j.Worker.ApplicationUser).Include(w => w.Worker).Where(j => j.JobID == job).Where(w => w.Response == Reply.Hired);

            ViewBag.WList = workers;
            return(View(review));
        }
コード例 #2
0
        public ActionResult Create([Bind(Exclude = "WorkerID, ApplicationDate, Response", Include = "JobApplicationID,JobID,Motivation, Flagged")] JobApplication jobApplication)
        {
            var id = User.Identity.GetUserId();

            jobApplication.ApplicationDate = DateTime.UtcNow;
            jobApplication.WorkerID        = id;
            jobApplication.Response        = Reply.Pending;
            var state = ModelState;


            try
            {
                db.JobApplications.Add(jobApplication);
                db.SaveChanges();
                TempData["ApplicationSuccess"] = "Your application has been submitted";
                return(RedirectToRoute("Default", new { controler = "JobApplications", action = "Index" }));
            }
            catch { }
            //catch
            //{
            //    db.SaveChanges();
            //    TempData["ApplicationSuccess"] = "Your application has been submitted";
            //    return RedirectToRoute("Defualt", new { controler = "JobApplications", action = "Index" });
            //}

            ViewBag.JobID    = jobApplication.JobID;
            ViewBag.Employer = db.Jobs.Include(s => s.Employer).Include(s => s.Employer.ApplicationUser).Include(s => s.Suburb).Where(s => s.JobID.Equals(jobApplication.JobID));
            ViewBag.WorkerID = User.Identity.GetUserId();
            TempData["ApplicationSuccess"] = "Your application was not submitted. Please review the all details on this form";
            return(View(jobApplication));
        }
コード例 #3
0
        public async Task <ActionResult> Create([Bind(Exclude = "ReportDate", Include = "IncidentID,JobID,Description,OffenderID,Progress")] Incident incident)
        {
            incident.ReportDate = DateTime.UtcNow;
            UserIncidents ui = new UserIncidents();

            ui.UserID     = User.Identity.GetUserId();
            ui.IncidentID = incident.IncidentID;

            Notification notice   = new Notification();
            var          offender = db.Users.Find(incident.OffenderID);

            if (ModelState.IsValid)
            {
                notice.Message = "An incident has been logged against you. Our admin will be in contact with you soon.";
                notice.User    = incident.OffenderID;
                notice.Updated = DateTime.UtcNow;
                notice.inc     = incident.IncidentID;

                db.Notifications.Add(notice);
                db.Incidents.Add(incident);
                db.UserIncidents.Add(ui);
                db.SaveChanges();

                TempData["IncidentReport"] = "Incident reported successfully. Please allow a couple of days for admin to look into it.";

                await EmailIncidentReport(incident.OffenderID);

                return(RedirectToRoute("Default", new { controller = "Incidents", action = "Index" }));
            }

            //ViewBag.JobApplicationID = new SelectList(db.JobApplications, "JobApplicationID", "Motivation", incident.JobApplicationID);
            return(View(incident));
        }
コード例 #4
0
 public static void RemoveUser(string myUserName)
 {
     if (CheckIfUserOnline(myUserName))
     {
         _identityDb.OnlineUsers.Remove(_identityDb.OnlineUsers.FirstOrDefault(x => x.Username == myUserName));
         _identityDb.SaveChanges();
     }
 }
コード例 #5
0
        public ActionResult Create([Bind(Include = "HelpID,HelpQuestion,HelpAnswer")] Help help)
        {
            if (ModelState.IsValid)
            {
                db.Helps.Add(help);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(help));
        }
コード例 #6
0
        public ActionResult Create(CrearPropuestaModel model)
        {
            if (ModelState.IsValid)
            {
                HttpPostedFileBase file = model.File;

                Propuesta propuesta = model.Propuesta;
                //asignar usuario dueno
                Usuario usuarioActual = ObtenerUsuarioActual(User);

                propuesta.UsuarioId = usuarioActual.Id;
                propuesta.Creador   = usuarioActual;
                usuarioActual.Propuestas.Add(propuesta);

                //aca codigo de la imagen


                if (file != null && file.ContentLength > 0)
                {
                    Guid   guid = Guid.NewGuid();
                    string str  = guid.ToString();

                    string path = Path.Combine(Server.MapPath("~/PropuestasPictures"), str + ".jpg");

                    using (MemoryStream outStream = new MemoryStream())
                    {
                        using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false))
                        {
                            Size size = new Size(1000, 1000);
                            ISupportedImageFormat format = new JpegFormat {
                                Quality = 80
                            };
                            imageFactory.Load(file.InputStream)
                            .Constrain(size)
                            .BackgroundColor(Color.White)
                            .Format(format)
                            .Save(path);
                        }
                    }

                    propuesta.URLFoto = str;
                    propuesta.Activa  = true;

                    db.Propuestas.Add(propuesta);
                    db.SaveChanges();

                    return(RedirectToAction("Index"));
                }

                ViewBag.UsuarioId = new SelectList(db.Usuarios, "Id", "Nombre", propuesta.UsuarioId);
                return(View(propuesta));
            }
            return(RedirectToAction("Index"));
        }
コード例 #7
0
        public ActionResult Create([Bind(Include = "CityID,CityName,CityAbbrev")] City city)
        {
            if (ModelState.IsValid)
            {
                db.Cities.Add(city);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(city));
        }
コード例 #8
0
        public ActionResult Create([Bind(Include = "NotificationID,Message,notice,Updated")] Notification notification)
        {
            if (ModelState.IsValid)
            {
                db.Notifications.Add(notification);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(notification));
        }
コード例 #9
0
        public ActionResult Create([Bind(Include = "SkillID,SkillDescription,Recom_Rate")] Skill skill)
        {
            if (ModelState.IsValid)
            {
                db.Skills.Add(skill);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(skill));
        }
コード例 #10
0
        public ActionResult Create([Bind(Include = "SuburbID,SubName,CityID")] Suburb suburb)
        {
            if (ModelState.IsValid)
            {
                db.Suburbs.Add(suburb);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CityID = new SelectList(db.Cities, "CityID", "CityName", suburb.CityID);
            return(View(suburb));
        }
コード例 #11
0
        public ActionResult Index(HomeIndexModel _HomeIndexModel, string returnUrl)
        {
            var currentUser = idb.Users.Find(User.Identity.GetUserId());

            if (_HomeIndexModel.LocationsId != null)
            {
                _HomeIndexModel.Locations = repository.GetLocations().ToList();
                currentUser.LocationID    = repository.GetLocations().Where(l => l.id == _HomeIndexModel.LocationsId).Select(o => o.id).FirstOrDefault();
                idb.SaveChanges();
            }
            else
            {
                _HomeIndexModel.LocationsId = 0;
            }

            if (currentUser.LocationID != null)
            {
                CultureHelper _CultureHelper = new CultureHelper(repository);
                TimeZoneInfo  TZone          = _CultureHelper.GetTimeZoneInfo(currentUser.LocationID);
                Location      _Location      = repository.GetLocations().Where(l => l.id == currentUser.LocationID).FirstOrDefault();
                _HomeIndexModel.FavouriteBunches = repository.GetFavouriteGroupsByLocation(_Location.id, currentUser.Id).ToList();
                Session["Culture"]                  = _CultureHelper.GetCulture(Convert.ToInt32(currentUser.LocationID));
                _HomeIndexModel.LocationsId         = _Location.id;
                _HomeIndexModel.CurrentUserLocation = _Location.Name;
                _HomeIndexModel.BunchCount          = repository.GetGroupCount(currentUser.LocationID);
                _HomeIndexModel.Followingcount      = repository.GetFollowingCount(currentUser.Id);
                _HomeIndexModel.HomePageRide        = repository.GetHomePageRideByUserID(currentUser.Id);
                if (_HomeIndexModel.HomePageRide != null)
                {
                    _HomeIndexModel.IsOnWay   = repository.IsOnWay(_HomeIndexModel.HomePageRide.id, currentUser.Id);
                    _HomeIndexModel.IsIn      = repository.IsIn(_HomeIndexModel.HomePageRide.id, currentUser.Id);
                    _HomeIndexModel.IsOut     = repository.IsOut(_HomeIndexModel.HomePageRide.id, currentUser.Id);
                    _HomeIndexModel.Keencount = repository.GetKeenCountForRide(_HomeIndexModel.HomePageRide.id);
                }
            }
            else
            {
                _HomeIndexModel.CurrentUserLocation = "Please set a Location";
            }

            if (returnUrl != null)
            {
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                return(View(_HomeIndexModel));
            }
        }
コード例 #12
0
        public ActionResult Create([Bind(Include = "EmployerID,WorkName,WorkNumber,WorkAddress1,WorkAddress2,SuburbID")] Employer employer)
        {
            if (ModelState.IsValid)
            {
                db.Employers.Add(employer);
                db.SaveChanges();
                TempData["WorkDetails"] = "Work details successfully updated";
                return(RedirectToRoute("Default", new { controller = "Manage", action = "Index" }));
            }


            ViewBag.SuburbID        = new SelectList(db.Suburbs, "SuburbID", "SubName", employer.SuburbID);
            TempData["WorkDetails"] = "Work details could not be updated. Please enter valid details";
            return(View(employer));
        }
コード例 #13
0
        public JsonResult Index(UserSettingsModel _SettingsModel)
        {
            var currentUser = idb.Users.Find(User.Identity.GetUserId());

            _SettingsModel.Locations = repository.GetLocations().ToList();

            //Check that user ID is a current location ID
            if (_SettingsModel.Locations.Any(l => l.id == _SettingsModel.LocationsId))
            {
                currentUser.LocationID    = repository.GetLocations().Where(l => l.id == _SettingsModel.LocationsId).Select(o => o.id).FirstOrDefault();
                currentUser.ReceiveEmails = _SettingsModel.ReceiveEmails;
                currentUser.FirstName     = _SettingsModel.FirstName;
                currentUser.LastName      = _SettingsModel.LastName;
                idb.SaveChanges();

                return(Json(new
                {
                    success = true,
                    message = "Settings Saved"
                }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new
                {
                    success = false,
                    message = "Please Select a Location"
                }, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #14
0
        public ActionResult Rights_DeleteUser(String id)
        {
            _identityDb.Users.Remove(_identityDb.Users.Find(id));
            _identityDb.SaveChanges();

            return(RedirectToAction("Rights"));
        }
コード例 #15
0
        public ActionResult ModificarUsuario(EditarUsuarioModel modelo)
        {
            if (ModelState.IsValid)
            {
                HttpPostedFileBase file     = modelo.File;
                Usuario            userInfo = modelo.MyUserInfo;

                if (userInfo.Fotos == null)
                {
                    userInfo.Fotos = new List <FotoPorfolio>();
                }


                if (file != null && file.ContentLength > 0)
                {
                    Guid   guid = Guid.NewGuid();
                    string str  = guid.ToString();

                    string path = Path.Combine(Server.MapPath("~/ProfilePictures"), str + ".jpg");

                    using (MemoryStream outStream = new MemoryStream())
                    {
                        using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false))
                        {
                            Size size = new Size(200, 200);
                            ISupportedImageFormat format = new JpegFormat {
                                Quality = 80
                            };
                            imageFactory.Load(file.InputStream)
                            .Constrain(size)
                            .BackgroundColor(Color.White)
                            .Format(format)
                            .Save(path);
                        }
                    }

                    userInfo.URLFotoPerfil = str;
                }
                Usuario usuarioActual = ObtenerUsuarioActual(User);

                //copiar una por una las propiedades al usuario actual
                usuarioActual.Apellido      = userInfo.Apellido;
                usuarioActual.Descripcion   = userInfo.Descripcion;
                usuarioActual.Email         = userInfo.Descripcion;
                usuarioActual.Facebook      = userInfo.Facebook;
                usuarioActual.Instagram     = userInfo.Instagram;
                usuarioActual.Nombre        = userInfo.Nombre;
                usuarioActual.Rol           = userInfo.Rol;
                usuarioActual.Telefono      = userInfo.Telefono;
                usuarioActual.URLFotoPerfil = userInfo.URLFotoPerfil;
                usuarioActual.Website       = userInfo.Website;

                db.Entry(usuarioActual).State = EntityState.Modified;
                db.SaveChanges();

                return(View("Usuario", ObtenerUsuarioActual(User)));
            }
            return(View(modelo));
        }
コード例 #16
0
        public async Task <JsonResult> Edit(UserViewModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(Json(new { Error = "Complete all required fields" }));
                }
                if (string.IsNullOrEmpty(model.Id))
                {
                    //create user
                    var user = Mapper.Map <ApplicationUser>(model);
                    user.Id = Guid.NewGuid().ToString();
                    var randomPassword = GeneratePassword(8);
                    var result         = await UserManager.CreateAsync(user, randomPassword);

                    if (result.Succeeded)
                    {
                        await UserManager.AddToRoleAsync(user.Id, "user");

                        //send email
                        var currentUser = UserManager.Users.SingleOrDefault(item => item.Id == UserId);

                        string msg = GetRegisterUsertEmailMsg();
                        msg = msg.Replace("@username", model.FirstName);
                        msg = msg.Replace("@byusername", currentUser?.FirstName + " " + currentUser?.LastName);
                        msg = msg.Replace("@email", model.Email);
                        msg = msg.Replace("@password", randomPassword);
                        msg = msg.Replace("@loginlink",
                                          ConfigurationManager.AppSettings["SiteAddress"] + "/Account/Login");
                        msg = msg.Replace("@siteaddress", ConfigurationManager.AppSettings["SiteAddress"]);
                        MailService.SendMail(model.Email, "Truck System User Details", msg);
                        return(Json(new { Done = 1 }));
                    }
                    return(Json(new { Error = "Cannot create user, please try again later." }));
                }
                else
                {
                    var user = await IdentityDb.Users.SingleOrDefaultAsync(item => item.Id == model.Id);

                    if (user != null)
                    {
                        user.FirstName   = model.FirstName;
                        user.LastName    = model.LastName;
                        user.CustomerId  = model.CustomerId;
                        user.Email       = model.Email;
                        user.PhoneNumber = model.PhoneNumber;
                        IdentityDb.SaveChanges();
                        return(Json(new { Done = 1 }));
                    }
                    return(Json(new { Error = "User not exist." }));
                }
            }
            catch (Exception exp)
            {
                return(null);
            }
        }
コード例 #17
0
ファイル: JobsController.cs プロジェクト: WarrenLuke/Exposure
        public ActionResult Update([Bind(Include = "JobID,Completed,StartDate, EndDate, EndTime, StartTime, DateAdvertised, Title, Description, AddressLine1, Rate, SuburbID")] Job job)
        {
            Job a = db.Jobs.Find(job.JobID);

            a.Completed = job.Completed;


            if (ModelState.IsValid)
            {
                db.Entry(a).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }


            ViewBag.Job      = db.Jobs.Where(j => j.JobID == job.JobID);
            ViewBag.JobID    = job.JobID;
            ViewBag.SuburbID = new SelectList(db.Suburbs, job.SuburbID);
            return(View(a));
        }
コード例 #18
0
        public ActionResult Create([Bind(Exclude = "CompanyBanner, Logo ", Include = "ID,CompanyName,Slogan,Description, SuburbID, TelNo, FaxNo, EmailAddress")] GeneralBusiness gb)
        {
            byte[] bannerData = null;

            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase poImgFile = Request.Files["CompanyBanner"];
                var image = poImgFile;
                using (var binary = new BinaryReader(poImgFile.InputStream))
                {
                    bannerData = binary.ReadBytes(poImgFile.ContentLength);
                }
            }

            byte[] logoData = null;

            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase poImgFile = Request.Files["Logo"];
                var image = poImgFile;
                using (var binary = new BinaryReader(poImgFile.InputStream))
                {
                    logoData = binary.ReadBytes(poImgFile.ContentLength);
                }
            }

            gb.Logo          = logoData;
            gb.CompanyBanner = bannerData;

            if (ModelState.IsValid)
            {
                db.GeneralBusinesses.Add(gb);
                db.SaveChanges();
                return(RedirectToRoute("Default", new { controller = "Manage", action = "Index" }));
            }

            return(View(gb));
        }
コード例 #19
0
        public ActionResult RoleCreate(string roleName)
        {
            using (var context = new IdentityDb())
            {
                var roleStore   = new RoleStore <IdentityRole>(context);
                var roleManager = new RoleManager <IdentityRole>(roleStore);

                roleManager.Create(new IdentityRole(roleName));
                context.SaveChanges();
            }

            ViewBag.ResultMessage = "Role created successfully !";
            return(RedirectToAction("RoleIndex", "Account"));
        }
コード例 #20
0
        public ActionResult Create([Bind(Exclude = "WorkerID", Include = "SkillID,YearsOfExperience")] WorkerSkill workerSkill, string returnUrl)
        {
            string user = User.Identity.GetUserId();


            workerSkill.WorkerID = user;
            var result = db.WorkerSkills.Find(user, workerSkill.SkillID);

            if (result != null)
            {
                TempData["exist"] = "You already added this skill. Please select a differnt one.";
                ViewBag.SkillID   = new SelectList(db.Skills, "SkillID", "SkillDescription", workerSkill.SkillID);
                ViewBag.WorkerID  = User.Identity.GetUserId();
                return(View(workerSkill));
            }

            if (ModelState.IsValid)
            {
                db.WorkerSkills.Add(workerSkill);
                db.SaveChanges();
                TempData["Skill"] = "Skill Added Successfully";

                return(RedirectToRoute("Default", new { controller = "Manage", action = "Index" }));
            }

            ViewBag.SkillID  = new SelectList(db.Skills, "SkillID", "SkillDescription", workerSkill.SkillID);
            ViewBag.WorkerID = User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(returnUrl))
            {
                return(Redirect(returnUrl));
            }
            else
            {
                return(View(workerSkill));
            }
        }
コード例 #21
0
        public IHttpActionResult PutProduct(int id, Product product)
        {
            var currentUser = manager.FindById(User.Identity.GetUserId());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != product.ProductId)
            {
                return(BadRequest());
            }

            product.UserId          = currentUser.Id;
            db.Entry(product).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }


            return(StatusCode(HttpStatusCode.NoContent));
        }
コード例 #22
0
 private static void AddCurrencies(this IdentityDb db)
 {
     if (!db.Currencies.Any())
     {
         db.Currencies.AddRange(new Currency()
         {
             Name = "RM"
         },
                                new Currency()
         {
             Name = "IRR"
         }
                                );
         db.SaveChanges();
     }
 }
コード例 #23
0
        public ActionResult Add_Recipes(Recipes recipes, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                string filename = "";
                byte[] bytes;
                int    BytestoRead;
                int    numBytesRead;
                if (file != null)

                {
                    filename = Path.GetFileName(file.FileName);

                    bytes = new byte [file.ContentLength];

                    BytestoRead = (int)file.ContentLength;

                    numBytesRead = 0;

                    while (BytestoRead > 0)

                    {
                        int n = file.InputStream.Read(bytes, numBytesRead, BytestoRead);

                        if (n == 0)
                        {
                            break;
                        }

                        numBytesRead += n;

                        BytestoRead -= n;
                    }

                    recipes.ImageUrl = bytes;
                }


                _db.Recipes.Add(recipes);
                _db.SaveChanges();
                return(RedirectToAction("Recipes", "Recipes"));
            }

            return(View());
        }
コード例 #24
0
 private static void AddLanguages(this IdentityDb db)
 {
     if (!db.Languages.Any())
     {
         db.Languages.AddRange(new Language()
         {
             Name = "English"
         },
                               new Language()
         {
             Name = "فارسی"
         },
                               new Language()
         {
             Name = "Malay"
         });
         db.SaveChanges();
     }
 }
コード例 #25
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            using (var db = new IdentityDb())
            {
                db.Database.Log = (c) => { System.Diagnostics.Debug.WriteLine(c); };

                foreach (var iclaim in userIdentity.Claims)
                {
                    if (acceptedClaims.Contains(iclaim.Type))
                    {
                        var usr = await manager.FindByIdAsync(this.Id);

                        var claim = usr.Claims.Where(c => c.ClaimType == iclaim.Type).FirstOrDefault();

                        if (claim == null)
                        {
                            usr.Claims
                            .Add(new UserClaimIntPk
                            {
                                ClaimType  = iclaim.Type,
                                ClaimValue = iclaim.Value,
                                UserId     = this.Id
                            });
                        }
                        else
                        {
                            if (claim.ClaimValue != iclaim.Value)
                            {
                                claim.ClaimValue      = iclaim.Value;
                                db.Entry(claim).State = System.Data.Entity.EntityState.Modified;
                            }
                        }
                    }
                }
                db.SaveChanges();
            }
            return(userIdentity);
        }
コード例 #26
0
        public async Task <ActionResult> CredentialsPost([Bind(Include = "Name,Id,Description")] RoleViewModel model, params int[] selectedCredentials)
        {
            if (model == null || selectedCredentials == null || selectedCredentials.Count() == 0) // BadRequest
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            // Adiciona credenciais
            ApplicationRole entityRole = _db.ApplicationRoles.Include(c => c.Credentials).Where(r => r.Id == model.Id).Single();

            if (entityRole == null) // NotFound
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
            }

            foreach (int credId in selectedCredentials)
            {
                Credential credential = _db.Credentials.Where(c => c.Id == credId).Single();
                entityRole.Credentials.Add(credential);
            }
            _db.Entry(entityRole).State = EntityState.Modified;
            _db.SaveChanges();

            // Remove credenciais
            var role = await RoleManager.FindByIdAsync(model.Id);

            List <int> removedCredentials = role.Credentials.Select(c => c.Id).ToList().Except(selectedCredentials).ToList();

            foreach (int credId in removedCredentials)
            {
                Credential credential = role.Credentials.Where(c => c.Id == credId).Single();
                role.Credentials.Remove(credential);
            }

            TempData["Success"] = string.Format("Credenciais de {0} modificadas com sucesso.", model.Name);

            await RoleManager.UpdateAsync(role);

            return(View("Index", RoleManager.Roles.OrderBy(r => r.Name)));
        }
コード例 #27
0
 public void SaveCategory(Category category)
 {
     _context.Categories.Add(category);
     _context.SaveChanges();
 }
コード例 #28
0
        internal static void RandomDogOwners(this IdentityDb context, int numberOfDogOwners, int emailLength, int phoneLength)
        {
            #region Helpers

            string[] EmailExtensions = new string[]
            {
                "@gmail.com", "@yahoo.com", "@outlook.com", "@yandex.com", "@aol.com", "@zoho.com", "@mail.com", "@tutanota.com"
            };

            string[] listFullNames = new string[]
            {
                "Lisette Gerhardt", "Kandis Paredes", "Carolee Ardis", "Debbi Monti", "John Chapman", "Francine Rosalez",
                "Rosette Hawkin", "Josie Poff", "Nadene Arnette", "Quinn Sharpe", "Breanna Costigan", "Reinaldo Tyra",
                "Stuart Easter", "Georgiana Molina", "Kira Pilkenton", "Olevia Coogan", "Cassaundra Breen", "Rosana Towner",
                "Georgetta Edinger", "Monique Bottomley", "Nathanial Nemitz", "Cheri Fender", "Claire Deibert", "Indira Flatt",
                "Sterling Kunz", "Lakendra Sowers", "Tandra Siguenza", "Angelique Nott", "Valrie Mcmiller", "Amina Paulos",
                "Rosetta Cervone", "Edgar Deharo", "Jacinta Mays", "Aldo Parsley", "Nelda Oritz", "Elroy Hallee", "Kathryn Enochs",
                "Thi Clift", "Arturo Vrba", "Forrest Natali", "Lorilee Herdt", "Marry Cottrell", "Manuela Musto", "Sheena Finney",
                "Audie Penny", "Ja Keogh", "Margurite Linney", "Ying Eble", "Tory Hennessy", "Somer Breed"
            };

            string RandomEmail(int numberOfLetters)
            {
                byte[] allLetters = new byte[numberOfLetters];

                for (int letter = 0; letter < numberOfLetters; letter++)
                {
                    if (letter == 0)
                    {
                        allLetters[letter] = (byte)random.Next(65, 91);
                        continue;
                    }
                    allLetters[letter] = (byte)random.Next(97, 123);
                }

                return(Encoding.ASCII.GetString(allLetters) + EmailExtensions[random.Next(EmailExtensions.Length)]);
            }

            string RandomPhoneNumber(int numberOfDigits)
            {
                char[] phoneLenght = new char[numberOfDigits];
                phoneLenght[0] = '0';
                phoneLenght[1] = '7';
                for (int i = 2; i < numberOfDigits; i++)
                {
                    if (i == 2)
                    {
                        phoneLenght[i] = random.Next(4).ToString()[0];
                        continue;
                    }

                    phoneLenght[i] = random.Next(10).ToString()[0];
                }

                return(new string(phoneLenght));
            }

            string RandomFullName()
            {
                return(listFullNames[random.Next(listFullNames.Length)]);
            }

            #endregion

            using (TransactionScope scope = new TransactionScope())
            {
                using (context = new IdentityDb())
                {
                    var haser = new PasswordHasher();
                    for (int i = 0; i < numberOfDogOwners; i++)
                    {
                        string userEmail = RandomEmail(emailLength);
                        string password  = "******";
                        string fullName  = RandomFullName();

                        var user = new ApplicationUser()
                        {
                            FirstName      = fullName.Split(null)[0],
                            LastName       = fullName.Split(null)[1],
                            PhoneNumber    = RandomPhoneNumber(9),
                            UserName       = userEmail,
                            Email          = userEmail,
                            IsConfirmed    = random.NextDouble() > 0.5,
                            LockoutEnabled = true,
                            PasswordHash   = haser.HashPassword(password)
                        };

                        context.Users.Add(user);

                        if (i % 100 == 0)
                        {
                            context.SaveChanges();
                            context.Dispose();
                            context = new IdentityDb();
                        }
                    }
                    context.SaveChanges();
                }
                scope.Complete();
            }
        }
コード例 #29
0
        public ActionResult Index(int groupid = -1, int rideid = -1, int InviteId = -1, string fromhome = "false")
        {
            var currentUser = idb.Users.Find(User.Identity.GetUserId());

            if (InviteId != -1)
            {
                if (repository.PrivateBunchInviteUserEmailNotSet(InviteId))
                {
                    repository.UpdateInvitePrivateUser(currentUser.Id, currentUser.Email, InviteId);
                    repository.Save();
                }
            }

            RideModelIndex RideModel = new RideModelIndex();
            Group          _Group    = repository.GetGroupByID(groupid);

            //If group is null, see if we can get the group from the rideid and if so recall action with just the groupid set.
            if (_Group == null)
            {
                _Group = repository.GetGroupByRideID(rideid);
                if (_Group != null)
                {
                    rideid  = -1;
                    groupid = _Group.id;
                    return(RedirectToAction("Index", new { groupid = _Group.id }));
                }
            }

            if (_Group == null)
            {
                GroupModel GroupModel = new GroupModel();
                GroupModel._Groups = repository.GetGroups().ToList();
                GroupModel.CurrentGroupMembership = repository.CurrentGroupsForUser(currentUser.Id);
                return(RedirectToAction("index", "group", GroupModel));
            }

            //Just in case location ID has not been set, set to same as ride.
            if (currentUser.LocationID == null)
            {
                currentUser.LocationID = _Group.Location.id;
                idb.SaveChanges();
            }

            RideModelHelper _RideHelper = new RideModelHelper(repository);
            var             t           = Request.QueryString["groupId"];

            if (groupid != -1 || rideid != -1)
            {
                RideModel = _RideHelper.PopulateRideModel(rideid, groupid, currentUser.Id, true);
            }
            else
            {
                GroupModel GroupModel = new GroupModel();
                GroupModel._Groups = repository.GetGroups().ToList();
                GroupModel.CurrentGroupMembership = repository.CurrentGroupsForUser(currentUser.Id);
                return(RedirectToAction("index", "group", GroupModel));
            }

            if (RideModel.Ride != null)
            {
            }
            else
            {
                GroupModel GroupModel = new GroupModel();
                GroupModel._Groups = repository.GetGroups().ToList();
                GroupModel.CurrentGroupMembership = repository.CurrentGroupsForUser(currentUser.Id);
                return(RedirectToAction("index", "group", GroupModel));
            }

            RideModel.FromHome    = fromhome;
            RideModel.IsFavourite = repository.IsInFavouriteList(RideModel.Group.id, currentUser.Id);
            if (_Group.Lat != null)
            {
                RideModel.lat = _Group.Lat;
            }

            if (_Group.Lng != null)
            {
                RideModel.lng = _Group.Lng;
            }

            if (RideModel.Group.IsPrivate)
            {
                if (!repository.IsInvitedToPrivateBunch(RideModel.Group.id, currentUser.Id))
                {
                    GroupModel GroupModel = new GroupModel();
                    GroupModel._Groups = repository.GetGroups().ToList();
                    GroupModel.CurrentGroupMembership = repository.CurrentGroupsForUser(currentUser.Id);
                    return(RedirectToAction("index", "group", GroupModel));
                }
            }

            RideModel.RouteCount = repository.RouteCountForGroup(RideModel.Group.id);

            return(View(RideModel));
        }
コード例 #30
0
 public void SaveProduct(Product product)
 {
     _context.Products.Add(product);
     _context.SaveChanges();
 }