private void btnChangeLogin_Click(object sender, EventArgs e) { if (LoggedUser.UserIsLogged) { if (textBoxNewLogin.Text.Equals(textBoxNewLoginRepeat.Text)) { if (textBoxNewLogin.Text.Length > 7) { var changeLogin = new User_(); if (changeLogin.ChangeNameUser(textBoxNewLogin.Text, textBoxPassword.Text)) { this.Close(); } } else { MessageBox.Show("Nowy login musi mieć conajmniej 8 znaków"); } } else { MessageBox.Show("Musisz podać dwa razy taki sam login"); } } else { MessageBox.Show("Aby zmienić login, musisz być zalogowany"); this.Close(); } }
private void btnChangePassword_Click(object sender, EventArgs e) { if (LoggedUser.UserIsLogged) { if (textBoxNewPassword.Text.Equals(textBoxNewPasswordRepeat.Text)) { if (textBoxNewPassword.Text.Length > 7) { var changePassword = new User_(); if (changePassword.ChangePassword(textBoxOldPassword.Text, textBoxNewPassword.Text)) { this.Close(); } } else { MessageBox.Show("Nowy hasło musi mieć conajmniej 8 znaków"); } } else { MessageBox.Show("Musisz podać dwa razy takie samo hasło"); } } else { MessageBox.Show("Aby zmienić login, musisz być zalogowany"); this.Close(); } }
public async Task <ActionResult> RegisterUser(RegisterUserModel model) { if (ModelState.IsValid) { /* * Address adr = new Address(); * adr.Locality = "Johar"; * adr.Lat = 24.9204M; * adr.Lng = 67.1344M; * db.Addresses.Add(adr); * db.SaveChanges(); */ Console.WriteLine(model.Locality); int AdrId1 = (from adr in db.Addresses where adr.Locality.Equals(model.Locality) select adr).FirstOrDefault().id; Console.WriteLine(user_id); Console.WriteLine(AdrId1); User_ user = new User_ { id = user_id, CNIC = model.CNIC, Phone = model.Phone, Address_id = AdrId1 }; db.User_.Add(user); db.SaveChanges(); return(RedirectToAction("", "Home")); } // If we got this far, something failed, redisplay form return(View(model)); }
private void buttonLogIn_Click(object sender, EventArgs e) { var logIn = new User_(); logIn.LogIn(textBoxLogin.Text, textBoxPassword.Text); if (LoggedUser.UserIsLogged) { this.Close(); } }
public void Ex1() { User u = new User("Oleg"); User_ u_ = new User_(); u_.Name = "Oleg"; var res1 = u.GetName(); var res2 = u_.Name; }
public static void Start() { ExecuteSavedQueries(); PulseTimer.Elapsed += new ElapsedEventHandler(Pulse); News = new News_(); Server = new Server_(); User = new User_(); if (PulseFlag) PulseTimer.Start(); Pulse(null, null); }
public static void Start() { ExecuteSavedQueries(); PulseTimer.Elapsed += new ElapsedEventHandler(Pulse); News = new News_(); Server = new Server_(); User = new User_(); if (PulseFlag) { PulseTimer.Start(); } Pulse(null, null); }
private async Task CreateUserRoles(IServiceProvider serviceProvider) { var roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >(); var userManager = serviceProvider.GetRequiredService <UserManager <User_> >(); // Создание ролей администратора и пользователя if (await roleManager.FindByNameAsync("admin") == null) { await roleManager.CreateAsync(new IdentityRole("admin")); } if (await roleManager.FindByNameAsync("user") == null) { await roleManager.CreateAsync(new IdentityRole("user")); } // Создание Администратора string adminEmail = "*****@*****.**"; string adminName = "admin"; string adminPassword = "******"; if (await userManager.FindByNameAsync(adminEmail) == null) { User_ admin = new User_ { Email = adminEmail, UserName = adminName }; IdentityResult result = await userManager.CreateAsync(admin, adminPassword); if (result.Succeeded) { await userManager.AddToRoleAsync(admin, "admin"); } } // Создание Пользователя string userEmail = "*****@*****.**"; string userName = "******"; string userPassword = "******"; if (await userManager.FindByNameAsync(userEmail) == null) { User_ user = new User_ { Email = userEmail, UserName = userName }; IdentityResult result = await userManager.CreateAsync(user, userPassword); if (result.Succeeded) { await userManager.AddToRoleAsync(user, "user"); } } }
// GET: Admin/User/Details/5 public ActionResult Details(string id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } User_ user_ = db.User_.Find(id); if (user_ == null) { return(HttpNotFound()); } return(View(user_)); }
public static void Start() { ExecuteSavedQueries(); PulseTimer.Elapsed += new ElapsedEventHandler(Pulse); Character = new Character_(); Mastery = new Mastery_(); Item = new Item_(); Skill = new Skill_(); User = new User_(); if (PulseFlag) { PulseTimer.Start(); } Pulse(null, null); }
// GET: Admin/User/Create public ActionResult Create() { // Tạo id user tự động var createID = (from c in db.User_ select c.id_user).ToList(); string id = ""; if (createID.Count == 0) // nếu danh sách rỗng { id = "Us01"; } else { for (int i = 0; i < createID.Count(); i++) { if (int.Parse(createID[i].Substring(2, 2)) != (i + 1)) { if (i + 1 >= 0 && i + 1 < 9) { id = "Us0" + (i + 1).ToString(); } else if (i + 1 > 9) { id = "Us" + (i + 1).ToString(); } break; } } if (id == "") { id = createID[createID.Count - 1].Substring(2, 2); if (int.Parse(id) >= 0 && int.Parse(id) < 9) { id = "Us0" + (int.Parse(id) + 1).ToString(); } else if (int.Parse(id) >= 9) { id = "Us" + (int.Parse(id) + 1).ToString(); } } } User_ us = new User_ { id_user = id }; ViewBag.id_typeuser = new SelectList(db.TypeUsers, "id_typeuser", "name_typeuser"); return(View(us)); }
public async Task <IActionResult> Register([FromBody] RegisterViewModel model) { if (ModelState.IsValid) { User_ user = new User_ { Email = model.Email, UserName = model.Name }; // Добавление нового пользователя var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "user"); // установка куки await _signInManager.SignInAsync(user, false); var msg = new { message = "Добавлен новый пользователь: " + user.UserName }; return(Ok(msg)); } else { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } var errorMsg = new { message = "Пользователь не добавлен.", error = ModelState.Values.SelectMany(e => e.Errors.Select(er => er.ErrorMessage)) }; return(Ok(errorMsg)); } } else { var errorMsg = new { message = "Неверные входные данные.", error = ModelState.Values.SelectMany(e => e.Errors.Select(er => er.ErrorMessage)) }; return(Ok(errorMsg)); } }
//[ValidateAntiForgeryToken] public async Task <IActionResult> Login([FromBody] LoginViewModel model) { if (ModelState.IsValid) { User_ user = await _userManager.FindByEmailAsync(model.Email); var result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, false); if (result.Succeeded) { User_ usr = await GetCurrentUserAsync(); bool x = true; if (usr != null) { x = await _userManager.IsInRoleAsync(usr, "user"); } var message = usr == null ? "" : usr.UserName; var msg = new { x, message }; return(Ok(msg)); } else { ModelState.AddModelError("", "Неправильный логин и (или) пароль"); var errorMsg = new { message = "Вход не выполнен.", error = ModelState.Values.SelectMany(e => e.Errors.Select(er => er.ErrorMessage)) }; return(Ok(errorMsg)); } } else { var errorMsg = new { message = "Вход не выполнен.", error = ModelState.Values.SelectMany(e => e.Errors.Select(er => er.ErrorMessage)) }; return(Ok(errorMsg)); } }
private void btnDeleteAccount_Click(object sender, EventArgs e) { var user = new User_(); if (user.RemoveUser(textBoxLogin.Text, textBoxPassword.Text)) { MessageBox.Show("Konto zostało trwale, nieodwracalnie usunięte"); LoggedUser.UserLogOut(); deleteOrNot = true; this.Close(); } else { MessageBox.Show("Nie udało się usunąć konta, być może takie konto nie istnieje lub wpisałeś złe hasło"); deleteOrNot = false; } }
public JsonResult GetSearchingData(string locality, string Distance, string Organization) { var ambulances = from amb in db.Ambulances where amb.Available == true select amb; if (!String.IsNullOrEmpty(locality)) { ambulances = ambulances.Where(s => s.Station.Address.Locality.Contains(locality)); } if (!String.IsNullOrEmpty(Organization)) { ambulances = ambulances.Where(s => s.Station.Organization.Contains(Organization)); } if (!String.IsNullOrEmpty(Distance)) { if (Distance == "Yes") { ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); string strCurrentUserId = user.Id; User_ s = db.User_.Find(strCurrentUserId); Address adr = s.Address; //int lat1, lat2, lon1, lon2; //lat1 = adr.Lat; //lon1 = adr.Lng; Dictionary <Ambulance, double> myDict = new Dictionary <Ambulance, double>(); foreach (var amb in ambulances) { //lat2 = amb.Station.Address.Lat; //lon2 = amb.Station.Address.Lng; double dist_ = DistanceCalculator.DistanceCalculate(adr, amb.Station.Address); myDict.Add(amb, dist_); } var ax = (from entry in myDict orderby entry.Value ascending select entry.Key); return(Json(ax.ToList(), JsonRequestBehavior.AllowGet)); } } return(Json(ambulances.ToList(), JsonRequestBehavior.AllowGet)); }
public ActionResult Block() { string id = Request["id"]; User_ us = db.User_.Find(id); string action = Request["action"]; if (action == "Khóa") { us.block_state_user = "******"; } else if (action == "Mở khóa") { us.block_state_user = "******"; } db.Entry(us).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index", "User", new { area = "Admin" })); }
public bool DeleteUser(User_ user) { using (MFDatabaseEntities moodFullDb = new MFDatabaseEntities()) { try { int usernameID = Convert.ToInt32(user.UserId); User xe = moodFullDb.Users.Single(x => x.UserId == usernameID); moodFullDb.Users.Remove(xe); moodFullDb.SaveChanges(); return(true); } catch { return(false); } } }
public ActionResult Login(User_ login) { bool status = false; Wollies_ShelterEntities db = new Wollies_ShelterEntities(); //check username and password form our database here //for demo I am going to use Admin as Username and Password1 as Password static value List <User_> Users; try { //User_ user = new User_(); //user.Username = "******"; //user.Password = "******"; //db.User_.Add(user); //db.SaveChanges(); Users = db.User_.ToList(); } catch (Exception e) { throw; } foreach (var item in Users) { if (item.Username == login.Username && item.Password == login.Password) { status = true; // show 2FA form Session["Username"] = login.Username; //2FA Setup TwoFactorAuthenticator tfa = new TwoFactorAuthenticator(); string UserUniqueKey = (login.Username + key); Session["UserUniqueKey"] = UserUniqueKey; var setupInfo = tfa.GenerateSetupCode("Wollies Shelter", login.Username, UserUniqueKey, 300, 300); ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl; ViewBag.SetupCode = setupInfo.ManualEntryKey; //message = "Credentials are correct"; return(View("Authorize", setupInfo)); } } return(View()); }
//[ValidateAntiForgeryToken] public async Task <IActionResult> LogisAuthenticatedOff() { User_ usr = await GetCurrentUserAsync(); bool isAdmin = false; if (usr != null) { isAdmin = await _userManager.IsInRoleAsync(usr, "admin"); } var message = usr == null ? "" : usr.UserName; var email = usr == null ? "" : usr.Email; var msg = new { isAdmin, message, email }; return(Ok(msg)); }
public bool EditUser(User_ user) { using (MFDatabaseEntities moodFullDb = new MFDatabaseEntities()) { try { int usernameId = Convert.ToInt32(user.UserId); User xe = moodFullDb.Users.Single(x => x.UserId == usernameId); xe.Username = user.Username; xe.Password = user.Password; xe.FirstName = user.FirstName; xe.LastName = user.LastName; xe.UserType = user.UserType; moodFullDb.SaveChanges(); return(true); } catch { return(false); } }; }
public bool CreateUser(User_ user) { using (MFDatabaseEntities moodFullDb = new MFDatabaseEntities()) { try { User xe = new User(); xe.Username = user.Username; xe.Password = user.Password; xe.FirstName = user.FirstName; xe.LastName = user.LastName; xe.UserType = user.UserType; moodFullDb.Users.Add(xe); moodFullDb.SaveChanges(); return(true); } catch { return(false); } } }
private void buttonRegistration_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(textBoxLogin.Text) && !string.IsNullOrWhiteSpace(textBoxPassword.Text)) { if (textBoxLogin.Text.Equals(textBoxLoginRepeat.Text) && textBoxPassword.Text.Equals(textBoxPasswordRepeat.Text)) { if (textBoxLogin.Text != "" && textBoxPassword.Text != "") { if (textBoxLogin.Text.Length >= 8 && textBoxPassword.Text.Length >= 8) { User_ user = new User_(); if (user.AddUser(textBoxLogin.Text, textBoxPassword.Text) == true) { MessageBox.Show("Poprawnie dodano nowego użytkownika"); this.Close(); } } else { MessageBox.Show("Login i hasło muszą składać się z conajmniej 8 znaków"); } } else { MessageBox.Show("Pola login i hasło nie mogą być puste"); } } else { MessageBox.Show("należy podać dwa razy taki sam login i hasło"); } } else { MessageBox.Show("Login i hasło musi się składać z tekstu"); } }
public ActionResult Index() { ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); if (user != null) { string strCurrentUserId = user.Id; User_ s = db.User_.Find(strCurrentUserId); if (s != null) { ViewBag.Role = 1; } else { Station s1 = db.Stations.Find(strCurrentUserId); if (s1 != null) { ViewBag.Role = 2; } } } return(View()); }
public ActionResult Login(User_ login) { //bool status = false; Wollies_ShelterEntities db = new Wollies_ShelterEntities(); List <User_> Users; try { Users = db.User_.ToList(); } catch (Exception e) { ViewBag.err = e.Message; throw; } foreach (var item in Users) { if (item.Username == login.Username && item.Password == login.Password) { Session["Username"] = login.Username; flex.currentuser = item; //2FA Setup TwoFactorAuthenticator tfa = new TwoFactorAuthenticator(); string UserUniqueKey = (login.Username + key); Session["UserUniqueKey"] = UserUniqueKey; //var setupInfo = tfa.GenerateSetupCode("Wollies Shelter", login.Username, UserUniqueKey, 300, 300); //ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl; //ViewBag.SetupCode = setupInfo.ManualEntryKey; //message = "Credentials are correct"; return(View("Authorize", flex)); } } return(View()); }
public static void Start() { ExecuteSavedQueries(); PulseTimer.Elapsed += new ElapsedEventHandler(Pulse); Character = new Character_(); Mastery = new Mastery_(); Item = new Item_(); Skill = new Skill_(); User = new User_(); if (PulseFlag) PulseTimer.Start(); Pulse(null, null); }
private async void btnRegistDone_Clicked(object sender, EventArgs e) { Cator.IsRunning = true; Cator.IsVisible = true; btnRegistDone.IsEnabled = false; var user = User_.Text; var pass = Pass_.Text; if (string.IsNullOrEmpty(User_.Text) || string.IsNullOrWhiteSpace(User_.Text)) { User_.Focus(); } else if (string.IsNullOrEmpty(Pass_.Text) || string.IsNullOrWhiteSpace(Pass_.Text)) { Pass_.Focus(); } else { HttpClient client = new HttpClient(); UserDb = new UserDataBase(); var userW = new User(); var user_exista = UserDb.GetMembers().ToList(); var token = user_exista[0].token; var value_check = new Dictionary <string, string> { { "email", user }, { "pass", pass }, { "token", token } }; var contentx = new FormUrlEncodedContent(value_check); try { var response = await client.PostAsync("http://www.washdryapp.com/app/public/solicitud/login_cliente", contentx); HttpContent content = response.Content; var json = await content.ReadAsStringAsync(); if (json == "[{\"nombre\":\"fail\"}]") { await DisplayAlert("Error", "su nombre o contraseña son invalidos", "ok"); } else { var json_ = JsonConvert.DeserializeObject <List <User> >(json); var user_x = new User(); //var userDataBase = new UserDataBase(); UserDb = new UserDataBase(); var tk = UserDb.GetMembers().ToList().FirstOrDefault(); user_x.email = json_[0].email; user_x.google_id = json_[0].google_id; user_x.name = json_[0].name; user_x.nombre = json_[0].nombre; user_x.password = ""; user_x.status = 0; user_x.remember_token = ""; user_x.id = json_[0].id; user_x.id_cliente = json_[0].id; user_x.username = json_[0].username; user_x.remember_token = "";//username id user_x.token = tk.token; UserDb.AddMember(user_x); UserDb.DeleteMember(0); Application.Current.MainPage = new MainPage(); } } catch (Exception ex) { await DisplayAlert("", "" + ex.ToString(), ""); } } Cator.IsRunning = false; Cator.IsVisible = false; btnRegistDone.IsEnabled = true; }
public ActionResult MaintainEmployees(int?Title, int?EmployeeType, Employee emp, User_ user, int?[] Role, string Gender, HttpPostedFileBase Contract, string button) { if (button == "Save") { try { Employee searchemployee_type = db.Employees.Find(emp.Emp_ID); if (searchemployee_type == null) { return(HttpNotFound()); } //saveEmp = emp; //saveEmp.Emp_Gender = Gender; emp.Title_ID = Title; emp.Emp_Type_ID = EmployeeType; //this is where we convert the contract to add to the database byte[] bytes; using (BinaryReader br = new BinaryReader(Contract.InputStream)) { bytes = br.ReadBytes(Contract.ContentLength); } emp.Emp_Contract_Name = Path.GetFileName(Contract.FileName); emp.Emp_Contract_Type = Contract.ContentType; emp.Emp_Contract = bytes; db.Entry(searchemployee_type).CurrentValues.SetValues(emp); db.SaveChanges(); //first look for the employee that we just added Employee searchemp = db.Employees.Where(z => z.Title_ID == emp.Title_ID && z.Emp_Type_ID == emp.Emp_Type_ID && z.Emp_Name == emp.Emp_Name && z.Emp_Email == emp.Emp_Email && z.Emp_Surname == emp.Emp_Surname && z.Emp_IDNumber == emp.Emp_IDNumber).FirstOrDefault(); Employee old = db.Employees.Where(z => z.Title_ID == emp.Title_ID && z.Emp_Type_ID == emp.Emp_Type_ID && z.Emp_Name == emp.Emp_Name && z.Emp_Email == emp.Emp_Email && z.Emp_Surname == emp.Emp_Surname && z.Emp_IDNumber == emp.Emp_IDNumber).FirstOrDefault(); //then we add the employee id to the user that we created at the top //if (searchemp == null) //{ // return View("AddEmployee", innovation); //} if (user == null || Role == null) { TempData["EditMessage"] = "Employee Succesfully Updated"; return(View("AddEmployee", innovation)); } //user.Emp_ID = searchemp.Emp_ID; TwoFactorAuthenticator tfa = new TwoFactorAuthenticator(); string UserUniqueKey = (user.Username + key); Session["UserUniqueKey"] = UserUniqueKey; var setupInfo = tfa.GenerateSetupCode("Wollies Shelter", user.Username, UserUniqueKey, 300, 300); searchemp.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl; db.Entry(old).CurrentValues.SetValues(searchemp); db.SaveChanges(); var olduser = db.User_.Where(Zinhle => Zinhle.Emp_ID == searchemp.Emp_ID).FirstOrDefault(); //var md5 = new MD5CryptoServiceProvider(); //var pass = md5.ComputeHash(Convert.FromBase64String(user.Password)); //user.Password = pass; //we store the info db.Entry(olduser).CurrentValues.SetValues(user); db.SaveChanges(); //we store the User acces that is needed User_ searchuser = db.User_.Where(z => z.Emp_ID == searchemp.Emp_ID).FirstOrDefault(); if (searchuser == null) { TempData["EditMessage"] = "Employee Succesfully Updated"; return(View("AddEmployee", innovation)); } foreach (var item in Role) { UserRole userRole = new UserRole(); userRole.UserID = searchuser.UserID; userRole.Role_ID = item; db.UserRoles.Add(userRole); db.SaveChanges(); TempData["EditMessage"] = "Employee Succesfully Updated"; } user = searchuser; TempData["EditMessage"] = "Employee Succesfully Updated"; return(View("BarCodeGenerated", user)); } catch (Exception e) { TempData["ErrorMessage"] = e.Message; return(RedirectToAction("Index", "Home")); } } else if (button == "Cancel") { TempData["ErrorMessage"] = "Succesfully Cancelled"; return(RedirectToAction("Index", "Home")); } return(RedirectToAction("Index", "Home")); }
public ActionResult AddEmployee(int?Title, int?EmployeeType, Employee emp, User_ user, int?[] Role, string Gender, HttpPostedFileBase Contract) { Employee saveEmp = new Employee(); try { if (Title == null || EmployeeType == null || emp == null) { TempData["EditMessage"] = "Please Complete all the relevant information"; return(View("AddEmployee", innovation)); } saveEmp = emp; //saveEmp.Emp_Gender = Gender; saveEmp.Title_ID = Title; saveEmp.Emp_Type_ID = EmployeeType; //this is where we convert the contract to add to the database byte[] bytes; using (BinaryReader br = new BinaryReader(Contract.InputStream)) { bytes = br.ReadBytes(Contract.ContentLength); } saveEmp.Emp_Contract_Name = Path.GetFileName(Contract.FileName); saveEmp.Emp_Contract_Type = Contract.ContentType; saveEmp.Emp_Contract = bytes; db.Employees.Add(saveEmp); db.SaveChanges(); //Now we have to store the user //first look for the employee that we just added Employee searchemp = db.Employees.Where(z => z.Title_ID == saveEmp.Title_ID && z.Emp_Type_ID == saveEmp.Emp_Type_ID && z.Emp_Name == saveEmp.Emp_Name && z.Emp_Email == saveEmp.Emp_Email && z.Emp_Surname == saveEmp.Emp_Surname && z.Emp_IDNumber == saveEmp.Emp_IDNumber).FirstOrDefault(); Employee old = db.Employees.Where(z => z.Title_ID == saveEmp.Title_ID && z.Emp_Type_ID == saveEmp.Emp_Type_ID && z.Emp_Name == saveEmp.Emp_Name && z.Emp_Email == saveEmp.Emp_Email && z.Emp_Surname == saveEmp.Emp_Surname && z.Emp_IDNumber == saveEmp.Emp_IDNumber).FirstOrDefault(); //then we add the employee id to the user that we created at the top if (searchemp == null) { TempData["SuccessMessage"] = "Successfully added the employee"; return(View("AddEmployee", innovation)); } if (user == null || Role == null) { TempData["SuccessMessage"] = "Succesfully added the employee"; return(View("AddEmployee", innovation)); } user.Emp_ID = searchemp.Emp_ID; TwoFactorAuthenticator tfa = new TwoFactorAuthenticator(); string UserUniqueKey = (user.Username + key); Session["UserUniqueKey"] = UserUniqueKey; var setupInfo = tfa.GenerateSetupCode("Wollies Shelter", user.Username, UserUniqueKey, 300, 300); searchemp.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl; ViewBag.Qr = setupInfo.QrCodeSetupImageUrl; db.Entry(old).CurrentValues.SetValues(searchemp); db.SaveChanges(); //var md5 = new MD5CryptoServiceProvider(); //var pass = md5.ComputeHash(Convert.FromBase64String(user.Password)); //user.Password = pass; //we store the info db.User_.Add(user); db.SaveChanges(); //we store the User acces that is needed User_ searchuser = db.User_.Where(z => z.Emp_ID == searchemp.Emp_ID).FirstOrDefault(); if (searchuser == null) { return(View("AddEmployee", innovation)); } foreach (var item in Role) { UserRole userRole = new UserRole(); userRole.UserID = searchuser.UserID; userRole.Role_ID = item; db.UserRoles.Add(userRole); db.SaveChanges(); TempData["SuccessMessage"] = "Succesfully added the User"; } user = searchuser; TempData["SuccessMessage"] = "Succesfully added the User"; return(View("BarCodeGenerated", user)); } catch (Exception e) { TempData["EditMessage"] = e.Message; return(RedirectToAction("AddEmployee")); } }
public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] User_ user) { user.CreatedDate = DateTime.Now; bool Status = false; string message = ""; if (ModelState.IsValid) { #region //Email is already Exist var isExist = IsEmailExist(user.Email); if (isExist) { ModelState.AddModelError("EmailExist", "E-Posta Zaten Var"); return(View(user)); } var isExist2 = IsUserNameExist(user.UserName); if (isExist2) { ModelState.AddModelError("UserNameExist", "Kullanıcı Adı Kullanılmış"); return(View(user)); } #endregion #region Generate Activation Code user.ActivationCode = Guid.NewGuid(); #endregion #region Password Hashing user.Password = Crypto.Hash(user.Password); user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword); user.IsEmailVerified = false; #endregion #region Save to Database using (EnstrumanSatisEntities db = new EnstrumanSatisEntities()) { db.User_.Add(user); db.SaveChanges(); SendVerificationLinkEmail(user.Email, user.ActivationCode.ToString()); message = " Hesap etkinleştirme bağlantısı " + user.Email + " e-posta adresinize gönderildi"; Status = true; } #endregion } else { message = "Geçersiz İstek"; } ViewBag.Message = message; ViewBag.Status = Status; return(View(user)); }
public ActionResult Index(string locality, string Distance, string Organization) { var ambulances = from amb in db.Ambulances where amb.Available == true select amb; if (Response.Cookies["Search"]["loc"] == null) { Response.Cookies["Search"]["loc"] = locality; } if (Response.Cookies["Search"]["dist"] == null) { Response.Cookies["Search"]["dist"] = Distance; } if (Response.Cookies["Search"]["org"] == null) { Response.Cookies["Search"]["org"] = Organization; } var Locality = new List <string>(); var loc = from a in db.Addresses orderby a.Locality select a.Locality; Locality.AddRange(loc.Distinct()); ViewBag.locality = new SelectList(Locality); var Org = new List <string>(); var org_ = from stat in db.Stations orderby stat.Organization select stat.Organization; Org.AddRange(org_.Distinct()); ViewBag.Organization = new SelectList(Org); var dist = new List <string>(); dist.Add("Yes"); dist.Add("No"); ViewBag.Distance = new SelectList(dist); if (User.Identity.IsAuthenticated) { ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); string strCurrentUserId = user.Id; User_ s = db.User_.Find(strCurrentUserId); if (s != null) { ViewBag.Role = 1; } } if (!String.IsNullOrEmpty(locality)) { ambulances = ambulances.Where(s => s.Station.Address.Locality.Contains(locality)); } if (!String.IsNullOrEmpty(Organization)) { ambulances = ambulances.Where(s => s.Station.Organization.Contains(Organization)); } if (!String.IsNullOrEmpty(Distance)) { if (Distance == "Yes") { ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); string strCurrentUserId = user.Id; User_ s = db.User_.Find(strCurrentUserId); Address adr = s.Address; //int lat1, lat2, lon1, lon2; //lat1 = adr.Lat; //lon1 = adr.Lng; Dictionary <Ambulance, double> myDict = new Dictionary <Ambulance, double>(); foreach (var amb in ambulances) { //lat2 = amb.Station.Address.Lat; //lon2 = amb.Station.Address.Lng; double dist_ = DistanceCalculator.DistanceCalculate(adr, amb.Station.Address); myDict.Add(amb, dist_); } var ax = (from entry in myDict orderby entry.Value ascending select entry.Key); return(View(ax.ToList())); } } return(View(ambulances.ToList())); }
public ActionResult Create([Bind(Include = "id_user,name_user,password_user,id_typeuser,lname_user,fname_user,email_user,avt_user,block_state_user,registerdate_user,lastvisitdate_user,phone_user,sex_user,birthday_user,address_user")] User_ user_) { string bday = Request["birthday"]; if (user_.name_user == "" || user_.lname_user == "" || user_.fname_user == "" || user_.password_user == "" || bday == null || user_.id_typeuser == "") { if (user_.name_user == "") { ModelState.AddModelError("usname", "Không được để trống tên tài khoản"); } if (user_.lname_user == "") { ModelState.AddModelError("lname", "Không được để trống họ"); } if (user_.fname_user == "") { ModelState.AddModelError("fname", "Không được để trống tên"); } if (user_.password_user == "") { ModelState.AddModelError("pass", "Không được để trống mật khẩu"); } if (bday == null) { ModelState.AddModelError("bday", "Không được để trống ngày sinh"); } if (user_.id_typeuser == "") { ModelState.AddModelError("typeus", "Không được để trống loại tài khoản"); } ViewBag.id_typeuser = new SelectList(db.TypeUsers, "id_typeuser", "name_typeuser", user_.id_typeuser); return(View(user_)); } var checkUserName = (from c in db.User_ where c.name_user == user_.name_user select c).ToList(); if (checkUserName.Count() != 0) { ModelState.AddModelError("RegisterError", "Tên tài khoản đã tổn tại!"); } if (ModelState.IsValid) { user_.password_user = GetMD5(user_.password_user); string sex = Request["sex"]; DateTime birthday = Convert.ToDateTime(Request["birthday"]); if (sex == "1") { user_.sex_user = "******"; } else if (sex == "2") { user_.sex_user = "******"; } else { user_.sex_user = "******"; } user_.birthday_user = birthday; user_.block_state_user = "******"; user_.registerdate_user = DateTime.Now; user_.avt_user = "******"; db.User_.Add(user_); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.id_typeuser = new SelectList(db.TypeUsers, "id_typeuser", "name_typeuser", user_.id_typeuser); return(View(user_)); }
public ActionResult MyAccount() { User_ user = db.User_.Where(x => x.UserName == User.Identity.Name).FirstOrDefault(); return(View(user)); }