public ActionResult Registration(CommerceIdeaBank.Models.User user)
        {
            if (ModelState.IsValid)
            {
                using (var db = new MainDBEntities())
                {
                    var crypto    = new SimpleCrypto.PBKDF2();
                    var encrpPass = crypto.Compute(user.Password);
                    var sysUser   = db.Users.Create();

                    sysUser.Username     = user.Username;
                    sysUser.Email        = user.Email;
                    sysUser.Password     = encrpPass;
                    sysUser.PasswordSalt = crypto.Salt;
                    sysUser.UserRole     = 1;
                    sysUser.IsActive     = true;

                    db.Users.Add(sysUser);
                    db.SaveChanges();

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

            return(View(user));
        }
예제 #2
0
 //SUPPORT API
 public JsonResult GetListName()
 {
     using (MainDBEntities db = new MainDBEntities())
     {
         return(Json(db.LoaiHang.Select(p => p.LoaiHang_Name).ToList(), JsonRequestBehavior.AllowGet));
     }
 }
예제 #3
0
        public int HuyXacNhanChotDonHang(string id)
        {
            using (MainDBEntities db = new MainDBEntities())
            {
                db.Configuration.LazyLoadingEnabled   = false;
                db.Configuration.ProxyCreationEnabled = false;

                var listId = id.Split(',');

                foreach (var item in listId)
                {
                    //Cập nhật trạng thái Xác nhận cho chốt đơn hàng
                    var chotDonHang = db.ChotDonHang.Where(p => p.ChotDonHang_ID.ToString() == item).FirstOrDefault();
                    if (chotDonHang != null)
                    {
                        chotDonHang.TrangThaiXacNhanDonHang = "CHUAXACNHAN";
                        chotDonHang.ThoiGianXacNhanDonHang  = null;
                    }
                }

                try
                {
                    db.SaveChanges();
                    return(1);
                }
                catch (Exception)
                {
                    return(0);

                    throw;
                }
            }
        }
예제 #4
0
        public ActionResult RequestEdit(int?requestId)
        {
            using (MainDBEntities mainDB = new MainDBEntities())
            {
                var requstResult = mainDB.RequestTables.FirstOrDefault(a => a.RequestID == requestId);
                var viewModel    = new RequestEditViewModel(requstResult);
                viewModel.GetCompany(mainDB.ClientTables.FirstOrDefault(x => x.ClientID == requstResult.ClientID));
                viewModel.GetType(mainDB.TypeTables.FirstOrDefault(x => x.TypeID == requstResult.TypeID));
                viewModel.GetStatus(mainDB.StatusTables.FirstOrDefault(x => x.StatusID == requstResult.StatusID));
                viewModel.GetUser(mainDB.UserAccounts.FirstOrDefault(x => x.UserID == requstResult.UserID));
                var statuses = mainDB.StatusTables.ToArray();
                viewModel.GetStatuses(statuses);
                var detailsList = requstResult.RequestDetails.Select(x => new DetailsViewModel
                {
                    StageNumber = x.StageNumber,
                    StageDate   = x.StageDate.Value.ToShortDateString(),
                    StageDesc   = x.StageDesc,
                    StageTime   = x.StageTime,
                    Status      = statuses.FirstOrDefault(y => y.StatusID == x.StatusID).StatusName,
                    UserName    = mainDB.UserAccounts.FirstOrDefault(y => x.UserID == requstResult.UserID).UserName
                }).ToArray();
                viewModel.Details = detailsList;

                return(View(viewModel));
            }
        }
예제 #5
0
        public ActionResult Save(StatusTable statuss)
        {
            bool status = false;

            if (ModelState.IsValid)
            {
                using (MainDBEntities mainDB = new MainDBEntities())
                {
                    if (statuss.StatusID > 0)
                    {
                        //edycja
                        var s = mainDB.StatusTables.Where(a => a.StatusID == statuss.StatusID).FirstOrDefault();
                        if (s != null)
                        {
                            s.StatusName = statuss.StatusName;
                        }
                    }
                    else
                    {
                        //zapis
                        mainDB.StatusTables.Add(statuss);
                    }
                    mainDB.SaveChanges();
                    status = true;
                }
            }
            return(new JsonResult {
                Data = new { status = status }
            });
        }
        public bool RemoveAmbassFromSchool(int?selected_school_id)
        {
            //Input validation
            if (selected_school_id == null || selected_school_id < 0)
            {
                return(false);
            }

            //Remove ambassador from selected school
            using (var context = new MainDBEntities())
            {
                //Find project with id = project_id, store in temp_project
                School school = context.Schools.Find(selected_school_id);

                //Ensure there's a point to the update
                if (school.Username == null || school.Username == "")
                {
                    return(true);
                }

                //Ensure user is actually ambassador before assignment and that
                //user actually exists in database
                school.Username = null;

                //Verify that valid project was found
                context.Schools.Add(school);

                //Indicate modification and make changes persistent
                context.Entry(school).State = EntityState.Modified;
                context.SaveChanges();

                //Return true indicating successful project edit
                return(true);
            }
        }
예제 #7
0
        public ActionResult Save(ClientTable client)
        {
            bool status = false;

            if (ModelState.IsValid)
            {
                using (MainDBEntities mainDB = new MainDBEntities())
                {
                    if (client.ClientID > 0)
                    {
                        //edycja
                        var s = mainDB.ClientTables.Where(a => a.ClientID == client.ClientID).FirstOrDefault();
                        if (s != null)
                        {
                            s.Nip         = client.Nip;
                            s.CompanyName = client.CompanyName;
                            s.Address     = client.Address;
                            s.Phone       = client.Phone;
                            s.Email       = client.Email;
                        }
                    }
                    else
                    {
                        //zapis
                        mainDB.ClientTables.Add(client);
                    }
                    mainDB.SaveChanges();
                    status = true;
                }
            }
            return(new JsonResult {
                Data = new { status = status }
            });
        }
예제 #8
0
        public ActionResult DeleteSelected(String[] ids)
        {
            if (ids == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            Guid[] id = null;

            //getting the guid of the current user;
            String user = System.Web.HttpContext.Current.User.Identity.Name;
            Guid   currentGuid;

            using (var dc = new MainDBEntities())
            {
                currentGuid = dc.users.FirstOrDefault(u => u.email == user).userId;
            }

            //ViewBag.CurrentUserGuid = currentGuid.ToString();

            if (ids != null)
            {
                id = new Guid[ids.Length];
                int j = 0;
                foreach (String i in ids)
                {
                    Guid.TryParse(i, out id[j++]);
                }
            }

            foreach (Guid i in id)
            {
                if (i == currentGuid)
                {
                    //return JavaScript(alert('Hello this is an alert'));
                    //ViewBag.Message = "Mymessage";
                    return(Content("<script language='javascript' type='text/javascript'>alert('You Cant Delete Yourself');</script>"));
                    // ViewBag.DataExists = true;
                    // return RedirectToAction("List");
                }
            }


            if (id != null && id.Length > 0)
            {
                List <user> personInfo = new List <user>();
                using (var dc = new MainDBEntities())
                {
                    personInfo = dc.users.Where(u => id.Contains(u.userId)).ToList();
                    foreach (var i in personInfo)
                    {
                        dc.users.Remove(i);
                    }
                    dc.SaveChanges();
                }
            }

            return(RedirectToAction("List"));
        }
예제 #9
0
 //rejestracja get
 public ActionResult Register(int?id)
 {
     using (MainDBEntities db = new MainDBEntities())
     {
         var v = db.UserAccounts.Where(a => a.UserID == id).FirstOrDefault();
         return(View(v));
     }
 }
예제 #10
0
        public override string[] GetRolesForUser(string username)
        {
            MainDBEntities db = new MainDBEntities();
            string         s  = db.UserAccounts.Where(x => x.UserName == username).FirstOrDefault().Roles;

            string[] resultS = { s };
            return(resultS);
        }
예제 #11
0
 public ActionResult GetTypes()
 {
     using (MainDBEntities mainDB = new MainDBEntities())
     {
         var type = mainDB.TypeTables.OrderBy(a => a.TypeName).ToList();
         return(Json(new { data = type }, JsonRequestBehavior.AllowGet));
     }
 }
예제 #12
0
 public ActionResult Save(int id)
 {
     using (MainDBEntities mainDB = new MainDBEntities())
     {
         var v = mainDB.ClientTables.Where(a => a.ClientID == id).FirstOrDefault();
         return(View(v));
     }
 }
예제 #13
0
 public ActionResult GetStatus()
 {
     using (MainDBEntities mainDB = new MainDBEntities())
     {
         var status = mainDB.StatusTables.OrderBy(a => a.StatusName).ToList();
         return(Json(new { data = status }, JsonRequestBehavior.AllowGet));
     }
 }
예제 #14
0
 public ActionResult GetClients()
 {
     using (MainDBEntities mainDB = new MainDBEntities())
     {
         var clients = mainDB.ClientTables.OrderBy(a => a.CompanyName).ToList();
         return(Json(new { data = clients }, JsonRequestBehavior.AllowGet));
     }
 }
예제 #15
0
        public IList <News> GetLatestNews(int pageNumber, int recordsPerPage = 3)
        {
            MainDBEntities database    = new MainDBEntities();
            var            skipRecords = pageNumber * recordsPerPage;

            return(database.News
                   .OrderByDescending(x => x.ID)
                   .Skip(skipRecords)
                   .Take(recordsPerPage)
                   .ToList());
        }
예제 #16
0
        public JsonResult GetSoHieuChuaCapByDichVu(string id)
        {
            using (MainDBEntities db = new MainDBEntities())
            {
                db.Configuration.LazyLoadingEnabled   = false;
                db.Configuration.ProxyCreationEnabled = false;

                var model = db.KhoSo.Where(p => p.DichVu_ID == id && p.TrangThai.Contains("CHUACAP")).FirstOrDefault();

                return(Json(model, JsonRequestBehavior.AllowGet));
            }
        }
예제 #17
0
        public JsonResult getStatus()
        {
            List <StatusTable> status = new List <StatusTable>();

            using (MainDBEntities dc = new MainDBEntities())
            {
                status = dc.StatusTables.OrderBy(a => a.StatusName).ToList();
            }
            return(new JsonResult {
                Data = status, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
예제 #18
0
        public JsonResult getUser()
        {
            List <UserAccount> user = new List <UserAccount>();

            using (MainDBEntities dc = new MainDBEntities())
            {
                user = dc.UserAccounts.OrderBy(a => a.UserName).ToList();
            }
            return(new JsonResult {
                Data = user, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
예제 #19
0
        public JsonResult getClient()
        {
            List <ClientTable> client = new List <ClientTable>();

            using (MainDBEntities dc = new MainDBEntities())
            {
                client = dc.ClientTables.OrderBy(a => a.CompanyName).ToList();
            }
            return(new JsonResult {
                Data = client, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
예제 #20
0
        public JsonResult getType()
        {
            List <TypeTable> type = new List <TypeTable>();

            using (MainDBEntities dc = new MainDBEntities())
            {
                type = dc.TypeTables.OrderBy(a => a.TypeName).ToList();
            }
            return(new JsonResult {
                Data = type, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
예제 #21
0
        public JsonResult GetChiTietByPhieuChotForExport(string id)
        {
            using (MainDBEntities db = new MainDBEntities())
            {
                int idPhieuChot;
                if (int.TryParse(id, out idPhieuChot))
                {
                    var phieuchot         = db.ChotDonHang.Where(p => p.ChotDonHang_ID == idPhieuChot).FirstOrDefault();
                    var chitietPhieuChots = db.ChiTietChotDonHang.Where(p => p.ChotDonHang_ID == idPhieuChot).ToList();
                    if (chitietPhieuChots != null)
                    {
                        var khachhang = db.KhachHang.Where(p => p.KhachHang_ID == phieuchot.KhachHang_ID).FirstOrDefault();

                        List <AltChiTietPhieuChotExport> chitietExports = new List <AltChiTietPhieuChotExport>();
                        foreach (var item in chitietPhieuChots)
                        {
                            var donhang = db.DonHang.Where(p => p.SoHieu == item.SoHieu).FirstOrDefault();
                            if (donhang != null)
                            {
                                AltChiTietPhieuChotExport chitietExport = new AltChiTietPhieuChotExport();
                                chitietExport.SoHieu          = donhang.SoHieu;
                                chitietExport.TenNguoiNhan    = donhang.NguoiNhan;
                                chitietExport.DiaChiNguoiNhan = donhang.DiaChiNguoiNhan;
                                chitietExport.TinhPhat        = db.TinhThanhPho.Where(p => p.TinhThanhPho_ID == donhang.TinhThanhPho_ID).FirstOrDefault().TinhThanhPho_Name;
                                chitietExport.MaTinhPhat      = donhang.TinhThanhPho_ID;
                                chitietExport.SoDTNguoiNhan   = donhang.SoDienThoaiNguoiNhan;
                                chitietExport.SoTienCOD       = donhang.SoTienThuHo.ToString();
                                chitietExport.MaDonHang       = donhang.SoDienThoaiNguoiNhan;
                                chitietExport.MaSo            = null;
                                chitietExport.NoiDungHang     = donhang.LoaiHang_Name;
                                chitietExport.TrongLuong      = null;
                                chitietExport.ChieuDai        = null;
                                chitietExport.ChieuRong       = null;
                                chitietExport.ChieuCao        = null;
                                chitietExport.PhatDongKiem    = null;
                                chitietExport.VUN             = null;
                                chitietExport.VungSauVungXa   = null;
                                chitietExport.TenShop         = khachhang.KhachHang_Name;
                                chitietExport.DiaChiShop      = khachhang.DiaChi;
                                chitietExport.SoDienThoaiShop = khachhang.DienThoai;

                                chitietExports.Add(chitietExport);
                            }
                        }

                        return(Json(chitietExports, JsonRequestBehavior.AllowGet));
                    }
                }

                return(null);
            }
        }
예제 #22
0
        public static int Count(Guid productID)
        {
            using (MainDBEntities db = new MainDBEntities())
            {
                var Enter =
                    db.WareHouse.Where(w => w.TypeID == 1 && w.ProductID == productID).Select(s => s.Count).ToList();

                var Exit =
                    db.WareHouse.Where(w => w.TypeID == 2 && w.ProductID == productID).Select(s => s.Count).ToList();

                return(Enter.Sum() - Exit.Sum());
            }
        }
        public ActionResult Login(CommerceIdeaBank.Models.User user)
        {
            if (ModelState.IsValid)
            {
                if (IsValid(user.Username, user.Password))
                {
                    FormsAuthentication.SetAuthCookie(user.Username, false);

                    //Retrieve relevant user object ***
                    using (var context = new MainDBEntities())
                    {
                        User relevant_user = context.Users.Find(user.Username);

                        //Check to determine permissions of authenticated users
                        if (relevant_user.UserRole == 1 /* Contributor */)
                        {
                            return(RedirectToAction("Index", "ContributorHome"));
                        }
                        else if (relevant_user.UserRole == 2 /* Mentor */)
                        {
                            return(RedirectToAction("Index", "AmbassadorHome"));
                        }
                        else if (relevant_user.UserRole == 3 /* Ambassador */)
                        {
                            return(RedirectToAction("Index", "AmbassadorHome"));
                        }
                        else if (relevant_user.UserRole == 4 /* Admin */)
                        {
                            return(RedirectToAction("Index", "AdminHome"));
                        }
                        else
                        {
                            //Output message box ***
                            MessageBox.Show("Oh no! Something seems to have gone wrong while logging " +
                                            "you in! We apologize about any inconvenience. Please try logging in " +
                                            "again and notify us if the issue persists!");

                            //Route person to the default home page
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "Login Data is Incorrect.");
            }

            return(View(user));
        }
        public ActionResult Login(CommerceIdeaBank.Models.User user)
        {
            if (ModelState.IsValid)
            {
                if (IsValid(user.Username, user.Password))
                {
                    FormsAuthentication.SetAuthCookie(user.Username, false);

                    //Retrieve relevant user object ***
                    using (var context = new MainDBEntities())
                    {
                        User relevant_user = context.Users.Find(user.Username);

                        //Check to determine permissions of authenticated users
                        if (relevant_user.UserRole == 1 /* Contributor */)
                        {
                            return RedirectToAction("Index", "ContributorHome");
                        }
                        else if (relevant_user.UserRole == 2 /* Mentor */)
                        {
                            return RedirectToAction("Index", "AmbassadorHome");
                        }
                        else if (relevant_user.UserRole == 3 /* Ambassador */)
                        {
                            return RedirectToAction("Index", "AmbassadorHome");
                        }
                        else if (relevant_user.UserRole == 4 /* Admin */)
                        {
                            return RedirectToAction("Index", "AdminHome");
                        }
                        else
                        {
                            //Output message box ***
                            MessageBox.Show("Oh no! Something seems to have gone wrong while logging " +
                                "you in! We apologize about any inconvenience. Please try logging in " +
                                "again and notify us if the issue persists!");

                            //Route person to the default home page
                            return RedirectToAction("Index", "Home");
                        }
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "Login Data is Incorrect.");
            }

            return View(user);
        }
예제 #25
0
        public ActionResult RequestEditPOST(RequestEditViewModel dupa)
        {
            ActionResult actionResult;
            var          tmp = dupa;

            if (ModelState.IsValid)
            {
                using (MainDBEntities mainDB = new MainDBEntities())
                {
                    var requstResult = mainDB.RequestTables.FirstOrDefault(a => a.RequestID == dupa.RequestID);

                    if (requstResult != null)
                    {
                        requstResult.Title       = dupa.Title;
                        requstResult.RequestDate = dupa.RequestDate;
                        requstResult.StatusID    = dupa.StatusId;
                        requstResult.Description = dupa.Description;
                        requstResult.RequestTime = dupa.RequestTime;
                        requstResult.Solution    = dupa.Solution;
                    }

                    mainDB.SaveChanges();
                }

                actionResult = RedirectToAction("Index");
            }
            else
            {
                using (MainDBEntities mainDB = new MainDBEntities())
                {
                    var statuses = mainDB.StatusTables.ToArray();
                    dupa.GetStatuses(statuses);
                    var requstResult = mainDB.RequestTables.FirstOrDefault(a => a.RequestID == dupa.RequestID);
                    var detailsList  = requstResult.RequestDetails.Select(x => new DetailsViewModel
                    {
                        StageNumber = x.StageNumber,
                        StageDate   = x.StageDate.Value.ToShortDateString(),
                        StageDesc   = x.StageDesc,
                        StageTime   = x.StageTime,
                        Status      = statuses.FirstOrDefault(y => y.StatusID == x.StatusID).StatusName,
                        UserName    = mainDB.UserAccounts.FirstOrDefault(y => x.UserID == requstResult.UserID).UserName
                    }).ToArray();
                    dupa.Details = detailsList;
                }

                actionResult = View("RequestEdit", dupa);
            }

            return(actionResult);
        }
        public bool AdminUpdateProjectStatus(int project_id, string new_status)
        {
            //Perform input validation
            if (new_status == null || new_status == "")
            {
                return(false);
            }
            if ((new_status != ProjectStatus.ASSIGNED) &&
                (new_status != ProjectStatus.IN_PROGRESS) &&
                (new_status != ProjectStatus.INTERN) &&
                (new_status != ProjectStatus.PRODUCTION) &&
                (new_status != ProjectStatus.ARCHIVED))
            {
                return(false);
            }

            using (var context = new MainDBEntities())
            {
                //Access object checks
                if (this.GetType() == typeof(AdminAccess))
                {
                    ProjectAssignment current_project = new ProjectAssignment();

                    //Read in necessary object
                    current_project = context.ProjectAssignments.Find(project_id);

                    //Modify status
                    current_project.ProgressStatus = new_status;

                    //Indicate that that value has been modified
                    context.ProjectAssignments.Attach(current_project);
                    var entry = context.Entry(current_project);

                    //Indicate that IsArchived property has been modified (indicates to EF that property
                    //needs update
                    entry.Property(x => x.ProgressStatus).IsModified = true;

                    //Save update
                    context.SaveChanges();

                    //Indicate successful update
                    return(true);
                }
                else
                {
                    //Invalid access object
                    return(false);
                }
            }
        }
        //Func Desc:
        //    Input:
        //   Output:
        public bool AssignProjectToSchool(int?project_id, int?school_id)
        {
            if (project_id == null)
            {
                return(false);
            }
            if (school_id == null)
            {
                return(false);
            }
            if (school_id < 0)
            {
                return(false);
            }
            if (project_id < 0)
            {
                return(false);
            }

            using (var context = new MainDBEntities())
            {
                //Find project with id = project_id, store in temp_project
                Project temp_project = context.Projects.Find(project_id);

                //Verify that valid project was found
                if (temp_project == null)
                {
                    return(false);
                }

                //Create Project Assignment
                ProjectAssignment new_assignment = new ProjectAssignment();

                //Set starting assignment values
                new_assignment.ProgressStatus = ProjectStatus.ASSIGNED;
                new_assignment.ProjectID      = (int)project_id;
                new_assignment.SchoolID       = (int)school_id;
                new_assignment.DateAssigned   = DateTime.Now;

                //Save changes to the database
                context.ProjectAssignments.Add(new_assignment);

                //Save update
                context.SaveChanges();

                //Indicate successful assignment
                return(true);
            }
        }
예제 #28
0
        public JsonResult Save(RequestTable request /*RequestDetail rd*/)
        {
            bool status = false;

            DateTime dateOrg;
            var      isValidDate = DateTime.TryParseExact(request.RequestDateString, "mm-dd-yyyy", null, System.Globalization.DateTimeStyles.None, out dateOrg);

            if (isValidDate)
            {
                request.RequestDate = dateOrg;
            }

            if (ModelState.IsValid)
            {
                using (MainDBEntities mainDB = new MainDBEntities())
                {
                    //var isValidModel = TryUpdateModel(request);
                    if (request.RequestID > 0 /*|| request.StatusID == 1*/)
                    {
                        //edycja
                        var s = mainDB.RequestTables.Where(a => a.RequestID == request.RequestID).FirstOrDefault();
                        if (s != null)
                        {
                            s.RequestID   = request.RequestID;
                            s.RequestDate = request.RequestDate;
                            s.Title       = request.Title;
                            s.ClientID    = request.ClientID;
                            s.TypeID      = request.TypeID;
                            s.StatusID    = request.StatusID;
                            s.UserID      = request.UserID;
                            s.Description = request.Description;
                        }
                    }
                    else /*if(isValidModel)*/
                    {
                        //zapis
                        mainDB.RequestTables.Add(request);
                        //mainDB.RequestDetails.Add(rd);
                    }
                    mainDB.SaveChanges();
                    status = true;
                }
            }

            RedirectToAction("index", "Request");
            return(new JsonResult {
                Data = new { status = status }
            });
        }
예제 #29
0
 public ActionResult Delete(int id)
 {
     using (MainDBEntities mainDB = new MainDBEntities())
     {
         var del = mainDB.ClientTables.Where(a => a.ClientID == id).FirstOrDefault();
         if (del != null)
         {
             return(View(del));
         }
         else
         {
             return(HttpNotFound());
         }
     }
 }
예제 #30
0
        public int XoaChotDonHang(string id)
        {
            using (MainDBEntities db = new MainDBEntities())
            {
                db.Configuration.LazyLoadingEnabled   = false;
                db.Configuration.ProxyCreationEnabled = false;

                var listId = id.Split(',');

                foreach (var item in listId)
                {
                    //Xóa chốt đơn hàng
                    var chotDonHang = db.ChotDonHang.Where(p => p.ChotDonHang_ID.ToString() == item).FirstOrDefault();
                    if (chotDonHang != null)
                    {
                        db.ChotDonHang.Remove(chotDonHang);
                        //Xóa chi tiết chốt đơn
                        var chitiets = db.ChiTietChotDonHang.Where(p => p.ChotDonHang_ID == chotDonHang.ChotDonHang_ID).ToList();
                        if (chitiets != null)
                        {
                            //Cập nhật trạng thái đơn
                            foreach (var chitiet in chitiets)
                            {
                                var donhang = db.DonHang.Where(p => p.SoHieu == chitiet.SoHieu).FirstOrDefault();
                                if (donhang != null)
                                {
                                    donhang.TrangThai = "CHUACHOT";
                                }
                            }

                            db.ChiTietChotDonHang.RemoveRange(chitiets);
                        }
                    }
                }

                try
                {
                    db.SaveChanges();
                    return(1);
                }
                catch (Exception)
                {
                    return(0);

                    throw;
                }
            }
        }
        public bool UpdateUserRole(string username, int?new_role)
        {
            if (username == null || username == "")
            {
                return(false);
            }
            if ((new_role != UserRole.ADMIN) &&
                (new_role != UserRole.AMBASSADOR) &&
                (new_role != UserRole.CONTRIBUTOR))
            {
                return(false);
            }

            using (var context = new MainDBEntities())
            {
                User selected_user = context.Users.Find(username);

                if (selected_user == null)
                {
                    return(false);
                }

                //Modify status
                if (new_role != null)
                {
                    selected_user.UserRole = (int)new_role;
                }
                else
                {
                    return(false);
                }


                //Indicate that that value has been modified
                context.Users.Attach(selected_user);
                var entry = context.Entry(selected_user);

                //Indicate that IsArchived property has been modified (indicates to EF that property
                //needs update
                entry.Property(x => x.UserRole).IsModified = true;

                //Save update
                context.SaveChanges();

                //Indicate successful archive
                return(true);
            }
        }
        public bool AdminUpdateProjectStatus(int project_id, string new_status)
        {
            //Perform input validation
            if (new_status == null || new_status == "") { return false; }
            if( (new_status != ProjectStatus.ASSIGNED) &&
                (new_status != ProjectStatus.IN_PROGRESS) &&
                (new_status != ProjectStatus.INTERN) &&
                (new_status != ProjectStatus.PRODUCTION) &&
                (new_status != ProjectStatus.ARCHIVED) )
            {
                return false;
            }

            using (var context = new MainDBEntities())
            {
                //Access object checks
                if (this.GetType() == typeof(AdminAccess))
                {
                    ProjectAssignment current_project = new ProjectAssignment();

                    //Read in necessary object
                    current_project = context.ProjectAssignments.Find(project_id);

                    //Modify status
                    current_project.ProgressStatus = new_status;

                    //Indicate that that value has been modified
                    context.ProjectAssignments.Attach(current_project);
                    var entry = context.Entry(current_project);

                    //Indicate that IsArchived property has been modified (indicates to EF that property
                    //needs update
                    entry.Property(x => x.ProgressStatus).IsModified = true;

                    //Save update
                    context.SaveChanges();

                    //Indicate successful update
                    return true;
                }
                else
                {
                    //Invalid access object
                    return false;
                }
            }
        }
        public ActionResult Registration(MVCLoginInternet.Models.userModel user)
        {

            if (ModelState.IsValid)
            {
                try
                {
                    using (var db = new MainDBEntities())
                    {
                        var sysUser = db.users.Create();

                        sysUser.userId = Guid.NewGuid();
                        sysUser.email = user.email;
                        sysUser.password = user.password;
                        sysUser.userName = user.userName;
                        sysUser.firstName = user.firstName;
                        sysUser.lastName = user.lastName;
                        //sysUser.twitterName = user.twitterName;
                        // sysUser.tw
                        //   sysUser.twitterName = user.twitterName;

                        db.users.Add(sysUser);
                        db.SaveChanges();


                        FormsAuthentication.SetAuthCookie(user.email, false);

                        return RedirectToAction("List");
                        // return RedirectToAction("Index", "Home");
                    }

                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", "Add unique values to username and email, this user already exists");
                    return View();
                }
            }
            else
            {
                ModelState.AddModelError("", "Registration data is incorrect");
            }
              return View();
        }
        public bool AddAmbassToSchool(int? selected_school_id, string new_ambassador_username)
        {
            //Input validation
            if (selected_school_id == null || selected_school_id < 0) { return false; }
            if (new_ambassador_username == null || new_ambassador_username == "") { return false; }

            using (var context = new MainDBEntities())
            {
                //Find project with id = project_id, store in temp_project
                School school = context.Schools.Find(selected_school_id);

                User ambassador = context.Users.Find(new_ambassador_username);

                //Perform input validation
                if (school == null || ambassador == null) { return false; }

                //Ensure user is actually ambassador before assignment and that
                //user actually exists in database
                if (ambassador.UserRole != UserRole.AMBASSADOR)
                {
                    return false;
                }
                else
                {
                    school.Username = new_ambassador_username;

                    //Verify that valid project was found
                    context.Schools.Add(school);

                    //Indicate modification and make changes persistent
                    context.Entry(school).State = EntityState.Modified;
                    context.SaveChanges();

                    //Return true indicating successful project edit
                    return true;
                }
            }
        }
        public bool RemoveAmbassFromSchool(int? selected_school_id)
        {
            //Input validation
            if (selected_school_id == null || selected_school_id < 0) { return false; }

            //Remove ambassador from selected school
            using (var context = new MainDBEntities())
            {
                //Find project with id = project_id, store in temp_project
                School school = context.Schools.Find(selected_school_id);

                //Ensure there's a point to the update
                if (school.Username == null || school.Username == "") { return true; }

                //Ensure user is actually ambassador before assignment and that
                //user actually exists in database
                school.Username = null;

                //Verify that valid project was found
                context.Schools.Add(school);

                //Indicate modification and make changes persistent
                context.Entry(school).State = EntityState.Modified;
                context.SaveChanges();

                //Return true indicating successful project edit
                return true;
            }
        }
        public bool EditSchool(AdminSchoolViewModel vm_school)
        {
            if (vm_school == null) { return false; }

            try
            {
                using (var context = new MainDBEntities())
                {
                    ApplicationSpecificMapper mapper = new ApplicationSpecificMapper();

                    //Validate input
                    if (mapper == null) { return false; }

                    School school = (School)mapper.Map((AdminSchoolViewModel)vm_school, typeof(School));

                    //Validate input
                    if (school == null) { return false; }

                    //Create the project edit and populate necessary attributes
                    SchoolEdit edit = new SchoolEdit();

                    edit.SchoolID = school.SchoolID;
                    edit.Username = school.Username;
                    edit.SchoolName = school.SchoolName;
                    edit.Phone = (int)school.Phone;
                    edit.Email = school.Email;
                    edit.ContactEmail = school.ContactEmail;
                    edit.ContactName = school.ContactName;
                    edit.ContactPhone = school.ContactPhone;
                    edit.Department = school.Department;
                    edit.Class = school.Class;
                    edit.StreetNumber = school.StreetNumber;
                    edit.StreetName = school.StreetName;
                    edit.ZipCode = school.ZipCode;
                    edit.City = school.City;
                    edit.State = school.State;

                    edit.EditDate = DateTime.Now;

                    context.SchoolEdits.Add(edit);

                    //Indicate modification and make changes persistent
                    context.Entry(school).State = EntityState.Modified;
                    context.SaveChanges();

                    //Return true indicating successful project edit
                    return true;
                }
            }
            catch
            {
                //There was an error during school edit
                return false;
            }
        }
        //Func Desc: Used to delete project idea. Admin function.
        //    Input: The id of the project to delete
        //   Output: Bool indicating deletion status. T = successful deletion, F = failure to delete.
        public bool DeleteProject(int? project_id)
        {
            if (project_id == null) { return false; }

            try
            {
                Project domain_model = new Project();

                using (var context = new MainDBEntities())
                {
                    domain_model = context.Projects.Find(project_id);

                    IEnumerable<ProjectAssignment> dependent_projects =
                        context.ProjectAssignments.Where( x => x.ProjectID == project_id );

                    if (dependent_projects != null)
                    {
                        foreach (ProjectAssignment assignment in dependent_projects.ToList())
                        {
                            //Remove project
                            context.ProjectAssignments.Remove(assignment);
                        }

                        context.SaveChanges();
                    }

                    context.Projects.Remove(domain_model);

                    context.SaveChanges();

                    //Indicate delete success
                    return true;
                }
            }
            catch
            {
                //Indicate deletion failure
                return false;
            }
        }
        //Func Desc:
        //    Input:
        //   Output:
        public bool AssignProjectToSchool(int? project_id, int? school_id)
        {
            if (project_id == null) { return false; }
            if (school_id == null) { return false; }
            if (school_id < 0) { return false; }
            if (project_id < 0) { return false; }

            using (var context = new MainDBEntities())
            {
                //Find project with id = project_id, store in temp_project
                Project temp_project = context.Projects.Find(project_id);

                //Verify that valid project was found
                if (temp_project == null) { return false; }

                //Create Project Assignment
                ProjectAssignment new_assignment = new ProjectAssignment();

                //Set starting assignment values
                new_assignment.ProgressStatus = ProjectStatus.ASSIGNED;
                new_assignment.ProjectID = (int)project_id;
                new_assignment.SchoolID = (int)school_id;
                new_assignment.DateAssigned = DateTime.Now;

                //Save changes to the database
                context.ProjectAssignments.Add(new_assignment);

                //Save update
                context.SaveChanges();

                //Indicate successful assignment
                return true;

            }
        }
        //Func Desc: Used to mark the project with primary key id to archived.
        //    Input: Int representing id of project to archive.
        //   Output: A bool indicating whether update was successful or not. T = success, F = failure.
        public bool ArchiveProject(int? id)
        {
            if (id == null) { return false; }

            using (var context = new MainDBEntities())
            {
                //Retrieve project
                Project project = context.Projects.Find(id);

                //Mark the project as archived
                if (project != null)
                {
                    project.IsArchived = true;
                }
                else
                {
                    //Indicate error status
                    return false;
                }

                //Indicate that that value has been modified
                context.Projects.Attach(project);
                var entry = context.Entry(project);

                //Indicate that IsArchived property has been modified (indicates to EF that property
                //needs update
                entry.Property(x => x.IsArchived).IsModified = true;

                //Save update
                context.SaveChanges();

                //Indicate successful archive
                return true;

            }
        }
        public ActionResult Edit([Bind(Include = "userId,email,userName,password,firstName,lastName")] user userE)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (var dc = new MainDBEntities())
                    {
                        //user userEdit = dc.users.Find(userId);
                        dc.Entry(userE).State = EntityState.Modified;
                        dc.SaveChanges();
                        return RedirectToAction("List");
                    }
                }
                catch 
                {
                    ModelState.AddModelError("", "Add value to the password field");
                    return View();

                }
            }
            return View(userE);
        }
        public ActionResult DeleteSelected(String[] ids)
        {
            if (ids == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Guid[] id = null;

            //getting the guid of the current user;
            String user = System.Web.HttpContext.Current.User.Identity.Name;
            Guid currentGuid;
            using (var dc = new MainDBEntities())
            {

                currentGuid = dc.users.FirstOrDefault(u => u.email == user).userId;

            }

            //ViewBag.CurrentUserGuid = currentGuid.ToString();

            if (ids != null)
            {
                id = new Guid[ids.Length];
                int j = 0;
                foreach (String i in ids)
                {
                    Guid.TryParse(i, out id[j++]);
                }
            }

            foreach (Guid i in id)
            {
                if (i == currentGuid)
                {
                    //return JavaScript(alert('Hello this is an alert'));
                    //ViewBag.Message = "Mymessage";
                    return Content("<script language='javascript' type='text/javascript'>alert('You Cant Delete Yourself');</script>");
                   // ViewBag.DataExists = true;
                   // return RedirectToAction("List");

                }
            }


            if (id != null && id.Length > 0)
            {
                List<user> personInfo = new List<user>();
                using (var dc = new MainDBEntities())
                {
                    personInfo = dc.users.Where(u => id.Contains(u.userId)).ToList();
                    foreach (var i in personInfo)
                    {
                        dc.users.Remove(i);
                    }
                    dc.SaveChanges();
                }

            }

            return RedirectToAction("List");
        }
        public bool UpdateUserRole(string username, int? new_role)
        {
            if (username == null || username == "") { return false; }
            if ( (new_role != UserRole.ADMIN) &&
                 (new_role != UserRole.AMBASSADOR) &&
                 (new_role != UserRole.CONTRIBUTOR))
            {
                return false;
            }

            using (var context = new MainDBEntities())
            {
                User selected_user = context.Users.Find(username);

                if (selected_user == null) { return false; }

                //Modify status
                if (new_role != null)
                {
                    selected_user.UserRole = (int)new_role;
                }
                else
                {
                    return false;
                }

                //Indicate that that value has been modified
                context.Users.Attach(selected_user);
                var entry = context.Entry(selected_user);

                //Indicate that IsArchived property has been modified (indicates to EF that property
                //needs update
                entry.Property(x => x.UserRole).IsModified = true;

                //Save update
                context.SaveChanges();

                //Indicate successful archive
                return true;
            }
        }
        private bool isValid(String email, String password)
        {
            bool isvalid = false;

            using (var db = new MainDBEntities())
            {
                var user = db.users.FirstOrDefault(u => u.email == email);

                if (user != null)
                {
                    if (user.password == password)
                    {
                        isvalid = true;
                    }
                }
            }
            return isvalid;
        }
        // GET: /Movies/Edit/5
        public ActionResult Edit(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            String userLogged = System.Web.HttpContext.Current.User.Identity.Name;
            user userEdit = null;
            //Guid currentGuid;
            using (var dc = new MainDBEntities())
            {
                userEdit = dc.users.Find(id);
            }

            if (userEdit == null)
            {
                return HttpNotFound();
            } 

            return View(userEdit);
        }
        private bool IsValid(string username, string password)
        {
            var crypto = new SimpleCrypto.PBKDF2();
            bool isValid = false;

            using (var db = new MainDBEntities())
            {
                var user = db.Users.FirstOrDefault(x => x.Username == username);

                if (user != null)
                {
                    if (user.Password == crypto.Compute(password, user.PasswordSalt))
                    {
                        HttpContext.Session["currentUser"] = user.Username;
                        HttpContext.Session["userEmail"] = user.Email;
                        HttpContext.Session["userRole"] = user.UserRole;
                        isValid = true;
                    }
                }
            }

            return isValid;
        }
        //Func Desc: Used to submit school to database
        //    Input: A SchoolViewModel object instance
        //   Output: A bool indicating whether submission succeeded. T = success, F = failure
        public bool SubmitSchool(AdminSchoolViewModel new_school)
        {
            //Input checks
            if (new_school == null) { return false; }

            try
            {
                using (var context = new MainDBEntities())
                {
                    ApplicationSpecificMapper mapper = new ApplicationSpecificMapper();

                    //Create new project instance
                    School school = new School();

                    //Map the view model to the domain model
                    school = (School)mapper.Map(new_school, typeof(School));

                    //Submit the project to the db
                    context.Schools.Add(school);

                    //Save changes
                    context.SaveChanges();

                    //Indicate successful submission
                    return true;
                }
            }
            catch
            {
                //Return false indicating failure to submit project
                return false;
            }
        }
        //Func Desc: Used to return a project from its id.
        //    Input: Int representing id of project to locate.
        //   Output: An instance of the project that has the specified id, or null
        public bool EditProject(object vm_project)
        {
            //Input checks
            if (vm_project == null) { return false; }
            if ( (vm_project.GetType() != typeof(AdminProjectViewModel)) &&
                 (vm_project.GetType() != typeof(AmbassProjectViewModel)) &&
                 (vm_project.GetType() != typeof(ContributorProjectViewModel)))
            {
                //Invalid view model
                Debug.WriteLine("\n\n***** " +
                    "View model input into EditProject of ContributorAccess is invalid in type. " +
                    "ERROR IN: CommerceIdeaBank.DatabaseInterface.BusinessLogic.ContributorAccess EditProject()" +
                    "*****\n\n" );

                //Indicate failure in status
                return false;
            }

            using (var context = new MainDBEntities())
            {
                ApplicationSpecificMapper mapper = new ApplicationSpecificMapper();

                if (this.GetType() == typeof(AdminAccess))
                {
                    Project proj = (Project)mapper.Map((AdminProjectViewModel)vm_project, typeof(Project));

                    //Create the project edit and populate necessary attributes
                    ProjectEdit edit = new ProjectEdit();
                    edit.Username = proj.Username;
                    edit.ProjectID = proj.ProjectID;
                    edit.EditDate = DateTime.Now;
                    context.ProjectEdits.Add(edit);

                    //Indicate modification and make changes persistent
                    context.Entry(proj).State = EntityState.Modified;
                    context.SaveChanges();

                    //Return true indicating successful project edit
                    return true;

                }
                else if (this.GetType() == typeof(AmbassadorAccess))
                {
                    Project proj = (Project)mapper.Map((AmbassProjectViewModel)vm_project, typeof(Project));

                    //Create the project edit and populate necessary attributes
                    ProjectEdit edit = new ProjectEdit();
                    edit.Username = proj.Username;
                    edit.ProjectID = proj.ProjectID;
                    edit.EditDate = DateTime.Now;
                    context.ProjectEdits.Add(edit);

                    //Indicate modification and make changes persistent
                    context.Entry(proj).State = EntityState.Modified;
                    context.SaveChanges();

                    //Return true indicating successful project edit
                    return true;
                }
                else if (this.GetType() == typeof(ContributorAccess))
                {
                    Project proj = (Project)mapper.Map((ContributorProjectViewModel)vm_project, typeof(Project));

                    //Create the project edit and populate necessary attributes
                    ProjectEdit edit = new ProjectEdit();
                    edit.Username = proj.Username;
                    edit.ProjectID = proj.ProjectID;
                    edit.EditDate = DateTime.Now;
                    context.ProjectEdits.Add(edit);

                    //Indicate modification and make changes persistent
                    context.Entry(proj).State = EntityState.Modified;
                    context.SaveChanges();

                    //Return true indicating successful project edit
                    return true;
                }
                else
                {
                    //Access type not recognized

                    Debug.WriteLine("\n\n***** " +
                        "Access object type wasn't recognized during EditProject(). " +
                        "ERROR IN: CommerceIdeaBank.DatabaseInterface.BusinessLogic.ContributorAccess EditProject()" +
                        "*****\n\n");

                    //Indicate error status
                    return false;
                }

            }
        }
        public bool UpdateActiveStatusToProduction(int? active_project_id)
        {
            //Input checks
            if (active_project_id == null) { return false; }
            if (active_project_id < 0) { return false; }

            using (var context = new MainDBEntities())
            {
                //Access object checks
                if ((this.GetType() == typeof(AdminAccess)) ||
                     (this.GetType() == typeof(AmbassadorAccess)))
                {
                    ProjectAssignment active_project = new ProjectAssignment();

                    //Read in necessary object
                    active_project = context.ProjectAssignments.Find(active_project_id);

                    //Modify status
                    active_project.ProgressStatus = ProjectStatus.PRODUCTION;

                    //Indicate that that value has been modified
                    context.ProjectAssignments.Attach(active_project);
                    var entry = context.Entry(active_project);

                    //Indicate that IsArchived property has been modified (indicates to EF that property
                    //needs update
                    entry.Property(x => x.ProgressStatus).IsModified = true;

                    //Save update
                    context.SaveChanges();

                    //Indicate successful archive
                    return true;
                }
                else
                {
                    //Invalid access object
                    return false;
                }
            }
        }
        public ActionResult Registration(CommerceIdeaBank.Models.User user)
        {
            if (ModelState.IsValid)
            {
                using (var db = new MainDBEntities())
                {
                    var crypto = new SimpleCrypto.PBKDF2();
                    var encrpPass = crypto.Compute(user.Password);
                    var sysUser = db.Users.Create();

                    sysUser.Username = user.Username;
                    sysUser.Email = user.Email;
                    sysUser.Password = encrpPass;
                    sysUser.PasswordSalt = crypto.Salt;
                    sysUser.UserRole = 1;
                    sysUser.IsActive = true;

                    db.Users.Add(sysUser);
                    db.SaveChanges();

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

            return View(user);
        }
        //Func Desc: Used to submit project idea
        //    Input: A ProjectView instance
        //   Output: Bool indicating submission status. T = successful submission, F = failure to submit.
        public bool SubmitProject(object new_project)
        {
            //Input checks
            if (new_project == null) { return false; }

            using(var context = new MainDBEntities())
            {
                //Determine response based on access privilages
                if (this.GetType() == typeof(AdminAccess)) // IF ADMINISTRATOR
                {
                    try
                    {
                        //Cast object to admin project view model type
                        AdminProjectViewModel admin_project =
                            (AdminProjectViewModel)new_project;

                        //Create new project instance
                        Project proj = new Project();

                        //Transfer necessary values
                        proj.ProjectName = admin_project.ProjectName;
                        proj.ProjectDesc = admin_project.ProjectDesc;
                        proj.BusinessJustification = admin_project.BusinessJustification;
                        proj.Username = admin_project.Username;
                        proj.Status = IdeaStatus.SUBMITTED;
                        proj.IsArchived = false; //Not yet archived
                        proj.PostDate = DateTime.Now;
                        proj.AssignDate = null;
                        proj.FinishDate = null;

                        //Submit the project to the db
                        context.Projects.Add(proj);

                        //Save changes
                        context.SaveChanges();

                        //Indicate successful submission
                        return true;
                    }
                    catch
                    {
                        //Return false indicating failure to submit project
                        return false;
                    }
                }
                else if (this.GetType() == typeof(AmbassadorAccess))
                {
                    try
                    {
                        //Cast object to contributor project view model type
                        AmbassProjectViewModel contributor_project =
                            (AmbassProjectViewModel)new_project;

                        //Create new project instance
                        Project proj = new Project();

                        //Transfer necessary values
                        proj.ProjectName = contributor_project.ProjectName;
                        proj.ProjectDesc = contributor_project.ProjectDesc;
                        proj.BusinessJustification = contributor_project.BusinessJustification;
                        proj.Username = contributor_project.Username;
                        proj.Status = IdeaStatus.SUBMITTED;
                        proj.IsArchived = false; //Not yet archived
                        proj.PostDate = DateTime.Now;
                        proj.AssignDate = null;
                        proj.FinishDate = null;

                        //Submit the project to the db
                        context.Projects.Add(proj);

                        //Save changes
                        context.SaveChanges();

                        //Indicate successful submission
                        return true;
                    }
                    catch
                    {
                        //Return false indicating failure to submit project
                        return false;
                    }
                }
                else if (this.GetType() == typeof(ContributorAccess))
                {
                    try
                    {
                        //
                        ContributorProjectViewModel contributor_project = (ContributorProjectViewModel)new_project;

                        //Create new project instance
                        Project proj = new Project();

                        //Transfer necessary values
                        proj.ProjectName = contributor_project.ProjectName;
                        proj.ProjectDesc = contributor_project.ProjectDesc;
                        proj.BusinessJustification = contributor_project.BusinessJustification;
                        proj.Username = contributor_project.Username;
                        proj.Status = IdeaStatus.SUBMITTED;
                        proj.IsArchived = false; //Not yet archived
                        proj.PostDate = DateTime.Now;
                        proj.AssignDate = null;
                        proj.FinishDate = null;

                        //Submit the project to the db
                        context.Projects.Add(proj);

                        //Save changes
                        context.SaveChanges();

                        //Indicate successful submission
                        return true;
                    }
                    catch
                    {
                        //Return false indicating failure to submit project
                        return false;
                    }

                }
                else
                {
                    //Access object not recognized
                    Debug.WriteLine("\n\n***** " +
                        "Access object type wasn't recognized during SubmitProject(). " +
                        "ERROR IN: CommerceIdeaBank.DatabaseInterface.BusinessLogic.ContributorAccess SubmitProject()" +
                        "*****\n\n");

                    //Indicate error
                    return false;
                }
            }
        }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (MainDBEntities db = new MainDBEntities())
                {     
                    user userEx = db.users.FirstOrDefault(u => u.email == model.UserName);
                    // Check if user already exists

                    if (userEx != null)
                    {
                        userEx.userName = model.twitterName;
                        userEx.firstName = model.firstName;
                        userEx.lastName = model.lastName;
                        db.Entry(userEx).State = EntityState.Modified;
                        db.SaveChanges();
                        FormsAuthentication.SetAuthCookie(userEx.email, false);

                        return RedirectToAction("List");
                    }
                    if (userEx == null)
                    {
                        
                        /////////////////////////////////////////

                        try
                        {

                            using (var df = new MainDBEntities())
                            {
                                var sysUser = df.users.Create();

                                sysUser.userId = Guid.NewGuid();
                                sysUser.email = model.UserName;
                                sysUser.password = "******";
                                sysUser.userName = model.twitterName;
                                sysUser.firstName = model.firstName;
                                sysUser.lastName = model.lastName;

                                df.users.Add(sysUser);
                                df.SaveChanges();


                                //return RedirectToAction("List");
                                FormsAuthentication.SetAuthCookie(model.UserName, false);

                                return RedirectToAction("List");
                            }
                        }
                        catch
                        {
                            ModelState.AddModelError("UserName", "User name or twitter name already exists. Please enter a different user name or twitter name.");

                        }

                        /////////////////////////////////

                        // Insert name into the profile table
                       // db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                     //   db.SaveChanges();

                        //OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        //OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        //return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            // Rewrite request before it gets passed on to the OAuth Web Security classes
            GooglePlusClient.RewriteRequest();

            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            /////////////////////////////////////

            user userEdit = null;
            using (var dc = new MainDBEntities())
            {
                userEdit = dc.users.FirstOrDefault(u => u.email == result.UserName);
            }

            if (userEdit!=null)
            {

                // If the current user is logged in add the new account
               // OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, result.UserName);
                FormsAuthentication.SetAuthCookie(result.UserName, false);

                return RedirectToAction("List");
                //return RedirectToLocal(returnUrl);
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            }
        }
        public ActionResult List()
        {
            var user = System.Web.HttpContext.Current.User.Identity.Name;


            var finalResult = string.Empty;
            using (var dc = new MainDBEntities())
            {

                finalResult = dc.users.FirstOrDefault(u => u.email == user).userName;

            }

            ViewBag.MyURL = finalResult;

            Guid id;
            String userl = System.Web.HttpContext.Current.User.Identity.Name;
            using (var db = new MainDBEntities())
            {
                id = db.users.FirstOrDefault(u => u.email == userl).userId;
            }

            ViewBag.CurrentUserGuid=id.ToString(); 


            /////////////////////////////////////////


            List<user> person = new List<user>();

            using (var dc = new MainDBEntities())
            {
                person = dc.users.ToList();
            }

            return View(person.AsEnumerable());
        }