public ActionResult Settings(LocalPasswordModel model) { ViewBag.NotRead = HomeController.GetNotReadMessagesCount(); UsersContext db = new UsersContext(); List<UserData> TempUserList = new List<UserData>(); TempUserList = db.UsersData.ToList(); for (int i = 0; i < TempUserList.Count; i++) { if (TempUserList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { ViewBag.currentUser = TempUserList[i]; break; } } if (String.IsNullOrEmpty(model.ConfirmPassword) || String.IsNullOrEmpty(model.OldPassword) || String.IsNullOrEmpty(model.NewPassword)) { ModelState.AddModelError("PasswordMessage", "Ошибка! Заполните все поля!"); return View(model); } if(model.ConfirmPassword != model.NewPassword) { ModelState.AddModelError("PasswordMessage", "Ошибка! Пароли не совпадают"); return View(model); } bool changePasswordSucceeded; changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword); if (!changePasswordSucceeded) { ModelState.AddModelError("PasswordMessage", "Ошибка! Данные введены не корректно"); return View(model); } ModelState.AddModelError("PasswordMessage", "Пароль успешно изменен!"); return View(); }
// // GET: /Frends/ public ActionResult Frends() { ViewBag.NotRead = HomeController.GetNotReadMessagesCount(); List<FrendsModel> TempList = new List<FrendsModel>(); List<FrendsModel> FrendsList = new List<FrendsModel>(); UsersContext db = new UsersContext(); List<UserData> TempUserList = new List<UserData>(); List<UserData> ConfirmFrends = new List<UserData>(); List<UserData> NotConfirmFrends = new List<UserData>(); int CountOfNotConfirmFrends = 0; TempList = db.Frends.ToList(); // Получаем все заявки в друзья for (int i = 0; i < TempList.Count; i++) { if (TempList[i].UserA.UserProfile.UserId == WebSecurity.CurrentUserId || TempList[i].UserB.UserProfile.UserId == WebSecurity.CurrentUserId) FrendsList.Add(TempList[i]); } // Получаем модель текущего пользоваеля TempUserList = db.UsersData.ToList(); for (int i = 0; i < TempUserList.Count; i++) { if (TempUserList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { ViewBag.currentUser = TempUserList[i]; break; } } // Получаем потвержденные и не подтвержденные заявки в друзья for (int i = 0; i < FrendsList.Count; i++) { if (FrendsList[i].UserA.UserProfile.UserId == WebSecurity.CurrentUserId) { if (FrendsList[i].IsConfirm) ConfirmFrends.Add(FrendsList[i].UserB); else { } } else { if (FrendsList[i].IsConfirm) ConfirmFrends.Add(FrendsList[i].UserA); else NotConfirmFrends.Add(FrendsList[i].UserA); } } ViewBag.FrendsCount = ConfirmFrends.Count; ViewBag.Frends = ConfirmFrends; // Считаем количество заявок в друзья, которые отправили нам // Если есть входящие заявки - генерируем кнопку if (NotConfirmFrends.Count != 0) { ViewBag.NotConfirm = "<button style=\"margin-left:15px;\" type=\"button\" class=\"btn\" onclick=\"location.href='/Frends/RequestFrends'\">Заявки в друзья(" + NotConfirmFrends.Count + ") </button> <br //>"; } return View(ConfirmFrends); }
public ActionResult AddFrends(int id) { UsersContext db = new UsersContext(); List<UserData> TempList = new List<UserData>(); TempList = db.UsersData.ToList(); FrendsModel frend = new FrendsModel(); frend.IsConfirm = false; frend.Time = DateTime.Now; for (int i = 0; i < TempList.Count; i++) { if (TempList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { frend.UserA = TempList[i]; } if (TempList[i].UserProfile.UserId == id) { frend.UserB = TempList[i]; } } db.Frends.Add(frend); db.SaveChanges(); int CurrentId = id; // Url.Action return RedirectToAction("Index", "Users", new { id = CurrentId }); //return View(); }
// // GET: /Users/ // Другой профиль public ActionResult Index(int id) { ViewBag.NotRead = HomeController.GetNotReadMessagesCount(); if (id == WebSecurity.CurrentUserId) { return RedirectToAction("Index", "Home"); } UserData model = new UserData(); List<UserData> TempList = new List<UserData>(); UsersContext db = new UsersContext(); TempList = db.UsersData.ToList(); for (int i = 0; i < TempList.Count; i++) { if (id == TempList[i].UserProfile.UserId) { model = TempList[i]; break; } } UserData currentUser = new UserData(); for (int i = 0; i < TempList.Count; i++) { if (WebSecurity.CurrentUserId == TempList[i].UserProfile.UserId) { currentUser = TempList[i]; break; } } /* * Проверяем на "Друзей" * Если находим какоето совпадение в БД проверяем был ли запрос подтвержден или нет */ List<FrendsModel> FrendsList = new List<FrendsModel>(); FrendsList = db.Frends.ToList(); for (int i = 0; i < FrendsList.Count; i++) { if ((FrendsList[i].UserA.UserProfile.UserId == WebSecurity.CurrentUserId && FrendsList[i].UserB.UserProfile.UserId == id) || (FrendsList[i].UserB.UserProfile.UserId == WebSecurity.CurrentUserId && FrendsList[i].UserA.UserProfile.UserId == id)) { if (FrendsList[i].IsConfirm) { ViewBag.FrendStatus = model.Name + " у вас в друзьях"; break; } else { ViewBag.FrendStatus = "Запрос в друзья отправлен"; break; } } else ViewBag.FrendStatus = "<button type=\"button\" class=\"btn\" onclick=\"location.href='/Frends/AddFrends/"+ id+"'\">Добавить в друзья </button>"; } ViewBag.currentUser = currentUser; return View(model); }
public ActionResult DelWall(int wallId) { UsersContext db = new UsersContext(); Wall firstOrder = db.Walls .Where(o => o.Id == wallId) .FirstOrDefault(); if (firstOrder != null) db.Walls.Remove(firstOrder); db.SaveChanges(); return RedirectToAction("Index", "Home"); }
public ActionResult Index() { UsersContext db = new UsersContext(); List<Wall> TempList = new List<Wall>(); List<Wall> CurrentUserWall = new List<Wall>(); TempList = db.Walls.ToList(); for (int i = 0; i < TempList.Count; i++) { if (TempList[i].ThisUser.UserId == WebSecurity.CurrentUserId) { CurrentUserWall.Add(TempList[i]); } } return PartialView(CurrentUserWall); }
public ActionResult Settings() { ViewBag.NotRead = HomeController.GetNotReadMessagesCount(); UsersContext db = new UsersContext(); List<UserData> TempUserList = new List<UserData>(); TempUserList = db.UsersData.ToList(); for (int i = 0; i < TempUserList.Count; i++) { if (TempUserList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { ViewBag.currentUser = TempUserList[i]; break; } } return View(); }
public ActionResult ViewWallUser(int UserId) { UsersContext db = new UsersContext(); GetCurrentUser(); List<Wall> TempList = new List<Wall>(); List<Wall> CurrentUserWall = new List<Wall>(); TempList = db.Walls.ToList(); for (int i = TempList.Count-1; i > -1 ; i--) { if (TempList[i].ThisUser.UserId == UserId) { CurrentUserWall.Add(TempList[i]); } } return View(CurrentUserWall); }
public void GetCurrentUser() { db = new UsersContext(); List<UserData> TempList = new List<UserData>(); TempList = db.UsersData.ToList(); ViewBag.Users = TempList; UserData model = new UserData(); for (int i = 0; i < TempList.Count; i++) { if (TempList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { model = TempList[i]; break; } } ViewBag.currentUser = model; }
// // GET: /Message/ public ActionResult PostMessage(int UserGetId) { Message model = new Message(); UsersContext db = new UsersContext(); List<UserData> TempList = new List<UserData>(); TempList = db.UsersData.ToList(); UserData PostUser = new UserData(); for (int i = 0; i < TempList.Count; i++) { if (TempList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { PostUser = TempList[i]; break; } } model.UserGet = db.UserProfiles.Find(UserGetId); model.UserPost = PostUser.UserProfile; return View(model); }
public ActionResult AddData() { UsersContext db = new UsersContext(); string a = WebSecurity.CurrentUserName; UserData model = new UserData(); List<UserData> TempList = new List<UserData>(); TempList = db.UsersData.ToList(); for (int i = 0; i < TempList.Count ; i++) { if (TempList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { model = TempList[i]; ViewBag.currentUser = TempList[i]; break; } } db.Dispose(); ViewBag.NotRead = HomeController.GetNotReadMessagesCount(); return View("AddData",model); }
public ActionResult PostMessage(Message model, int UserGetId, string returnUrl) { UsersContext db = new UsersContext(); model.UserGet = db.UserProfiles.Find(UserGetId); model.UserPost = db.UserProfiles.Find(WebSecurity.CurrentUserId); model.Time = DateTime.Now; model.IsRead = false; // Обнуляем ID юзера, т.к. чудесным образом вместо модели получателя // в контроллер приходит ID получателя, причем он записывается в поле ID модели // чудеса да и только model.Id = 0; int CurrentUserPageId = model.UserGet.UserId; db.Messages.Add(model); db.SaveChanges(); return Redirect(returnUrl); //Uri MyUrl = Request.UrlReferrer; //if (MyUrl.LocalPath == "/Message/Dialog") // return RedirectToAction("Dialog", "Message", new { UserId = UserGetId }); //else // return RedirectToAction("Index", "Users", new { id = CurrentUserPageId }); }
public SimpleMembershipInitializer() { Database.SetInitializer<UsersContext>(null); try { using (var context = new UsersContext()) { if (!context.Database.Exists()) { // Create the SimpleMembership database without Entity Framework migration schema ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); } catch (Exception ex) { throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex); } }
public ActionResult ConfirmRequest(int id) { UsersContext db = new UsersContext(); var EditUser = db.Frends .Where(c => c.Id == id) .FirstOrDefault(); EditUser.IsConfirm = true; db.SaveChanges(); return RedirectToAction("RequestFrends"); }
public ActionResult Upload(HttpPostedFileBase upload) { UsersContext db = new UsersContext(); if (upload != null) { // получаем имя файла string fileName = System.IO.Path.GetFileName(upload.FileName); // сохраняем файл в папку Files в проекте string Extention = System.IO.Path.GetExtension(upload.FileName); string NewFileName = Crypto.Hash(fileName); NewFileName = NewFileName.Remove(0,20); NewFileName = NewFileName.ToLower(); NewFileName +=Extention; upload.SaveAs(Server.MapPath("~/Avatars/" + NewFileName)); var EditUser = db.UsersData .Where(c => c.UserProfile.UserId == WebSecurity.CurrentUserId) .FirstOrDefault(); //System.IO.File.Delete(Server.MapPath(EditUser.AvatarUrl)); EditUser.AvatarUrl = "/Avatars/" + NewFileName; db.SaveChanges(); upload.SaveAs(Server.MapPath("~/Avatars/" + NewFileName)); } return RedirectToAction("Index", "Home"); }
public ActionResult Dialog (int UserId) { UsersContext db = new UsersContext(); List<UserData> TempUserList = new List<UserData>(); TempUserList = db.UsersData.ToList(); for (int i = 0; i < TempUserList.Count; i++) { if (TempUserList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { ViewBag.currentUser = TempUserList[i]; break; } } List<Message> TempList = new List<Message>(); TempList = db.Messages.ToList(); List<Message> DialogList = new List<Message>(); for (int i = TempList.Count -1 ; i >= 0; i--) { if ((TempList[i].UserGet.UserId == WebSecurity.CurrentUserId && TempList[i].UserPost.UserId == UserId) || (TempList[i].UserPost.UserId == WebSecurity.CurrentUserId && TempList[i].UserGet.UserId == UserId)) DialogList.Add(TempList[i]); } List<MessageModel> NewDialogList = new List<MessageModel>(); for (int i = 0; i < DialogList.Count; i++) { UserData UserInfo = new UserData(); MessageModel tempMessageModel = new MessageModel(); tempMessageModel.Message = DialogList[i]; if (DialogList[i].UserGet.UserId == WebSecurity.CurrentUserId) { int FindUserId = (int)DialogList[i].UserPost.UserId; UserInfo = db.UsersData .Where(c => c.UserProfile.UserId == FindUserId) .FirstOrDefault(); tempMessageModel.UserData = UserInfo; } if (DialogList[i].UserPost.UserId == WebSecurity.CurrentUserId) { int FindUserId = (int)DialogList[i].UserGet.UserId; UserInfo = db.UsersData .Where(c => c.UserProfile.UserId == FindUserId) .FirstOrDefault(); tempMessageModel.UserData = UserInfo; } ViewBag.UserGet = UserId; NewDialogList.Add(tempMessageModel); } // Если были нерпочитанные сообщения в диалоге, т опри открытии диалога меняем их статус for (int i = 0; i < NewDialogList.Count; i++) { if(NewDialogList[i].Message.IsRead == false && NewDialogList[i].Message.UserGet.UserId == WebSecurity.CurrentUserId) { // создаем переменну _tempIndex и передаем ей id сообщения // после чего используем ее в LINQ запросе // Все это необходимо т.к. EntityFramework не поддерживает индексаторы int _tempIndex = NewDialogList[i].Message.Id; var EditStatus = db.Messages .Where(w => w.Id == _tempIndex) .FirstOrDefault(); EditStatus.IsRead = true; NewDialogList[i].Message.IsRead = true; db.SaveChanges(); } } for (int i = 0; i < DialogList.Count; i++) { if (DialogList[i].IsRead == false && DialogList[i].UserGet.UserId == WebSecurity.CurrentUserId) { int _tempIndex = DialogList[i].Id; var EditStatus = db.Messages .Where(w => w.Id == _tempIndex) .FirstOrDefault(); EditStatus.IsRead = true; db.SaveChanges(); } } ViewBag.NotRead = HomeController.GetNotReadMessagesCount(); return View(NewDialogList); }
public ActionResult AddWall( Wall model, HttpPostedFileBase upload) { UsersContext db = new UsersContext(); if (upload != null) { // получаем имя файла string fileName = System.IO.Path.GetFileName(upload.FileName); // сохраняем файл в папку Files в проекте string Extention = System.IO.Path.GetExtension(upload.FileName); string NewFileName = Crypto.HashPassword(fileName); NewFileName = NewFileName.Remove(0, 20); NewFileName += Extention; NewFileName = NewFileName.Replace('/', 'w'); NewFileName = NewFileName.Replace('\\', 'a'); NewFileName = NewFileName.Replace('+', 'q'); upload.SaveAs(Server.MapPath("~/WallsContent/" + NewFileName)); model.ContentUrl = "/WallsContent/" + NewFileName; } model.ThisUser = db.UserProfiles.Find(WebSecurity.CurrentUserId); model.CreationDate = DateTime.Now; model.PostUser = db.UserProfiles.Find(WebSecurity.CurrentUserId); db.Walls.Add(model); db.SaveChanges(); return RedirectToAction("Index", "Home"); }
public ActionResult Register(RegisterModel model) // регистрация { // Всякие проверки if (model.ConfirmPassword == null || model.EmailAdres == null || model.Password == null || model.UserName == null) { ModelState.AddModelError("MyError", "Ошибка! Заполните все поля!"); return View(model); } if (ModelState.IsValid) { // Attempt to register the user try { if (model.EmailAdres.IndexOf('@') < 1) { ModelState.AddModelError("EmailAdres", "E-mail адрес введен не корректно"); return View(model); } List<int> qwe = new List<int>(); for (int i = 0; i < model.UserName.Length; i++) { qwe.Add((char)model.UserName[i]); } bool LoginValid = false; for (int i = 0; i < model.UserName.Length; i++) { if (((int)model.UserName[i] > 47 && (int)model.UserName[i] < 58) || ((int)model.UserName[i] > 64 && (int)model.UserName[i] < 91) || ((int)model.UserName[i] > 96 && (int)model.UserName[i] < 123)) LoginValid = true; else { ModelState.AddModelError("UserName", "Имя пользователя должно состоять из следущих символо: A-Z и 0-9"); return View(model); } } if (LoginValid) { model.UserName.ToLower(); model.EmailAdres.ToLower(); if (WebSecurity.UserExists(model.UserName)) { ModelState.AddModelError("UserName", "Логин занят"); return View(model); } UsersContext db = new UsersContext(); List<EmailModel> emailCheck = new List<EmailModel>(); emailCheck = db.EmailModels.ToList(); for (int i = 0; i < emailCheck.Count; i++) { if (emailCheck[i].Email == model.EmailAdres) { ModelState.AddModelError("UserName", "Пользователь с таким e-mail уже существует"); return View(model); } } // ТУТ СОЗДАЕМ НОВОГО ПОЛЬЗОВАТЕЛЯ WebSecurity.CreateUserAndAccount(model.UserName, model.Password); // сРАЗУЖЕ ЛОГИНИМСЯ bool logged = WebSecurity.Login(model.UserName, model.Password); if (logged) { //set auth cookie FormsAuthentication.SetAuthCookie(model.UserName, false); } UserProfile TempProfile = db.UserProfiles.Find(WebSecurity.GetUserId(model.UserName)); UserData CurrentUserDataModel = new UserData(TempProfile); db.UsersData.Add(CurrentUserDataModel); db.SaveChanges(); // ГЕНЕРИРУЕМ КОТД ПОДТВЕРЖДЕНИЯ EmailModel e = new EmailModel(); e.Email = model.EmailAdres; e.IsConfirm = false; e.Key = Crypto.SHA256(model.EmailAdres); e.PasswordRecoverKey = Crypto.SHA256(model.EmailAdres + model.Password + model.UserName); e.UserProfile = TempProfile; db.EmailModels.Add(e); db.SaveChanges(); SendMail("smtp.mail.ru", "ЯЩИК С КОТОРОГО ОТПРАВЛЯЕТЯ ПИСЬМО", "ПАРОЛЬ ОТ ЯЩИКА", e.Email , "public", "Welcom to public " + "Пожалуйста, активируйте Ваш аккаунт, перейдя по этой ссылке http://public.somee.com/Account/ActivationAccount/" + e.Key, null); ViewBag.currentUser = CurrentUserDataModel; return View("AddData", CurrentUserDataModel); } } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } } else { for (int i = 0; i < model.UserName.Length; i++) { if ((int)model.UserName[i] < 48 || (int)model.UserName[i] > 57 || (int)model.UserName[i] < 65 || (int)model.UserName[i] > 90 || (int)model.UserName[i] < 97 || (int)model.UserName[i] > 122 ) ModelState.AddModelError("UserName", "Имя пользователя должно состоять из следущих символо: A-Z и 0-9"); } if (model.UserName.Length < 4) ModelState.AddModelError("UserName", "Имя пользователя должно быть не менее трех символов"); if (model.Password != model.ConfirmPassword) ModelState.AddModelError("ConfirmPassword", "Оба пароля должны быть идентичны"); if (model.EmailAdres.IndexOf('@') < 1) ModelState.AddModelError("EmailAdres", "E-mail адрес введен не корректно"); } // If we got this far, something failed, redisplay form return View(model); }
// АКТИВАЦИЯ АККАУНТА ЕСЛИ ПОЛЬЗОВАТЕЛЬ ПЕРЕШЕЛ ПО ССЫЛКЕ public ActionResult ActivationAccount(string ActivatonCode) { UsersContext db = new UsersContext(); EmailModel userEmail = new EmailModel(); List<EmailModel> TempList = new List<EmailModel>(); TempList = db.EmailModels.ToList(); for (int i = 0; i < TempList.Count; i++) { if (ActivatonCode == TempList[i].Key && WebSecurity.CurrentUserId == TempList[i].UserProfile.UserId) { userEmail = TempList[i]; var EditUser = db.EmailModels .Where(c => c.Id == userEmail.Id) .FirstOrDefault(); EditUser.IsConfirm = true; db.SaveChanges(); break; } } ViewBag.EmailError = null; return RedirectToAction("Index", "Home"); }
public ActionResult RecoverPassword(PasswordRecoverModel Model) { if (Model.Email == null || Model.Name == null) { ModelState.AddModelError("MyObject", "Заполните все поля"); return View(); } UsersContext db = new UsersContext(); EmailModel FindUser = new EmailModel(); List<EmailModel> _tempList = new List<EmailModel>(); _tempList = db.EmailModels.ToList(); for (int i = 0; i <_tempList.Count; i++) if (_tempList[i].Email.Trim().ToLower() == Model.Email.Trim().ToLower() && _tempList[i].UserProfile.UserName.Trim().ToLower() == Model.Name.Trim().ToLower()) { FindUser = _tempList[i]; break; } if (FindUser.Email == null) { ModelState.AddModelError("MyObject", "Данные введены не корректно"); return View(); } string Key = WebSecurity.GeneratePasswordResetToken(FindUser.UserProfile.UserName); SendMail("smtp.mail.ru", "*****@*****.**", "7632bxr29zx6", FindUser.Email, "public", "Welcom to public " + "Для восстановления пароля перейдите по этой ссылке http://public.somee.com/Account/RecoverPasswordPage?Key=" + Key, null); return View(); }
public ActionResult RecoverPasswordPage(LocalPasswordModel model) { if (model.NewPassword == null || model.ConfirmPassword == null) { ModelState.AddModelError("NewPassword", "Ошибка! Заполните все поля"); return View(model); } if (model.NewPassword != model.ConfirmPassword) { ModelState.AddModelError("NewPassword", "Ошибка! Пароли должны совпадать"); return View(model); } int s = WebSecurity.GetUserIdFromPasswordResetToken(model.OldPassword); string FindUser = ""; WebSecurity.ResetPassword(model.OldPassword, model.NewPassword); UsersContext db = new UsersContext(); List<UserProfile> _userProfileList = db.UserProfiles.ToList(); for (int i = 0; i < _userProfileList.Count; i++) { if (_userProfileList[i].UserId == s) { FindUser = _userProfileList[i].UserName; break; } } bool logget = WebSecurity.Login(FindUser, model.NewPassword); if (logget) return RedirectToAction("Index", "Home"); else return View(); }
public ActionResult Manage(LocalPasswordModel model) { GetCurrentUser(); bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)); ViewBag.HasLocalPassword = hasLocalAccount; ViewBag.ReturnUrl = Url.Action("Manage"); if (hasLocalAccount) { if (ModelState.IsValid) { // ChangePassword will throw an exception rather than return false in certain failure scenarios. bool changePasswordSucceeded; try { changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword); UsersContext db; db = new UsersContext(); List<UserData> TempList = new List<UserData>(); TempList = db.UsersData.ToList(); ViewBag.Users = TempList; UserData _model = new UserData(); for (int i = 0; i < TempList.Count; i++) { if (TempList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { _model = TempList[i]; break; } } ViewBag.currentUser = _model; } catch (Exception) { changePasswordSucceeded = false; } if (changePasswordSucceeded) { return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess }); } else { ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } } } else { // User does not have a local password so remove any validation errors caused by a missing // OldPassword field ModelState state = ModelState["OldPassword"]; if (state != null) { state.Errors.Clear(); } if (ModelState.IsValid) { try { WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword); return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess }); } catch (Exception) { ModelState.AddModelError("", String.Format("Unable to create local account. An account with the name \"{0}\" may already exist.", User.Identity.Name)); } } } // If we got this far, something failed, redisplay form return View(model); }
public ActionResult FindUser (string Model) { if (String.IsNullOrEmpty(Model)) return RedirectToAction("Frends"); ViewBag.NotRead = HomeController.GetNotReadMessagesCount(); List<FrendsModel> TempList = new List<FrendsModel>(); List<FrendsModel> FrendsList = new List<FrendsModel>(); UsersContext db = new UsersContext(); List<UserData> TempUserList = new List<UserData>(); List<UserData> ConfirmFrends = new List<UserData>(); List<UserData> NotConfirmFrends = new List<UserData>(); TempList = db.Frends.ToList(); // Получаем все заявки в друзья for (int i = 0; i < TempList.Count; i++) { if (TempList[i].UserA.UserProfile.UserId == WebSecurity.CurrentUserId || TempList[i].UserB.UserProfile.UserId == WebSecurity.CurrentUserId) FrendsList.Add(TempList[i]); } // Получаем модель текущего пользоваеля TempUserList = db.UsersData.ToList(); for (int i = 0; i < TempUserList.Count; i++) { if (TempUserList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { ViewBag.currentUser = TempUserList[i]; break; } } // Получаем потвержденные и не подтвержденные заявки в друзья for (int i = 0; i < FrendsList.Count; i++) { if (FrendsList[i].UserA.UserProfile.UserId == WebSecurity.CurrentUserId) if (FrendsList[i].IsConfirm) ConfirmFrends.Add(FrendsList[i].UserB); else NotConfirmFrends.Add(FrendsList[i].UserB); else if (FrendsList[i].IsConfirm) ConfirmFrends.Add(FrendsList[i].UserA); else NotConfirmFrends.Add(FrendsList[i].UserA); } string Find = Model.Trim().ToLower(); List<UserData> FindUsersList = new List<UserData>(); for (int i = 0; i < ConfirmFrends.Count; i++) { if (ConfirmFrends[i].Name.ToLower() == Find || ConfirmFrends[i].LastName.ToLower() == Find) FindUsersList.Add(ConfirmFrends[i]); } ViewBag.FrendsCount = ConfirmFrends.Count; ViewBag.Frends = FindUsersList; return View("Frends", FindUsersList); }
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 (UsersContext db = new UsersContext()) { UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower()); // Check if user already exists if (user == null) { // 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 AddData(UserData model, HttpPostedFileBase upload) { UsersContext db = new UsersContext(); List<UserData> TempList = new List<UserData>(); TempList = db.UsersData.ToList(); for (int i = 0; i < TempList.Count; i++) { if (TempList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { ViewBag.currentUser = TempList[i]; break; } } var EditUser = db.UsersData .Where(c => c.UserProfile.UserId == WebSecurity.CurrentUserId) .FirstOrDefault(); if (upload != null) { // получаем имя файла string fileName = System.IO.Path.GetFileName(upload.FileName); // сохраняем файл в папку Files в проекте string Extention = System.IO.Path.GetExtension(upload.FileName); string NewFileName = Crypto.Hash(fileName); NewFileName = NewFileName.Remove(0, 20); NewFileName = NewFileName.ToLower(); NewFileName += Extention; upload.SaveAs(Server.MapPath("~/Avatars/" + NewFileName)); //System.IO.File.Delete(Server.MapPath(EditUser.AvatarUrl)); EditUser.AvatarUrl = "/Avatars/" + NewFileName; db.SaveChanges(); upload.SaveAs(Server.MapPath("~/Avatars/" + NewFileName)); } if (model.Name == null) { ModelState.AddModelError("Name", "Поле Имя обязательно к заполнению"); return View("AddData", model); } if (model.LastName == null) { ModelState.AddModelError("LastName", "Поле Фамилия обязательно к заполнению"); return View("AddData", model); } EditUser.BrithDay = model.BrithDay; EditUser.About = model.About; EditUser.City = model.City; EditUser.College = model.College; EditUser.Entertainment = model.Entertainment; EditUser.FavoriteBook = model.FavoriteBook; EditUser.FavoriteGames = model.FavoriteGames; EditUser.FavoriteKino = model.FavoriteKino; EditUser.FavoriteMusik = model.FavoriteMusik; EditUser.HPhone = model.HPhone; EditUser.Instagram = model.Instagram; EditUser.Institute = model.Institute; EditUser.Interesses = model.Interesses; EditUser.Job = model.Job; EditUser.LastName = model.LastName; EditUser.Name = model.Name; EditUser.Phone = model.Phone; EditUser.School = model.School; EditUser.Sex = model.Sex; EditUser.Skype = model.Skype; EditUser.Twitter = model.Twitter; EditUser.WebSite = model.WebSite; ViewBag.currentUser = EditUser; if (ModelState.IsValid) db.SaveChanges(); else { ModelState.AddModelError("BrithDay", "Введите дату корректно"); return View(model); } ViewBag.NotRead = HomeController.GetNotReadMessagesCount(); return RedirectToAction("Index", "Home"); }
//public ActionResult Messages(int id) //{ // return View(); //} public ActionResult Messages() { ViewBag.NotRead = HomeController.GetNotReadMessagesCount(); UsersContext db = new UsersContext(); List<Message> TempList = new List<Message>(); TempList = db.Messages.ToList(); List<Message> CurrentUserMessages = new List<Message>(); for (int i = 0; i < TempList.Count; i++) { if (TempList[i].UserGet.UserId == WebSecurity.CurrentUserId) CurrentUserMessages.Add(TempList[i]); } List<UserData> TempUserList = new List<UserData>(); TempUserList = db.UsersData.ToList(); UserData currentUser = new UserData(); List<UserProfile> _tr = db.UserProfiles.ToList(); for (int i = 0; i < TempUserList.Count; i++) { int rr = WebSecurity.CurrentUserId; if (TempUserList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { currentUser = TempUserList[i]; break; } } List<Message> DialogList = new List<Message>(); // Получаем id пользователей с которыми у нас были диалоги List<int> MessageUsersFirstList = new List<int>(); for (int i = 0; i < TempList.Count; i++) { if (TempList[i].UserGet.UserId == WebSecurity.CurrentUserId) MessageUsersFirstList.Add(TempList[i].UserPost.UserId); if (TempList[i].UserPost.UserId == WebSecurity.CurrentUserId) MessageUsersFirstList.Add(TempList[i].UserGet.UserId); } // удаляем повторяющиеся List<int> MessageUsersSecondList = new List<int>(MessageUsersFirstList.Distinct()); // Находим последниии сообщения диалогов // формируем список диалогов for (int i = 0; i < MessageUsersSecondList.Count; i++) { for (int j = TempList.Count-1; j > 0; j--) { if ((MessageUsersSecondList[i] == TempList[j].UserGet.UserId && TempList[j].UserPost.UserId == WebSecurity.CurrentUserId) || (MessageUsersSecondList[i] == TempList[j].UserPost.UserId && TempList[j].UserGet.UserId == WebSecurity.CurrentUserId)) { DialogList.Add(TempList[j]); break; } } } // ViewBag.DialogList = DialogList; // Получаем список диалогов как вконтакте List<MessageModel> NewDialogList = new List<MessageModel>(); for (int i = 0; i < DialogList.Count; i++) { UserData UserInfo = new UserData(); MessageModel tempMessageModel = new MessageModel(); tempMessageModel.Message = DialogList[i]; if (DialogList[i].UserGet.UserId == WebSecurity.CurrentUserId) { int FindUserId = (int)DialogList[i].UserPost.UserId; UserInfo = db.UsersData .Where(c => c.UserProfile.UserId == FindUserId) .FirstOrDefault(); tempMessageModel.UserData = UserInfo; } if (DialogList[i].UserPost.UserId == WebSecurity.CurrentUserId) { int FindUserId = (int)DialogList[i].UserGet.UserId; UserInfo = db.UsersData .Where(c => c.UserProfile.UserId == FindUserId) .FirstOrDefault(); tempMessageModel.UserData = UserInfo; } NewDialogList.Add(tempMessageModel); } // СОртируем по дате отрпавки List<MessageModel> SortedDialogList = NewDialogList.OrderBy(o => o.Message.Time).ToList(); SortedDialogList.Reverse(); ViewBag.DialogList = SortedDialogList; ViewBag.currentUser = currentUser; ViewBag.CurrentUserMessages = CurrentUserMessages; return View(); }
public ActionResult RequestFrends() { ViewBag.NotRead = HomeController.GetNotReadMessagesCount(); List<FrendsModel> TempList = new List<FrendsModel>(); List<FrendsModel> FrendsList = new List<FrendsModel>(); UsersContext db = new UsersContext(); TempList = db.Frends.ToList(); for (int i = 0; i < TempList.Count; i++) { if ((TempList[i].UserA.UserProfile.UserId == WebSecurity.CurrentUserId && !TempList[i].IsConfirm) || (TempList[i].UserB.UserProfile.UserId == WebSecurity.CurrentUserId) && !TempList[i].IsConfirm) FrendsList.Add(TempList[i]); } List<UserData> TempUserList = new List<UserData>(); TempUserList = db.UsersData.ToList(); for (int i = 0; i < TempUserList.Count ; i++) { if (TempUserList[i].UserProfile.UserId == WebSecurity.CurrentUserId) { ViewBag.currentUser = TempUserList[i]; break; } } List<RequestFrendsModel> NotConfirmFrends = new List<RequestFrendsModel>(); for (int i = 0; i < FrendsList.Count; i++) { if (FrendsList[i].UserB.UserProfile.UserId == WebSecurity.CurrentUserId) NotConfirmFrends.Add(new RequestFrendsModel(FrendsList[i].UserA, FrendsList[i].Id)); } return View(NotConfirmFrends); }
public ActionResult Renouncement (int id) { UsersContext db = new UsersContext(); //IQueryable<FrendsModel> ods = from o in db.Frends // where o.Id == id // select o; //db.DeleteObject(ods.First()); FrendsModel RemoveFrendModel = db.Frends.Find(id); db.Frends.Remove(RemoveFrendModel); db.SaveChanges(); return RedirectToAction("RequestFrends"); }
public static int GetNotReadMessagesCount() { UsersContext db = new UsersContext(); List<Message> TempList = new List<Message>(); TempList = db.Messages.ToList(); List<Message> CurrentUserMessages = new List<Message>(); for (int i = 0; i < TempList.Count; i++) { if (TempList[i].UserGet.UserId == WebSecurity.CurrentUserId) CurrentUserMessages.Add(TempList[i]); } List<UserData> TempUserList = new List<UserData>(); TempUserList = db.UsersData.ToList(); UserData currentUser = new UserData(); for (int i = 0; i < TempList.Count; i++) { int q = WebSecurity.CurrentUserId; if (WebSecurity.CurrentUserId == TempUserList[i].UserProfile.UserId) { currentUser = TempUserList[i]; break; } } List<Message> DialogList = new List<Message>(); // Получаем id пользователей с которыми у нас были диалоги List<int> MessageUsersFirstList = new List<int>(); for (int i = 0; i < TempList.Count; i++) { int q = WebSecurity.CurrentUserId; if (TempList[i].UserGet.UserId == WebSecurity.CurrentUserId) MessageUsersFirstList.Add(TempList[i].UserPost.UserId); if (TempList[i].UserPost.UserId == WebSecurity.CurrentUserId) MessageUsersFirstList.Add(TempList[i].UserGet.UserId); } // удаляем повторяющиеся List<int> MessageUsersSecondList = new List<int>(MessageUsersFirstList.Distinct()); // Находим последниии сообщения диалогов // формируем список диалогов for (int i = 0; i < MessageUsersSecondList.Count; i++) { for (int j = TempList.Count - 1; j > 0; j--) { if ((MessageUsersSecondList[i] == TempList[j].UserGet.UserId && TempList[j].UserPost.UserId == WebSecurity.CurrentUserId) || (MessageUsersSecondList[i] == TempList[j].UserPost.UserId && TempList[j].UserGet.UserId == WebSecurity.CurrentUserId)) { DialogList.Add(TempList[j]); break; } } } // ViewBag.DialogList = DialogList; List<MessageModel> NewDialogList = new List<MessageModel>(); for (int i = 0; i < DialogList.Count; i++) { UserData UserInfo = new UserData(); MessageModel tempMessageModel = new MessageModel(); tempMessageModel.Message = DialogList[i]; if (DialogList[i].UserGet.UserId == WebSecurity.CurrentUserId) { int FindUserId = (int)DialogList[i].UserPost.UserId; UserInfo = db.UsersData .Where(c => c.UserProfile.UserId == FindUserId) .FirstOrDefault(); tempMessageModel.UserData = UserInfo; } if (DialogList[i].UserPost.UserId == WebSecurity.CurrentUserId) { int FindUserId = (int)DialogList[i].UserGet.UserId; UserInfo = db.UsersData .Where(c => c.UserProfile.UserId == FindUserId) .FirstOrDefault(); tempMessageModel.UserData = UserInfo; } NewDialogList.Add(tempMessageModel); } int NotReadMessagesCount = 0; for (int i = 0; i < NewDialogList.Count; i++) { if (NewDialogList[i].Message.IsRead == false && NewDialogList[i].Message.UserGet.UserId == WebSecurity.CurrentUserId) NotReadMessagesCount++; } return NotReadMessagesCount; }