Exemplo n.º 1
2
        public string AddBlock(string userId, string type)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
                var currentUser = manager.FindById(User.Identity.GetUserId());
                var blockedUser = manager.FindById(userId);

                if (type.Equals("Block"))
                {
                    currentUser.blockedList.Add(blockedUser);

                    //unfollow each person if there was any following
                    UnFollow(currentUser, blockedUser);
                    UnFollow(blockedUser, currentUser);
                }
                else  //unblock user just remove him from the list
                {
                    var block = currentUser.blockedList.Find(user => user.Id == blockedUser.Id);

                    if (block != null)
                    {
                        currentUser.blockedList.Remove(block);
                    }
                }

              //  manager.UpdateAsync(currentUser);

                var store = new UserStore<ApplicationUser>(new ApplicationDbContext());

               // store.Context.SaveChanges();
                db.SaveChanges();
                return "success";
            }
        }
Exemplo n.º 2
1
        public ContentResult CreateFileUsingName(string fileName)
        {
            using (var ctx = new ApplicationDbContext())
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ctx));
                var currentUser = manager.FindById(User.Identity.GetUserId());
                var fileManager = new FileManager(manager.FindById(User.Identity.GetUserId()).Id);

                    var entity = new File
                    {
                        Nom = fileName,
                        DateCreation = DateTime.Now,
                        NombreObjets = 0,
                        Taille = 10,
                        User = currentUser
                    };
                    ctx.Files.Add(entity);
                    ctx.SaveChanges();

                    fileManager.Create(fileName, "Testing");

            }

            return Content("file Added");
        }
Exemplo n.º 3
1
        public string AddFollow(string userId, string type)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
                var currentUser = manager.FindById(User.Identity.GetUserId());
                var followedUser = manager.FindById(userId);

                if (type.Equals("Follow"))
                {
                    currentUser.followList.Add(followedUser);
                }
                else
                {
                    UnFollow(currentUser, followedUser);
                }

                //manager.UpdateAsync(currentUser);

                var store = new UserStore<ApplicationUser>(new ApplicationDbContext());

                //store.Context.SaveChanges();
                db.SaveChanges();
                return "success";
            }
        }
Exemplo n.º 4
1
        public ActionResult Create(PatientViewModel patientDetail)
        {
            var alreadyExists = db.PatientDetails.Where(p => p.FullName == patientDetail.PatientDetails.FullName && p.ContactNo == patientDetail.PatientDetails.ContactNo);
            if (alreadyExists.Count() > 0)
            {
                ModelState.AddModelError("", "Patient with same name and contact no already exists in the system");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var currentUserId = User.Identity.GetUserId();
                    long customerId = 1;
                    long branchId = 1;
                    if (currentUserId != null)
                    {
                        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                        customerId = manager.FindById(currentUserId).HMSEmpID;
                        branchId = manager.FindById(currentUserId).BranchID;
                        patientDetail.PatientDetails.CreatedBy = Convert.ToInt32(customerId);
                    }

                    DateTime today = DateTime.Today;
                    //int age = today.Year - patientDetail.PatientDetails.Age;
                    patientDetail.PatientDetails.DOB = today.AddYears(- (patientDetail.PatientDetails.Age));
                    //if (patientDetail.PatientDetails.DOB.Date > today.AddYears(-age)) age--;

                    //patientDetail.PatientDetails.Age = age;
                    patientDetail.PatientDetails.CreatedOn = DateTime.Now;
                    patientDetail.PatientDetails.DateOfRegistration = DateTime.Now;
                    db.PatientDetails.Add(patientDetail.PatientDetails);
                    db.SaveChanges();
                    patientDetail.Appointment.CreatedDate = DateTime.Now;
                    patientDetail.Appointment.CreatedBy = Convert.ToInt32(customerId);
                    //patientDetail.Appointment.BranchDetails_ID = Convert.ToInt32(branchId);
                    patientDetail.PatientDetails.Appointments.Add(patientDetail.Appointment);
                    db.SaveChanges();
                    return RedirectToAction("Index", "Appointments");
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }

            ViewBag.Specialization = new SelectList(db.Specializations.ToList(), "ID", "Name", patientDetail.Appointment.Specialization_ID);
            ViewBag.Doctors = new SelectList(db.Doctors.Include("EmployeeDetail").ToList(), "ID", "EmployeeDetail.FirstName", patientDetail.Appointment.Doctor_ID);
            ViewBag.City = new SelectList(db.Cities.ToList(), "ID", "Name", patientDetail.PatientDetails.City_ID);
            ViewBag.ShiftType = new SelectList(db.ShiftTypes, "ID", "Name", patientDetail.Appointment.ShiftType_ID);
            ViewBag.PatientType = new SelectList(db.PatientTypes, "ID", "Type", patientDetail.Appointment.PatientType_ID);
            ViewBag.Branch = new SelectList(db.BranchDetails, "ID", "Name", patientDetail.Appointment.BranchDetails_ID);
            return View(patientDetail);
        }
        public ActionResult Certificate(int courseId)
        {
            string user = User.Identity.GetUserId();
            var u = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var course = db.Courses.First(c => c.id == courseId);
            string path;

            if (System.IO.File.Exists(Server.MapPath("~/resources/cert/" +  u.FindById(user).FirstName + "_" + u.FindById(user).LastName + "/" + course.name +".jpeg")))
            {
                path = "/resources/cert/" + u.FindById(user).FirstName + "_" + u.FindById(user).LastName + "/" + course.name + ".jpeg";
                ViewBag.Path = path;
                return View();
            }

            try
            {
                Image im = Image.FromFile(Server.MapPath("~/resources/cert/MyCertificate.jpeg"));
                path = PrintInPicture(im, u.FindById(user).FirstName, u.FindById(user).LastName, course.name);
            }
            catch (Exception)
            {
                Image im = Image.FromFile(Server.MapPath("~/resources/cert/MyCertificate.jpeg"));
                im.Save(Server.MapPath("~/resources/cert/MyCertificate1.jpeg"), System.Drawing.Imaging.ImageFormat.Jpeg);
                im = Image.FromFile(Server.MapPath("~/resources/cert/MyCertificate1.jpeg"));
                path = PrintInPicture(im, u.FindById(user).FirstName, u.FindById(user).LastName, course.name);
            }

            ViewBag.Path = path;
            return View();
        }
Exemplo n.º 6
1
        //
        // GET: /Manage/Index
        public async Task<ActionResult> Index(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
                : message == ManageMessageId.Error ? "An error has occurred."
                : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
                : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
                : "";

            var userId = User.Identity.GetUserId();
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(userId);

            var model = new IndexViewModel
            {
                HasPassword = HasPassword(),
                IoTConnectionString = currentUser.IoTHubConnectionString,
                IoTHubEndpoint = currentUser.IoTHubEndpoint,
                PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
                TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
                Logins = await UserManager.GetLoginsAsync(userId),
                BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
            };
            return View(model);
        }
Exemplo n.º 7
1
        public void AddImage()
        {
            if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
            {
                var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];

                string fileName = GenerateFileName("Image") +"."+ pic.FileName.Split('.')[1];

                pic.SaveAs(Server.MapPath("/img/" + fileName));

                using (ApplicationDbContext db = new ApplicationDbContext())
                {
                    var store = new UserStore<ApplicationUser>(db);
                    var manager = new UserManager<ApplicationUser>(store);
                    var currentUser = manager.FindById(User.Identity.GetUserId());

                    //if the user already has an image
                    if(currentUser.userImgPath != "")
                    {
                        reloadImage(currentUser, fileName);
                    }
                    else
                        currentUser.userImgPath = fileName;

                    db.SaveChanges();
                    // manager.UpdateAsync(currentUser);
                    //store.Context.SaveChanges();
                    // FormsAuthentication.SignOut();
                   // Session.Abandon();
                   // Index();
                }

            }
        }
Exemplo n.º 8
0
        //
        // GET: /Manage/Index
        public async Task<ActionResult> Index(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
                : message == ManageMessageId.Error ? "An error has occurred."
                : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
                : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
                : "";

            var userId = User.Identity.GetUserId();
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(User.Identity.GetUserId());

            // lambda to extract photolist using currentUser as filter
            var photoList = Db.Photos.Where(x => x.UserId == userId).ToList();
            var model = new IndexViewModel
            {
                PhotoList = photoList,
                HasPassword = HasPassword(),
                PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
                TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
                Logins = await UserManager.GetLoginsAsync(userId),
                BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
            };

            ViewBag.User = currentUser;
            return View(model);
        }
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            // check if the UserInfo session is set.  otherwise set it from request context
            _sqlConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            if (requestContext.HttpContext.Request.IsAuthenticated)
            {
                _userInfo = new AspNetUserInfo();
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser user = userManager.FindById(requestContext.HttpContext.User.Identity.GetUserId());
                //_userInfo = user.AspNetUser;
                _userInfo.Id = new Guid(user.Id);
                _userInfo.FirstName = user.FirstName;
                _userInfo.LastName = user.LastName;
                _userInfo.Email = user.Email;
                _userInfo.CompanyName = user.CompanyName;
                _userInfo.CustomerKey = user.CustomerKey;

                //GET THE USER ROLE (customer, admin, planning officer)
                var userIdentity = (System.Security.Claims.ClaimsIdentity)requestContext.HttpContext.User.Identity;
                var claims = userIdentity.Claims;
                //var userClaimType = userIdentity.RoleClaimType;
                _userRole = claims.Where(c => c.Type == System.Security.Claims.ClaimTypes.Role).FirstOrDefault().Value;
            }
            base.Initialize(requestContext);
        }
Exemplo n.º 10
0
 public ActionResult FriendList()
 {
     var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     var currentUser = manager.FindById(User.Identity.GetUserId());
     int id = currentUser.UserInfo.Id;
     return PartialView(GetFriendsCtrl(id));
 }
Exemplo n.º 11
0
 public ActionResult Posts(string firstName)
 {
     var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     var currentUser = manager.FindById(User.Identity.GetUserId());
     int id = currentUser.UserInfo.Id;
     return PartialView(GetAllPosts(id, firstName));
 }
Exemplo n.º 12
0
        // GET: Schedules/Create
        public ActionResult Create(int? departmentId, int? groupId)
        {
            Department department = db.Departments.Find(departmentId);
            DepartmentGroup group = db.DepartmentGroups.Find(groupId);

            if(department == null && group == null)
            {
                return HttpNotFound();
            }

            if (User.Identity.IsAuthenticated)
            {
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
                var currentUser = userManager.FindById(User.Identity.GetUserId());
                if ((department != null && department.Bosses.Contains(currentUser)) || (group != null && group.Department.Bosses.Contains(currentUser)))
                {
                    //ViewBag.DepartmentId = new SelectList(db.Departments.ToList().Where(q=>q.Bosses.Contains(currentUser)).ToList(), "Id","Name",departmentId);
                    //ViewBag.GroupId = new SelectList(db.DepartmentGroups.ToList().Where(q=>q.Department.Bosses.Contains(currentUser)).ToList(), "Id","Name",groupId);
                    ViewBag.DepartmentId = new SelectList(db.Departments.ToList().Where(q => q.Bosses.Contains(currentUser)).ToList(), "Id", "Name", departmentId);
                    var groups = new SelectList(db.DepartmentGroups.ToList().Where(q => q.Department.Bosses.Contains(currentUser)).ToList(), "Id", "Name", groupId).ToList();
                    groups.Insert(0,new SelectListItem() { Value = "", Text = "All" });
                    ViewBag.GroupId = groups;
                    return View();
                }
                else
                {
                    return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
                }

            }
            else
            {
                return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
            }
        }
Exemplo n.º 13
0
        public ActionResult Create([Bind(Include = "Id,StartTime,EndTime,DepartmentId,GroupId")] Schedule schedule)
        {
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var currentUser = userManager.FindById(User.Identity.GetUserId());

            if (ModelState.IsValid && User.Identity.IsAuthenticated)
            {
                if (schedule.DepartmentId == 0 && schedule.GroupId == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                Department department = db.Departments.Find(schedule.DepartmentId) ?? db.DepartmentGroups.Find(schedule.GroupId).Department;
                if (department == null)
                {
                    return HttpNotFound();
                }
                if (department.Bosses.Contains(currentUser)) //Current logged in user must be boss for the department
                {
                    db.Schedules.Add(schedule);
                    db.SaveChanges();

                    return RedirectToAction("Index", "Schedules", new { departmentId = schedule.DepartmentId, groupId = schedule.GroupId });
                }
                else
                {
                    return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
                }
            }
            ViewBag.DepartmentId = new SelectList(db.Departments.ToList().Where(q => q.Bosses.Contains(currentUser)).ToList(), "Id", "Name", schedule.DepartmentId);
            var groups = new SelectList(db.DepartmentGroups.ToList().Where(q => q.Department.Bosses.Contains(currentUser)).ToList(), "Id", "Name", schedule.GroupId).ToList();
            groups.Insert(0,new SelectListItem(){ Value = "", Text = "All"});
            ViewBag.GroupId = groups;

            return View(schedule);
        }
Exemplo n.º 14
0
        public ActionResult ChangeCapacity([Bind(Include = "SpaceID,Name,capacity,used")] SpaceUpdateCapacityViewModel space)
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ProjectContext()));
            ApplicationUser currentUser = manager.FindById(User.Identity.GetUserId());

            if (ModelState.IsValid && (currentUser.role == GlobalRole.ADMIN || currentUser.role == GlobalRole.APPROVER))
            {
                Space fullSpace = db.Spaces.Find(space.SpaceID);
                fullSpace.capacity = space.capacity;
                fullSpace.used = space.used;

                ////////////////////////////////////////////
                ////////////////////////////////////////////
                ////Send Email to Principal Investigator////
                ////////////////////////////////////////////
                ////////////////////////////////////////////

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

                return RedirectToAction("Review", "Space", new {id = space.SpaceID });
            }

            return View();
        }
Exemplo n.º 15
0
        /********
         * Change Capacity (Admin and Approver ONLY).
         ********/
        public ActionResult ChangeCapacity(int? id)
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ProjectContext()));
            ApplicationUser currentUser = manager.FindById(User.Identity.GetUserId());

            // Permissions Check.
            if (currentUser.role != GlobalRole.ADMIN && currentUser.role != GlobalRole.APPROVER)
            {
                //return HttpNotFound();
                return Redirect("../../Dashboard");
            }

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Space space = db.Spaces.Find(id);

            if (space == null)
            {
                //return HttpNotFound();
                return Redirect("../../Dashboard");
            }

            SpaceUpdateCapacityViewModel svm = new SpaceUpdateCapacityViewModel();
            svm.Name = space.Name;
            svm.SpaceID = space.key;
            svm.capacity = space.capacity;
            svm.used = space.used;

            return View(svm);
        }
        public string submitCodePost(string title, string content, string type)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                CodePost tmp = new CodePost();

                content = HttpUtility.JavaScriptStringEncode(content);

                var store = new UserStore<ApplicationUser>(db);
                var userManager = new UserManager<ApplicationUser>(store);
                ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;
                var currentUser = userManager.FindById(User.Identity.GetUserId());

                if (title != null && content != null && type != null)
                {
                    tmp.title = title;
                    tmp.content = content;
                    tmp.votes = 0;
                    tmp.user_id = user.Id;
                    tmp.userName = user.user;
                    tmp.userImgPath = currentUser.userImgPath;
                }

                bool result = updateHashTags(tmp);

                if(result == false)
                    db.posts.Add(tmp);

                db.SaveChanges();

                return "success";
            }
        }
Exemplo n.º 17
0
 public ActionResult GetInfoData()
 {
     var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     var currentUser = manager.FindById(User.Identity.GetUserId());
     int id = currentUser.UserInfo.Id;
     return Json(GetPersonalDetails(id), JsonRequestBehavior.AllowGet);
 }
Exemplo n.º 18
0
        public ActionResult Create([Bind(Include = "Id,Title,Content,CompanyId,IsPublic")] NewsItem newsItem)
        {
            if (ModelState.IsValid && User.Identity.IsAuthenticated)
            {
                    if (newsItem.CompanyId == 0)
                    {
                        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                    }
                    Company company = db.Companies.Find(newsItem.CompanyId);
                    if (company == null)
                    {
                        return HttpNotFound();
                    }

                    var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
                    var currentUser = userManager.FindById(User.Identity.GetUserId());
                    if (company.Bosses.Contains(currentUser) ||  company.Admins.Contains(currentUser))
                    {
                        newsItem.Created = DateTime.Now;
                        newsItem.Creator = currentUser;
                        db.NewsItems.Add(newsItem);
                        db.SaveChanges();

                        return RedirectToAction("Details", "Companies", new { id = newsItem.CompanyId });
                    }
                    else
                    {
                        return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
                    }

            }

            ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name", newsItem.CompanyId);
            return View(newsItem);
        }
        public ActionResult FileUpload(HttpPostedFileBase file)
        {
            if (file != null)
            {
                using (var dbContext = new YATContext())
                {
                    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                    var currentUser = manager.FindById(User.Identity.GetUserId());
                    var YATUser = dbContext.User.Where(p => p.Id.Equals(currentUser.Id)).FirstOrDefault();

                    string picName = System.IO.Path.GetFileName(file.FileName);
                    String photo = YATUser.Id + Path.GetExtension(picName);
                    file.SaveAs(Server.MapPath("~/Pics/" + photo));

                    YATUser.Photo = photo;
                    dbContext.SaveChanges();
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    file.InputStream.CopyTo(ms);
                    byte[] array = ms.GetBuffer();
                }

            }
            return RedirectToAction("UserSettings", "UserProfile");
        }
        //[HttpPost, ActionName("Approve")]
        //[ValidateAntiForgeryToken]
        public ActionResult Approve(int id)
        {
            IncreaseSpaceRequest incspacerequest = db.IncreaseSpaceRequests.Find(id);
            Space space = db.Spaces.Find(incspacerequest.SpaceID);

            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ProjectContext()));
            ApplicationUser currentUser = manager.FindById(User.Identity.GetUserId());
            if (currentUser.role != GlobalRole.REGULAR)
            {
                if(((Int64)space.capacity + (Int64)incspacerequest.increase) > int.MaxValue)
                {
                    space.capacity = int.MaxValue;
                }
                else
                {
                    space.capacity += incspacerequest.increase;
                }

                db.IncreaseSpaceRequests.Remove(incspacerequest);
                db.SaveChanges();

                ///////////////////////////////
                ///////////////////////////////
                ////Send Email to Requester////
                ///////////////////////////////
                ///////////////////////////////

            }

            return RedirectToAction("../Dashboard");
        }
Exemplo n.º 21
0
 public ActionResult ConfirmEmail(string userID, string code)
 {
     var userStore = new UserStore<IdentityUser>();
     UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
     var user = manager.FindById(userID);
     CreateTokenProvider(manager, EMAIL_CONFIRMATION);
     try
     {
         IdentityResult result = manager.ConfirmEmail(userID, code);
         if (result.Succeeded)
         {
             TempData["ConfirmationResponse"] = "You have successfully registered for an account. Please verify your account by clicking on the link sent to you in your e-mail.";
             return RedirectToAction("Login");
         }
         else
         {
             TempData["ConfirmationResponseError"] = "Your validation attempt has failed. We may be experiencing system problems. Please try again later.";
             return RedirectToAction("Login");
         }
     }
     catch
     {
         TempData["ConfirmationResponseError"] = "Your validation attempt has failed. We may be experiencing system problems. Please try again later.";
         return RedirectToAction("Login");
     }
 }
Exemplo n.º 22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

            SqlDataSource1.SelectParameters["UserName"].DefaultValue = currentUser.FullName;
        }
        public ActionResult Games()
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(User.Identity.GetUserId());

            return View(currentUser.FavoriteTeams);
        }
Exemplo n.º 24
0
        public ActionResult Dashboard()
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ProjectContext()));
            ApplicationUser currentUser = manager.FindById(User.Identity.GetUserId());

            if (currentUser == null)
            {
                return Redirect("/");
            }

            ViewBag.UserRole = currentUser.role;

            if(currentUser.role != GlobalRole.REGULAR)
            {
                ViewBag.NewSpaceRequests = db.NewSpaceRequests.ToList<NewSpaceRequest>();
                ViewBag.IncreaseSpaceRequests = db.IncreaseSpaceRequests.ToList<IncreaseSpaceRequest>();
                ViewBag.Spaces = db.Spaces.ToList<Space>();
            }
            else
            {
                //change this to only show the right things
                ViewBag.NewSpaceRequests = db.NewSpaceRequests.ToList<NewSpaceRequest>().FindAll(nsr => nsr.requester_key.Equals(currentUser.Id));
                ViewBag.IncreaseSpaceRequests = db.IncreaseSpaceRequests.ToList<IncreaseSpaceRequest>().FindAll(isr => isr.requester_key.Equals(currentUser.Id));
                ViewBag.UserSpaces = db.UserSpaces.ToList<UserSpace>().FindAll(us => us.user.UserName.Equals(currentUser.UserName));
            }
            return View();
        }
        public ActionResult Create(ServicePaymentViewModel model)
        {
            if (ModelState.IsValid)
            {
                var currentUserId = User.Identity.GetUserId();
                long customerId = 1;

                if (currentUserId != null)
                {
                    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                    customerId = manager.FindById(currentUserId).HMSEmpID;
                }

                foreach(ServicePayment item in model.ServicePaymentList)
                {
                    item.CreatedDate = DateTime.Now;
                    item.UpdatedDate = DateTime.Now;
                    item.CreatedBy = Convert.ToInt32(customerId);
                    item.UpdatedBy = Convert.ToInt32(customerId);
                    db.ServicePayments.Add(item);
                }

                db.SaveChanges();
                return RedirectToAction("Index", "ServicePayments");
            }

            ViewBag.ServicePayment_Doctor_ID = new SelectList(db.Doctors, "ID", "OtherDetails", model.ServicePayment.Doctor_ID);
            //ViewBag.PatientStatus_ID = new SelectList(db.PatientStatus, "ID", "ID", servicePayment.PatientStatus_ID);
            ViewBag.ServicePayment_Service_ID = new SelectList(db.Services, "ID", "Name", model.ServicePayment.Service_ID);
            ViewBag.ServicePayment_ServiceSubCategory_ID = new SelectList(db.ServiceSubCategories, "ID", "Name", model.ServicePayment.ServiceSubCategory_ID);
            ViewBag.ServicePayment_PaymentModeID = new SelectList(db.PaymentModes, "ID", "Mode", model.ServicePayment.PaymentModeID);
            return View(model);
        }
Exemplo n.º 26
0
        public ActionResult Index()
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

            if (User.Identity.IsAuthenticated) {

                var currentUser = manager.FindById(User.Identity.GetUserId());

                //ViewBag.TeamName = currentUser.UserInfo.TeamName;
                //ViewBag.UserId = currentUser.UserInfo.Id;
                ViewBag.UserName = currentUser.UserName;
                ViewBag.TeamName = currentUser.TeamName;

                ViewBag.SiteRoot = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));

                //var request = HttpContext.Current.Request;

                //int resultId = (from r in db.Results
                //                where r.User.Id == currentUser.Id
                //                select r.Id).First();
                //ViewBag.ResultId = resultId;
            }

            return View();
        }
Exemplo n.º 27
0
        public List<EmployeeViewModel> CreateEmployeeRange(IEnumerable<EmployeeWFM> inputList)
        {
            List<EmployeeViewModel> viewEmployees = new List<EmployeeViewModel>();
            ApplicationUser user = null;
            EmployeeViewModel employeeView = null;

            using (UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
            {
                foreach (var inputEmployee in inputList)
                {
                    employeeView = DataMapperView.DoMapping<EmployeeWFM, EmployeeViewModel>(inputEmployee);
                    if (employeeView != null)
                    {
                        if (!String.IsNullOrEmpty(employeeView.IdentityId))
                        {
                            user = userManager.FindById(employeeView.IdentityId);
                            if (user != null)
                            {
                                employeeView.IdentityFirstName = user.FirstName;
                                employeeView.IdentityLastName = user.LastName;
                            }
                        }
                        viewEmployees.Add(employeeView);
                    }
                }
            }

            return viewEmployees;
        }
Exemplo n.º 28
0
        private async Task<string> ProcessPayment(CourseRegistrationModel model, int id)
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(User.Identity.GetUserId());
            string userEmail = currentUser.Email;
            return await Task.Run(() =>
            {
                Course course = db.Courses.Find(id);
                var myCharge = new StripeChargeCreateOptions
                {
                    Amount = (int)(course.Course_Cost * model.NumberOfParticipants * 100),
                    Currency = "usd",
                    Description = "Description for test charge",
                    ReceiptEmail = userEmail,
                    Source = new StripeSourceOptions
                    {
                        TokenId = model.Token
                    }
                };

                var chargeService = new StripeChargeService("sk_test_yPi2XADkAP3wiS1i6tkjErxZ");
                var stripeCharge = chargeService.Create(myCharge);

                return stripeCharge.Id;
            });
        }
 public ActionResult Read(int? id)
 {
     if (id == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     var currentUser = manager.FindById(User.Identity.GetUserId());
     User user;
     using (var dbContext = new YATContext())
     {
         user = dbContext.User.Where(p => p.Id.Contains(currentUser.Id)).FirstOrDefault();
     }
     string userid = user.Id;
     Message message = db.Messages.Find(id);
     Messaging msging = new Messaging();
     var messages = msging.getConversation(message.To.Id, message.From.Id).ToList();
     foreach (Message mess in messages)
     {
         if (mess.ToId.Equals(userid)) 
         { 
             msging.read(mess.To.Id, mess.Id);
         }
     }
     if (message == null)
     {
         return HttpNotFound();
     }
     return View(messages);
 }
Exemplo n.º 30
0
        public async Task<ActionResult> ImportLinkedIn()
        {
            var userManger = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var user = userManger.FindById(this.User.Identity.GetUserId());
            var claim = user.Claims.SingleOrDefault(m => m.ClaimType == "LinkedIn_AccessToken");

            if(claim == null)
            {
                // Redirect to connect LinkedIn
                // Drop a session nugget to get us back here
                Session["LinkLoginRedirect"] = "/Profile/ImportLinkedIn";
                return new Resume.Controllers.AccountController.ChallengeResult("LinkedIn", Url.Action("LinkLoginCallback", "Account"), User.Identity.GetUserId());
            }

            var client = new LinkedInApiClient(HttpContext.GetOwinContext().Request, claim.ClaimValue);
            var profileApi = new LinkedInProfileApi(client);
            var liProfile = await profileApi.GetBasicProfileAsync();

            // Convert the LinkedIn api object into something eaiser to bind to the view
            var importVM = new ImportLinkedInViewModel();
            importVM.FirstName = liProfile.FirstName;
            importVM.LastName = liProfile.LastName;
            importVM.Summary = liProfile.Summary;
            importVM.Positions = liProfile.Positions.Select(p => new Position()
            {
                Company = p.Company.Name,
                StartDate = new DateTime(p.StartDate.Year ?? DateTime.Now.Year, p.StartDate.Month ?? 1, p.StartDate.Day ?? 1),
                EndDate = p.EndDate == null ? (DateTime?)null : new DateTime(p.StartDate.Year ?? DateTime.Now.Year, p.StartDate.Month ?? 1, p.StartDate.Day ?? 1)
            }).ToList();

            return View(importVM);
        }
Exemplo n.º 31
0
    public void RemoveLogin(string loginProvider, string providerKey)
    {
        UserManager manager = new UserManager();
        var         result  = manager.RemoveLogin(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
        string      msg     = String.Empty;

        if (result.Succeeded)
        {
            var user = manager.FindById(User.Identity.GetUserId());
            IdentityHelper.SignIn(manager, user, isPersistent: false);
            msg = "?m=RemoveLoginSuccess";
        }
        Response.Redirect("~/Account/Manage" + msg);
    }
Exemplo n.º 32
0
        public ActionResult PatientApprovals()
        {
            ViewBag.CurrentPage = "PatientApprovals";
            var userId = User.Identity.GetUserId <int>();

            //
            if (UserManager.IsInRole(userId, "GlobalAdmin"))
            {
                var user = UserManager.FindById(userId);
                return(View(user));
            }

            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 33
0
        public ActionResult Deliveries()
        {
            ViewBag.CurrentPage = "Deliveries";
            var userId = User.Identity.GetUserId <int>();

            //
            if (UserManager.IsInRole(userId, "GlobalAdmin") || UserManager.IsInRole(userId, "DispensaryAdmin"))
            {
                var user = UserManager.FindById(userId);
                return(View(user));
            }

            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 34
0
        //
        // GET: /Manage/Index
        public async Task <ActionResult> Index(ManageMessageId?message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
                : message == ManageMessageId.Error ? "An error has occurred."
                : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
                : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
                : "";

            var userId = User.Identity.GetUserId();

            var manager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));

            var currentUser = manager.FindById(User.Identity.GetUserId());

            db = new ApplicationDbContext();
            var article = (from a in db.Articles select a).Where(a => a.UserID == currentUser.Id);

            ViewBag.Count = article.Count();

            var model = new IndexViewModel
            {
                FirstName         = currentUser.FirstName,
                LastName          = currentUser.LastName,
                HasPassword       = HasPassword(),
                PhoneNumber       = await UserManager.GetPhoneNumberAsync(userId),
                TwoFactor         = await UserManager.GetTwoFactorEnabledAsync(userId),
                Logins            = await UserManager.GetLoginsAsync(userId),
                BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId),
            };

            ViewBag.vCount = GetViewsCountByUser(User.Identity.GetUserId());
            ViewBag.cCount = GetCommentsCountByUser(User.Identity.GetUserId());
            var art = (from a in db.Articles
                       where a.UserID == userId && a.isAprove == false
                       orderby a.DateCreate
                       select a);

            ViewBag.Articles = art;
            var abu = (from a in db.Articles
                       where a.UserID == userId && a.isAprove == true
                       orderby a.DateCreate
                       select a);

            ViewBag.ArticlesByUser = abu;
            return(View(model));
        }
Exemplo n.º 35
0
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            var user = UserManager.FindById(id);

            if (user == null)
            {
                return(HttpNotFound());
            }
            GetUserRoles(user);
            return(View(user));
        }
Exemplo n.º 36
0
        //// GET: /Account/EditUserSettings
        //public ActionResult EditUserSettings()
        //{
        //    var manager = new UserManager<SimpleCMS.Models.ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore<SimpleCMS.Models.ApplicationUser>(new SimpleCMS.Models.ApplicationDbContext()));
        //    var user = manager.FindById(User.Identity.GetUserId());
        //    //var user = GetUser();
        //    if (user.UserSettings == null)
        //    {
        //        user.UserSettings = new UserSettings()
        //        {
        //            // Only inteded as a demo
        //        };
        //    }
        //    // TODO: Return view
        //    return new EmptyResult();
        //}

        //// POST: /Account/EditUserSettings
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public async Task<ActionResult> EditUserSettings([Bind(Include = "")] ApplicationUserSettingsViewModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        //        var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
        //        //var user = GetUser();
        //        if (user != null)
        //        {
        //            if (user.UserSettings == null)
        //            {
        //                user.UserSettings = new UserSettings();
        //            }
        //            //TODO: Update properties from viewmodel
        //            await UserManager.UpdateAsync(user);
        //        }
        //        return View(model);
        //    }
        //    else
        //    {
        //        return View(model);
        //    }
        //}

        // GET: /Account/EditBasicInfo
        public ActionResult EditBasicInfo()
        {
            var manager = new UserManager <SimpleCMS.Models.ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <SimpleCMS.Models.ApplicationUser>(new SimpleCMS.Models.ApplicationDbContext()));
            var user    = manager.FindById(User.Identity.GetUserId());

            return(View(new ExternalLoginConfirmationViewModel()
            {
                Email = user.Email,
                Birthday = user.Birthday,
                HomeTown = user.HomeTown,
                PhoneNumber = user.PhoneNumber,
                UserIdCode = user.UserIdCode,
                TwoFactorEnabled = user.TwoFactorEnabled
            }));
        }
Exemplo n.º 37
0
        public ActionResult DeleteOneOrder(int ID)
        {
            var model = db.GetBookingByID(ID).FirstOrDefault();

            if (model == null)
            {
                return(HttpNotFound());
            }
            model.BookedRoomNumber = db.GetRoomById(model.BookedRoomID).FirstOrDefault().RoomNumber;
            using (var um = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()))) {
                model.BookedUserName = um.FindById(model.BookedUserID).UserName;
            }

            return(View(model));
        }
Exemplo n.º 38
0
        // GET: User/Delete/5
        public async Task <ActionResult> Delete(string id)
        {
            var user      = UserManager.FindById(id);
            var isSuccess = RepositoryProvider.Get <SPRepository>().DeleteUserById(id);

            if (isSuccess)
            {
                var azureStorageHelper = new AzureStorageHelper(ConfigHelper.AzureStorageConnectionString);
                if (!string.IsNullOrEmpty(user.PhotoPath))
                {
                    await azureStorageHelper.DeleteFile(user.PhotoPath, AzureStorageHelper.FileUsage.UserPhotos);
                }
            }
            return(Redirect(Request.UrlReferrer == null ? "/User" : Request.UrlReferrer.AbsoluteUri));
        }
Exemplo n.º 39
0
        public IHttpActionResult DeleteUser(long id)
        {
            _messageService.DeleteAllByUserId(id);
            var user = UserManager.FindById(id);

            if (user != null)
            {
                UserManager.Delete(user);
                return(Ok());
            }

            HttpCode(HttpStatusCode.NotFound);
            HttpMessage("User not found");
            return(Ok());
        }
Exemplo n.º 40
0
        // GET: ClientDetails/Create
        public ActionResult Create()
        {
            var userId = User.Identity.GetUserId();
            var user   = UserManager.FindById(userId);

            ClientDetail ng = new ClientDetail()
            {
                TrxnDate = DateTime.Today,
                Branch   = user.CompanyToken.Branch,
                Email    = user.Email,
                ClientNo = RandomString(10),
            };

            return(View(ng));
        }
Exemplo n.º 41
0
        private void makeEdit()
        {
            ApplicationUser user = getUser();

            if (user != null)
            {
                try
                {
                    using (ApplicationDbContext dbcontext = new ApplicationDbContext())
                    {
                        string UserID   = GridView1.SelectedRow.Cells[1].Text;
                        var    manager  = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(dbcontext));
                        var    editUser = manager.FindById(UserID);

                        if (editEmail_tb.Text != null && editEmail_tb.Text != string.Empty)
                        {
                            editUser.EmailConfirmed = false;
                            editUser.Email          = editEmail_tb.Text;
                        }
                        if (editpass_tb.Text != null && editpass_tb.Text != string.Empty)
                        {
                            PasswordHasher passwordHasher = new PasswordHasher();
                            editUser.PasswordHash = passwordHasher.HashPassword(editpass_tb.Text);
                        }
                        if (name_tb.Text != null && name_tb.Text != string.Empty)
                        {
                            editUser.Name = name_tb.Text;
                        }
                        if (surname_tb.Text != null && surname_tb.Text != string.Empty)
                        {
                            editUser.Surname = surname_tb.Text;
                        }

                        string[] userRoles = manager.GetRoles(UserID).ToArray();
                        manager.RemoveFromRoles(UserID, userRoles);
                        manager.AddToRole(UserID, roleDropListEdit.SelectedItem.Value);
                        editUser.Role = roleDropListEdit.SelectedItem.Value;

                        manager.Update(editUser);
                    }
                }
                catch (Exception ex)
                {
                    ErrorMessageEdit.Text = "Nepavyko pakeisti vartotojo duomenų";
                    Trace.Write("Error occurred while editing user: {0}", ex.ToString());
                }
            }
        }
Exemplo n.º 42
0
        public ActionResult Index()
        {
            ApplicationDbContext context = new ApplicationDbContext();
            var userAuthentication       = User.Identity.IsAuthenticated;

            if (!userAuthentication)
            {
                return(View());
            }

            try
            {
                var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
                var currentUser = UserManager.FindById(User.Identity.GetUserId());
                var role        = UserManager.GetRoles(User.Identity.GetUserId());

                if (!currentUser.PreviousLogIn)
                {
                    if (role[0].ToString() == RoleName.Doctor)
                    {
                        currentUser.PreviousLogIn = true;
                        context.SaveChanges();
                        return(RedirectToAction("Create", "Doctors"));
                    }
                    else
                    {
                        currentUser.PreviousLogIn = true;
                        context.SaveChanges();
                        return(RedirectToAction("Create", "Patients"));
                    }
                }
                else
                {
                    if (role[0].ToString() == RoleName.Doctor)
                    {
                        return(RedirectToAction("Index", "Doctors"));
                    }
                    else
                    {
                        return(RedirectToAction("Dashboard", "Patients"));
                    }
                }
            }
            catch
            {
                return(RedirectToAction("Login", "Account"));
            }
        }
Exemplo n.º 43
0
        public ActionResult ManageAccount()
        {
            var user       = UserManager.FindById(User.Identity.GetUserId());
            var prt        = db.Parents.Where(c => c.UserId == user.Id).SingleOrDefault();
            var collection = new ParentManageAccountViewModel
            {
                Parent          = db.Parents.Where(c => c.UserId == user.Id).SingleOrDefault(),
                NewPassword     = null,
                OldPassword     = prt.Password,
                ConfirmPassword = null,
                Parents         = db.Parents.ToList(),
                Departments     = db.Departments.ToList()
            };

            return(View(collection));
        }
Exemplo n.º 44
0
        public ActionResult Index()
        {
            var user       = UserManager.FindById(User.Identity.GetUserId());
            var parent     = db.Parents.Where(c => c.UserId == user.Id).SingleOrDefault();
            var Rel        = db.ParentStudentRelations.Where(c => c.ParentId == parent.ParentId).ToList();
            var collection = new CollectionOfAllViewModel
            {
                Rel     = Rel,
                Hostels = db.Hostels.ToList(),
                News    = db.News.ToList(),
                Notices = db.Notices.ToList()
            };

            return(View(collection));
            //return View();
        }
Exemplo n.º 45
0
        public ActionResult Roulette()
        {
            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));

            if (User.Identity.GetUserId() != null)
            {
                System.Web.HttpContext.Current.Session["numbers"] = null;   // clear the session from past
                var user = UserManager.FindById(User.Identity.GetUserId()); // get the current user
                ViewBag.UserMoney = user.Money;
                return(View());
            }
            else
            {
                return(RedirectToAction("Login", "Account"));
            }
        }
Exemplo n.º 46
0
        public async Task <IHttpActionResult> DeleteUser(string id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            IdentityResult result = await UserManager.DeleteAsync(UserManager.FindById(id));

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
Exemplo n.º 47
0
        public static async Task ReauthorizeUserAsync(string userId)
        {
            IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

            authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));

            var user     = userManager.FindById(userId);
            var identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            authenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = true
            }, identity);
        }
Exemplo n.º 48
0
        // GET: Admin/Edit/5
        public ActionResult Edit(string id)
        {
            var user = UserManager.FindById(id);

            return(View(new UserViewModel
            {
                Id = user.Id,
                UserName = user.UserName,
                Email = user.Email,
                FirstName = user.FirstName,
                LastName = user.LastName,
                EmailConfirmed = user.EmailConfirmed,
                PhoneNumber = user.PhoneNumber,
                PhoneNumberConfirmed = user.PhoneNumberConfirmed
            }));
        }
Exemplo n.º 49
0
 public ActionResult EvaluarIndicadorParaEmpresa(int idIndicador, string cuit, int periodo)
 {
     try
     {
         var              store                     = new UserStore <ApplicationUser>(new TpIntegradorDbContext());
         var              userManager               = new UserManager <ApplicationUser>(store);
         ApplicationUser  user                      = userManager.FindById(User.Identity.GetUserId());
         List <Indicador> indicadoresDelUsuario     = user.Indicadores;
         double           valorTrasAplicarIndicador = sv.EvaluarIndicadorParaEmpresa(idIndicador, cuit, periodo, indicadoresDelUsuario);
         return(Json(new { Success = true, Valor = valorTrasAplicarIndicador }));
     }
     catch (Exception e)
     {
         return(Json(new { Success = false, Error = "Error: verificar que haya operandos para el año seleccionado." }));
     }
 }
Exemplo n.º 50
0
        public IHttpActionResult PutUser(AppUser user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var olduser = UserManager.FindById(user.Id);
            var newUser = Mapper.Map(user, olduser);

            newUser.Gender   = CheckGender(user.Gender);
            newUser.PhotoUri = GetImageName(newUser.PhotoUri);
            UserManager.Update(newUser);

            return(Ok(newUser));
        }
Exemplo n.º 51
0
        //[Authorize(Roles = "canEdit")]
        public ActionResult Create([Bind(Include = "MessageID,MessageBox")] Message message)
        {
            UserManager <ApplicationUser> UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));
            var CurrentUser = UserManager.FindById(User.Identity.GetUserId());

            message.ApplicationUser = CurrentUser;

            if (ModelState.IsValid)
            {
                db.Messages.Add(message);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(message));
        }
Exemplo n.º 52
0
        public ActionResult EditProfile()
        {
            var currentUserId = User.Identity.GetUserId();

            var manager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));

            var currentUser = manager.FindById(User.Identity.GetUserId());

            //Get Users FullName from UserManager
            EditProfileViewModel editProfileViewModel = new EditProfileViewModel();

            editProfileViewModel.FirstName = currentUser.FirstName;
            editProfileViewModel.LastName  = currentUser.LastName;

            return(View(editProfileViewModel));
        }
Exemplo n.º 53
0
        public ActionResult DeleteOneUser(string Id)
        {
            using (var um = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()))) {
                var user = um.FindById(Id);


                var fu = new FormatedUser {
                    Id           = user.Id,
                    UserName     = user.UserName,
                    PasswordHash = user.PasswordHash,
                    Admin        = um.IsInRole(user.Id, "Admin")
                };

                return(View(fu));
            }
        }
Exemplo n.º 54
0
        public async Task <ActionResult> Edit(ManagerUserMode viewModel)
        {
            AppUser user = UserManager.FindById(viewModel.UserId);

            user.PayRollUser = viewModel.UserName;
            user.PhoneNumber = viewModel.Phone;
            var result = await UserManager.UpdateAsync(user);

            if (!result.Succeeded)
            {
                // Add all errors to the page so they can be used to display what went wrong
                AddErrors(result);
                return(View(viewModel));
            }
            return(RedirectToAction("Mlist"));
        }
 public ApplicationUser GetUser(string id)
 {
     using (var db = new DataContext())
     {
         var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
         try
         {
             var user = UserManager.FindById(id);
             return user;
         }
         catch
         {
             return null;
         }
     };
 }
Exemplo n.º 56
0
        public IHttpActionResult Post(DTO_PRO_DeTai tbl_PRO_DeTai)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            ApplicationUser user   = UserManager.FindById(User.Identity.GetUserId());
            DTO_PRO_DeTai   result = BS_PRO_DeTai.save_PRO_DeTai(db, PartnerID, -1, user.StaffID, tbl_PRO_DeTai, Username);


            if (result != null)
            {
                return(CreatedAtRoute("get_PRO_DeTai", new { id = result.ID }, result));
            }
            return(Conflict());
        }
Exemplo n.º 57
0
        public ActionResult UnsafeDeletion(int groupID)
        {
            UserQuery              userQuery     = new UserQuery();
            List <User>            qryResult     = userQuery.GetUserByGroup(groupID); // Select all users in corresponding group
            List <ApplicationUser> userGroupList = new List <ApplicationUser>();

            // For each user with corresponding group ID
            foreach (var item in qryResult)
            {
                ApplicationUser identity_user = UserManager.FindById(item.UserID); // Get user from identity database
                userGroupList.Add(identity_user);
            }

            ViewData["UsersInGroup"] = userGroupList; // For View
            return(View());
        }
Exemplo n.º 58
0
        public ActionResult MyProfile()
        {
            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));

            if (User.Identity.GetUserId() != null)
            {
                var user = UserManager.FindById(User.Identity.GetUserId());

                ViewBag.role = user.Roles.SingleOrDefault().Role.Name;

                return(View(user));
            }
            else
            {
                return(RedirectToAction("Login", "Account"));
            }
        }
Exemplo n.º 59
0
        public ActionResult PharmacyIndex(int?id)
        {
            if (id != null)
            {
                POrder pOrder = db.POrders.Find(id);
                pOrder.Accept          = true;
                db.Entry(pOrder).State = EntityState.Modified;

                db.SaveChanges();
            }
            var manager     = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(User.Identity.GetUserId());

            var pOrders = db.POrders.Include(p => p.Pharmacy).Include(p => p.Prescript).Where(p => p.PharmacyId == currentUser.Pharmacist.PharmacyId);

            return(View(pOrders.ToList()));
        }
Exemplo n.º 60
0
        // GET: Neighborhood/Create
        public ActionResult Create()
        {
            var user    = UserManager.FindById(User.Identity.GetUserId());
            var UsrLang = user.Institution.Country.Language;

            //****
            var cat_countries = from c in db.Countries
                                where c.Active == true
                                select c;

            if (user.Institution.AccessLevel == AccessLevel.Country || user.Institution.AccessLevel == AccessLevel.SelfOnly || user.Institution.AccessLevel == AccessLevel.Service)
            {
                if (user.Institution.AccessLevel == AccessLevel.Country)
                {
                    cat_countries = cat_countries.Where(s => s.ID == user.Institution.CountryID);
                }
                else if (user.Institution.AccessLevel == AccessLevel.SelfOnly || user.Institution.AccessLevel == AccessLevel.Service)
                {
                    cat_countries = cat_countries.Where(s => s.ID == user.Institution.CountryID);
                }
            }

            ViewBag.Countries = new SelectList(cat_countries, "ID", "Name");

            //****
            var areas = db.Areas.Include(a => a.Country);

            if (user.Institution.AccessLevel == AccessLevel.Country || user.Institution.AccessLevel == AccessLevel.SelfOnly || user.Institution.AccessLevel == AccessLevel.Service)
            {
                if (user.Institution.AccessLevel == AccessLevel.Country)
                {
                    areas = areas.Where(s => s.CountryID == user.Institution.CountryID)
                            .OrderBy(o => o.Country.Name).ThenBy(o => o.Name);
                }
                else if (user.Institution.AccessLevel == AccessLevel.SelfOnly || user.Institution.AccessLevel == AccessLevel.Service)
                {
                    areas = areas.Where(s => s.CountryID == user.Institution.CountryID)
                            .OrderBy(o => o.Country.Name).ThenBy(o => o.Name);
                }
            }

            ViewBag.Areas = new SelectList(areas, "ID", "Name");

            //****
            return(View());
        }