public void ShouldReturnListOfResultsForParticularHunt() { List<huntparticipant> huntParticipants = new List<huntparticipant>(); user newUser = new user(); newUser.UserId = 1; newUser.Name = "Fake User"; huntparticipant participant = new huntparticipant(); participant.HuntId = 1; participant.UserId = 1; participant.HuntParticipantId = 1; participant.ElapsedTime = 1; participant.Tally = 1; huntParticipants.Add(participant); serviceClient.Setup(s => s.GetHuntParticipants(myFakeHunt)).Returns(huntParticipants.ToArray()); serviceClient.Setup(s => s.GetParticipantName(newUser.UserId)).Returns(newUser); viewModel.RefreshLeaderboard(); serviceClient.Verify(s => s.GetHuntParticipants(myFakeHunt), Times.Exactly(1)); serviceClient.Verify(s => s.GetParticipantName(newUser.UserId), Times.Exactly(1)); Participant newParticipant = new Participant(newUser.Name, participant.Tally, participant.ElapsedTime); ObservableCollection<Participant> participantsList = new ObservableCollection<Participant>(); participantsList.Add(newParticipant); //Values differ apparently but look the same to me. Needs checked again. Assert.AreEqual(participantsList, LeaderboardResults); #endregion }
/// <summary> /// username init /// </summary> /// <param name="userName">login - userName</param> public void Init(string userName, IRepository repository) { if (!string.IsNullOrEmpty(userName)) { User = repository.UserGetByLogin(userName); } }
protected void loginBtn_Click(object sender, EventArgs e) { if (Page.IsValid) { curUser = user.findUser(userInfoColl, usernameTxt.Text); if (user.ValidatePassword(passwordTxt.Text, curUser.Password) == true && curUser != null) { try { myDB.connectToBoardsDatabase(curUser); Session["myBoard"] = myBoard; Session["curUser"] = curUser; // Move to the MainPage Response.Redirect("~/elements.aspx"); } catch (Exception ex) { errorTxt.Text = ex.Message; } } else { errorTxt.Text = "Incorrect Username and/or Password."; } } }
public ActionResult register() { string name = Request.Form["name"]; string password = Request.Form["password"]; string passwordConfirm = Request.Form["confirmPassword"]; teethLabEntities db = new teethLabEntities(); if (db.users.Where(o => o.name == name).Count() > 0) { TempData["error"] = "الاسم موجود مسبقآ , رجاء اختيار اسم اخر"; return Redirect(Url.Action("viewRegister", "user")); } if (password != passwordConfirm) { TempData["error"] = "الرقم السري غير مطابق"; return Redirect(Url.Action("viewRegister", "user")); } user user = new user(); user.name = name; user.password = password; db.users.Add(user); db.SaveChanges(); TempData["error"] = "تمت الاضافه بنجاح"; return Redirect(Url.Action("viewRegister", "user")); }
private List<user> ParseUserPage(string html) { List<user> list = new List<user>(); HtmlDocument docNav = new HtmlDocument(); docNav.LoadHtml(html); XPathNavigator nav = docNav.CreateNavigator(); XPathNodeIterator i = nav.Select("//table[contains(@class, 'achievements') and contains(@class, 'real')]/tbody/tr"); while (i.MoveNext()) { user u = new user(); XPathNavigator node = i.Current.SelectSingleNode("./td[contains(@class, 'name')]"); if (node != null) u.account = node.Value.Trim(); node = i.Current.SelectSingleNode("./td[contains(@class, 'achievements')]/span/span[not(contains(@class, 'additional'))]"); if (node != null) int.TryParse(node.Value.Trim(), out u.ap); node = i.Current.SelectSingleNode("./td[contains(@class, 'achievements')]/span/span[contains(@class, 'additional')]"); if (node != null) u.lastapgain = node.Value.Remove(0, node.Value.IndexOf("Since") + 5).Replace("/", "/").Trim(); node = i.Current.SelectSingleNode("./td[contains(@class, 'world')]"); if (node != null) u.world = node.Value.Trim(); list.Add(u); } return list; }
// // GET: /Users/ public ActionResult Index() { DocsLinqDataContext doc_db = new DocsLinqDataContext(); int userID = Convert.ToInt32(Session["userID"]); user u = new user(); u = (from users in doc_db.users where users.userID.Equals(userID) select users).FirstOrDefault<user>(); ViewBag.u = u; // Get the states List<State> states = new List<State>(); states = (from s in doc_db.States orderby s.abbr select s).ToList<State>(); ViewBag.states = states; // Get the user's available modules List<module> modules = new List<module>(); modules = Users.GetUserModules(userID); ViewBag.Modules = modules; return View(); }
public bool authenticate(string n, string p, bool r) { bool rtn = false; string hp = ""; #region get user data DataTable dt = new DataTable(); try { using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["denpone"].ToString())) { using (MySqlCommand comm = new MySqlCommand("SELECT * FROM users WHERE uname = @n", conn)) { conn.Open(); comm.Parameters.AddWithValue("@n", n); //comm.Parameters.AddWithValue("@p", p); using (MySqlDataReader sdr = comm.ExecuteReader()) { dt.Load(sdr); } } } } catch (Exception ex) { logError("authenticate", ex); } #endregion #region Authenticate and fill session if (dt.Rows.Count == 1) { foreach (DataRow dr in dt.Rows) { hp = dr["pwd"].ToString(); bool v = BCrypt.Net.BCrypt.Verify(p, hp); if (v) { try { int uid = int.Parse(dr["user_id"].ToString()); user u = new user(); u.set_uname(dr["uname"].ToString()); u.set_uid(uid); //u.set_admin(adm); HttpContext.Current.Session["user"] = u; if (r) { writeCookie(uid); } rtn = true; } catch (Exception ex) { logError("authenticate/write cookie", ex); } } } } #endregion return rtn; }
public ActionResult CheckLoginUser(user u) { string user = u.username; string pass = u.password; if (user != null && pass != null) { using (db) { if (db.checkLoginUser(user, pass)) { var v = db.findLoginUser(user, pass); if (v != null) { Session["LogedUserID"] = v.username.ToString(); Session["LogedUserFullname"] = v.hoten.ToString(); Session["LogedUserImages"] = v.hinh.ToString(); return RedirectToAction("Index", "Product"); } } return RedirectToAction("Index", "Product"); } } return RedirectToAction("Index", "Product"); }
public UserForm(user u) { InitializeComponent(); ControlsUtil.SetBackColor(this.Controls); if (u == null) { u = new user(); btnInactive.Visible = false; IsNew = true; } NewPassword = u.password; if (u.inactive) { panelControl1.Enabled = false; btnInactive.Visible = false; btnSave.Visible = false; IsNew = false; } bdgUser.DataSource = u; //validations Validations.ValidatorCPFCNPJ vldCPF = new Validations.ValidatorCPFCNPJ() { ErrorText = "O CPF informado é inválido.", ErrorType = ErrorType.Warning }; validator.SetValidationRule(tfCPF, vldCPF); }
public string Build(user creds) { if (!new DatabaseCredentialsValidator(_DbContext).IsValid(creds)) { throw new AuthenticationException(); } long ID = _DbContext.users.Where(u => u.username.Equals(creds.username, StringComparison.CurrentCultureIgnoreCase)).ToList()[0].id; var UserTokenObj = _DbContext.Tokens.SingleOrDefault(x => x.user.id == ID); var token = BuildSecureToken(TokenSize); var user = _DbContext.users.SingleOrDefault(u => u.username.Equals(creds.username, StringComparison.CurrentCultureIgnoreCase)); if (UserTokenObj!=null) { //Update if Token Exist UserTokenObj.Tokenn = token; UserTokenObj.CreateDate = DateTime.Now; _DbContext.ObjectStateManager.ChangeObjectState(UserTokenObj, System.Data.EntityState.Modified); //_DbContext.Entry(UserTokenObj).State = System.Data.Entity.EntityState.Modified; _DbContext.SaveChanges(); } else { //Insert if Token Not Exist _DbContext.Tokens.AddObject(new Token { Tokenn = token, user = user, CreateDate = DateTime.Now }); _DbContext.SaveChanges(); } return token; }
protected void createAccBtn_Click(object sender, EventArgs e) { if (Page.IsValid) { if (passwordTxt.Text == cnfrmPassTxt.Text) { user newUser = new user(); newUser.Username = usernameTxt.Text; newUser.Password = user.HashPassword(passwordTxt.Text); newUser.Email = emailTxt.Text; newUser.Phone = phoneTxt.Text; if (user.checkUsername(userInfoColl, newUser).Count() == 0) { if (user.checkEmail(userInfoColl, newUser).Count() == 0) { myDB.insertUserInfoDoc(userInfoColl, newUser); Response.Redirect("~/login.aspx"); } else { errorTxt.Text = "Email is already in use."; } } else { errorTxt.Text = "Username is already taken."; } } else { errorTxt.Text = "Passwords do not match."; } } }
public ActionResult UserRegister(registerModel model) { if (ModelState.IsValid) { string passwordConvert = FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "SHA1"); user myUser = new user { email = model.UserName, password = passwordConvert }; try { db.users.AddObject(myUser); db.SaveChanges(); }catch{ ModelState.AddModelError("", "The User already exist, can't create the new user"); return View(model); } FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */); return RedirectToAction("MyToDo", "Todo"); } // If we got this far, something failed, redisplay form return View(model); }
public static IEnumerable<ticket> MyGroupsTickets(dbDataContext db, user usr) { IEnumerable<ticket> groupTix = from p in db.tickets where p.submitter != usr.id && (p.assigned_to_group == usr.sub_unit || p.originating_group == usr.sub_unit) && p.closed == DateTime.Parse("1/1/2001") select p; IEnumerable<ticket> ITix = ICommentedIn(db, usr.id); if (groupTix != null && ITix != null) return groupTix.Except(ITix).OrderByDescending(p => p.priority1.level).OrderBy(p => p.submitted); else return groupTix.OrderByDescending(p => p.priority1.level).OrderBy(p => p.submitted); }
public User(user entity) : this() { ModelObjectHelper.CopyObject(entity, this); this.UserImageLink = SiteSettings.GetProfileImagePath(this.image); this.gender = string.IsNullOrWhiteSpace(this.gender) ? "Male" : this.gender; this.LatLong = string.Format("{0},{1}", string.IsNullOrWhiteSpace(entity.latitude) ? "0" : entity.latitude, string.IsNullOrWhiteSpace(entity.longitude) ? "0" : entity.longitude); }
/// <summary> /// Generates a new password for a given user and e-mails them the new credentials. /// </summary> /// <param name="u">User object</param> /// <returns>True if e-mail was sent ::: False if we encountered an error.</returns> public static Boolean sendNewPass(user u) { // Get the user information DocsLinqDataContext doc_db = new DocsLinqDataContext(); user thisUser = (from users in doc_db.users where users.userID.Equals(u.userID) select users).FirstOrDefault<user>(); // Generate the new password PasswordGenerator pg = new PasswordGenerator(); string newPass = pg.Generate(); // Assign to user thisUser.password = newPass; try { // Attempt to committ the changes to the database // Save the changes doc_db.SubmitChanges(); // Attempt to send e-mail try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(); mail.To.Add(thisUser.email); mail.Subject = "CURT Documentation Account Recovery"; mail.IsBodyHtml = true; string htmlBody; htmlBody = "<div style='margin-top: 15px;font-family: Arial;font-size: 10pt;'>"; htmlBody += "<h4>Dear " + thisUser.fname + " " + thisUser.lname + ",</h4>"; htmlBody += "<p>There has been a password change for {"+thisUser.username+"}. You're new credentials for CURT Manufacturing Documentation are: </p>"; htmlBody += "<p style='margin:2px 0px'>Username: <strong>" + thisUser.username + "</strong></p>"; htmlBody += "<p style='margin:2px 0px'>Password: <strong>" + newPass + "</strong></p>"; htmlBody += "______________________________________________________________________"; htmlBody += "<p>If you feel this has been sent by mistake, please contact Web Support at <a href='mailto:[email protected]' target='_blank'>[email protected]</a>.</p>"; htmlBody += "<br /><span style='color:#999'>Thank you,</span>"; htmlBody += "<br /><br /><br />"; htmlBody += "<span style='line-height:75px;color:#999'>CURT Documentation Administrator</span>"; htmlBody += "</div>"; mail.Body = htmlBody; SmtpServer.Send(mail); } catch (Exception e) { Console.Write(e.Message); return false; } return true; } catch (ChangeConflictException e) { return false; } }
/// <summary> /// Add an user to settings /// </summary> /// <param name="newUser">the user</param> public static void AddUser(user newUser) { if (!String.IsNullOrEmpty(Properties.Settings.Default.users)) { Properties.Settings.Default.users = ";"; } Properties.Settings.Default.users = newUser.email + "," + newUser.password + "," + newUser.pop3 + "," + newUser.port.ToString() + "," + newUser.ssl.ToString(); Properties.Settings.Default.Save(); users.Add(newUser); }
public static void Add(dbDataContext db, string name, string email, string phone, int _sub_unit) { user newUser = new user(); newUser.userName = name; newUser.email = email; newUser.phone = phone; newUser.sub_unit = _sub_unit; db.users.InsertOnSubmit(newUser); db.SubmitChanges(); if (newUser.id == 1) newUser.is_admin = true; db.SubmitChanges(); }
public ResetCompanyPasswordViewModelTest() { serviceClient = new Mock<ITreasureHuntService>(); viewModel = new ResetCompanyPasswordViewModel(serviceClient.Object); currentUser = new user(); currentUser.UserId = 1; currentUser.Name = "Emma"; currentUser.Password = "******"; CurrentUser = currentUser; }
public ErrorMessage Delete() { if (currentUser == null) return ErrorMessage.ERROR; else { db.user.DeleteOnSubmit(currentUser); Submit(); currentUser = null; return ErrorMessage.OK; } }
/// <summary> /// 重写基类在Action之前执行的方法 /// </summary> /// <param name="filterContext"></param> protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); ////--------- //Session["User"] = new user() { nickname = "火骑士空空", UserGuid = "75df2a84e26c427c9336b26a5eb65170", openid = "olzRYwMvBIsLngr0Wtze2b_zOJkI" }; //temp.OpenId = "ov1YDs8pD1jFg026SGrr6V7ZAa8Q"; //------------- CurrentUserInfo = Session["User"] as user; // //检验用户是否已经登录,如果登录则不执行,否则则执行下面的跳转代码 if (CurrentUserInfo == null || CurrentUserInfo.UserGuid == null) { var myHeader = Request.Headers; if (myHeader["X-Requested-With"] != null) { //myHeader["session-expired"] = "expired"; Response.Headers.Add("session-expired", "expired"); //X-AspNetMvc-Version: 4.0 //Server: Microsoft-IIS/8.0 //X-AspNet-Version: 4.0.30319 //X-Powered-By: ASP.NET HttpContext.ApplicationInstance.CompleteRequest(); } else { //Response.Redirect("/home/activity"); Response.Write("should sign!"); } Response.End(); return; } //if (string.IsNullOrEmpty(CurrentUserInfo.OpenId))//如果在微信上就把条件改成phone==string.Empty或string.IsNullOrEmpty(phone); //{ // var myHeader = Request.Headers; // if (!string.IsNullOrEmpty(Request["x-requested-with"])) // { // Response.Write("..."); // Response.End(); // return; // } // else // { // Response.Redirect("/sign/Register"); // } // Response.Redirect("/Sign/Register"); // return; //} }
public user getCurrentUser() { IdentityHelper helper = new IdentityHelper(); string currentDomain = Domain.GetCurrentDomain().Name; user currentUser = null; currentUser = new user(); currentUser.lanID = HttpContext.Current.User.Identity.Name; currentUser.name = helper.GetUserDisplayName(HttpContext.Current.User.Identity.Name); return currentUser; }
private void button1_Click(object sender, EventArgs e) { string login = textBox1.Text.ToLower(); string password = textBox2.Text; user tmp = new user(login, password); int lvl = tmp.isUser(); if ((lvl > -1) && (lvl < 3)) { Objects objects = new Objects(lvl); objects.Show(); this.Hide(); } else MessageBox.Show("Данного пользователя нет в системе"); }
//static List<Room> roomsWiseUser = new List<Room>(); public string Login(string name) { //FormsAuthentication.SetAuthCookie(Context.ConnectionId, false); var a = HttpContext.Current.User.Identity.Name; var user = new user { name = name, ConnectionId = Context.ConnectionId, ContextName =a,age = 20, avator = "", id = 1, sex = "Male", memberType = "Re+gistered", fontColor = "red", status = Status.Online.ToString() }; Clients.Caller.rooms(Rooms.ToArray()); Clients.Caller.setInitial(Context.ConnectionId, name); var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); string sJSON = oSerializer.Serialize(loggedInUsers); loggedInUsers.Add(user); Clients.Caller.getOnlineUsers(sJSON); Clients.Others.newOnlineUser(user); return name; }
/// <summary> /// Get instance of 'user' class used in Activity service /// </summary> /// <returns></returns> public static user GetActivityUser() { user userObj = new user(); string now = DateTime.Now.ToString("O"); userObj.login = RightNowConfigService.GetConfigValue(RightNowConfigKeyNames.UserName); userObj.company = RightNowConfigService.GetConfigValue(RightNowConfigKeyNames.CompanyName); var password = RightNowConfigService.GetConfigValue(RightNowConfigKeyNames.Password); userObj.now = now; userObj.auth_string = ToaMD5HashUtil.AuthString(now, password); return userObj; }
public void Create_User() { var u = new user(); u.administrator = false; u.alias = "danielovich"; u.email = "*****@*****.**"; u.logins = 1; u.password = "******"; var en = _service.Create( u ); Assert.IsTrue( en == UserCreationStatus.email_exists ); Assert.IsNotNull( _service.Get( u.alias ) ); }
protected void Page_Load(object sender, EventArgs e) { curUser = (user)Session["curUser"]; if (curUser.Account_Type == "designer") { accountTypeLink.InnerText = "Designer"; accountTypeLink.HRef = "designer.aspx"; } else { accountTypeLink.InnerText = "Maps"; accountTypeLink.HRef = "maps.aspx"; } }
public void GetUser(string username = "", string password = "") { user u = new user { username = username, password = password }; try { string json = u.GetUser(); Response.ContentType = "application/json"; Response.Write(json); Response.End(); } catch (Exception e) { throwError(e.Message); } }
public ActionResult Index(user user, string userBirth) { var userSession = (user)Session["user"]; user.email = userSession.email; DateTime newBirthDate = Convert.ToDateTime(userBirth); UserPanel modelPanel = new UserPanel(); using (var db = new HotelDBEntities()) { user currentUser = db.users.FirstOrDefault(u => u.email == user.email); if (String.IsNullOrEmpty(user.name) || String.IsNullOrEmpty(user.surname)) { modelPanel.user = currentUser; modelPanel.info.type = 0; modelPanel.info.text = "You didn't fill name or surname, please fill those fields."; return View(modelPanel); } if (!(String.IsNullOrEmpty(user.password)) && (user.password.Length > 10 || user.password.Length < 6)) { modelPanel.user = currentUser; modelPanel.info.type = 0; modelPanel.info.text = "Password must be between 6 and 10 characters."; return View(modelPanel); } if (!(String.IsNullOrEmpty(user.password)) && (user.password.Length < 10 || user.password.Length > 6)) { var crypto = new SimpleCrypto.PBKDF2(); var encrPass = crypto.Compute(user.password); currentUser.password = encrPass; currentUser.password_salt = crypto.Salt; } currentUser.name = user.name; currentUser.surname = user.surname; currentUser.country = user.country; currentUser.birth_date = newBirthDate; db.users.Attach(currentUser); db.Entry(currentUser).Property(p => p.password).IsModified = true; db.Entry(currentUser).Property(p => p.password_salt).IsModified = true; db.Entry(currentUser).Property(p => p.name).IsModified = true; db.Entry(currentUser).Property(p => p.surname).IsModified = true; db.Entry(currentUser).Property(p => p.country).IsModified = true; db.Entry(currentUser).Property(p => p.birth_date).IsModified = true; db.SaveChanges(); modelPanel.user = currentUser; modelPanel.info.type = 1; modelPanel.info.text = "Your data has been changed."; return View(modelPanel); } }
/// <summary> /// Add users to the user list from settings /// </summary> public static void GetUsersFromSettings() { string[] allSavedUsers = Properties.Settings.Default.users.Split(';'); foreach (string savedUser in allSavedUsers) { if (String.IsNullOrEmpty(savedUser)) { break; } string[] savedUserArr = savedUser.Split(','); user _user = new user(); _user.email = savedUserArr[0]; _user.password = savedUserArr[1]; _user.pop3 = savedUserArr[2]; _user.port = int.Parse(savedUserArr[3]); _user.ssl = bool.Parse(savedUserArr[4]); users.Add(_user); } }
public ActionResult Forgot(string username, string email) { DocsLinqDataContext doc_db = new DocsLinqDataContext(); if (username.Trim().Length != 0) { // Instantiate the user object and assign user user u = new user(); u = (from users in doc_db.users where users.username.Equals(username.Trim()) select users).FirstOrDefault(); if (u != null) { // Make sure we found a user if (AuthenticateUser.sendNewPass(u)) { // Attempt to send updated e-mail HttpContext.Response.Redirect("~/Authenticate/userFound"); } else { ViewBag.Message = "We were unable to locate " + username.Trim() + " in our system"; } } else { ViewBag.Message = "We were unable to locate " + username.Trim() + " in our system."; } } else if (email.Trim().Length != 0) { // Instantiate our user object and populate from database user u = new user(); u = (from users in doc_db.users where users.email.Equals(email.Trim()) select users).FirstOrDefault(); if (u != null) { // Make sure we found a user if (AuthenticateUser.sendNewPass(u)) { // Attempt to send update e-mail HttpContext.Response.Redirect("~/Authenticate/userFound"); } else { ViewBag.Message = "We were unable to locate " + email.Trim() + " in our system."; } } else { ViewBag.Message = "We were unable to locate " + email.Trim() + " in our system."; } } else { // Both username and email were blank ViewBag.Message = "You did not enter a username or e-mail address"; } return View("Forgot"); }
public Tuple <bool, Int32> AddUser(user objuser) { return(InstallUserDAL.Instance.AddIntsallUser(objuser)); }
public void UpdateProspect(user objuser) { InstallUserDAL.Instance.UpdateProspect(objuser); }
public ActionResult listado(string Error, string searchStr = "", int idCategory = 0) { if (Session["USER_ID"] != null) { long userId = (long)Session["USER_ID"]; user curUser = entities.users.Find(userId); List <ShowMessage> pubMessageList = ep.GetChatMessages(userId); List <document> document_list = new List <document>(); long communityAct = Convert.ToInt64(Session["CURRENT_COMU"]); Dictionary <long, string> categoryDict = new Dictionary <long, string>(); if (searchStr == "" && idCategory == 0) { var query = (from r in entities.documents where r.community_id == communityAct select r); document_list = query.ToList(); } else if (searchStr != "" && idCategory == 0) { var query1 = (from r in entities.documents where r.first_name.Contains(searchStr) == true && r.community_id == communityAct select r); document_list = query1.ToList(); } else if (searchStr == "" && idCategory != 0) { var query2 = (from r in entities.documents where r.document_type.id == idCategory && r.community_id == communityAct select r ); document_list = query2.ToList(); } else { var query3 = (from r in entities.documents where r.first_name.Contains(searchStr) == true && r.document_type.id == idCategory && r.community_id == communityAct select r); document_list = query3.ToList(); } List <document_type> document_category_list = entities.document_type.Where(x => x.community_id == communityAct).ToList(); documentosViewModel viewModel = new documentosViewModel(); communityList = ep.GetCommunityList(userId); viewModel.communityList = communityList; document_type document_type = entities.document_type.Find(idCategory); viewModel.side_menu = "documentos"; if (idCategory != 0) { viewModel.side_sub_menu = "documentos_" + document_type.type_name; } else { viewModel.side_sub_menu = "documentos_listado"; } viewModel.document_category_list = document_category_list; viewModel.document_list = document_list; viewModel.searchStr = searchStr; viewModel.typeID = idCategory; viewModel.curUser = curUser; viewModel.pubTaskList = ep.GetNotifiTaskList(userId); viewModel.pubMessageList = pubMessageList; viewModel.messageCount = ep.GetUnreadMessageCount(pubMessageList); ViewBag.msgError = Error; return(View(viewModel)); } else { return(Redirect(ep.GetLogoutUrl())); } }
public Student_Form(user u) { InitializeComponent(); this.u = u; }
public bool Add_and_Edit_Customer(customer customer, List <Model.Friend> list_friend, int action_status, user user) { bool check = false; try { if (Util.Cnv_Int(customer.id.ToString()) > -1 && action_status != Variable.action_status.is_add) { customer data_edit = new customer(); data_edit = Get_Customer(customer.id); if (action_status == Variable.action_status.is_update) { // update data data_edit.Address = customer.Address; data_edit.BirthDay = customer.BirthDay; data_edit.FullName = customer.FullName; data_edit.IdCard = customer.IdCard; data_edit.PhoneNumber = customer.PhoneNumber; data_edit.Sex = customer.Sex; data_edit.FamilyPhoneNumber = customer.FamilyPhoneNumber; data_edit.CategoryId = customer.CategoryId; data_edit.Money = customer.Money; data_edit.Note = customer.Note; data_edit.UpdatedAt = DateTime.Now; data_edit.UpdatedBy = user.id; data_edit.cycle = customer.cycle; } else if (action_status == Variable.action_status.is_delete) // delete data { data_edit.Status = false; } } else { _db.customers.Add(customer); // add data } _db.SaveChanges(); int IdCustomer = customer.id; if (action_status == Variable.action_status.is_add && !add_friend(list_friend, user, IdCustomer)) { check = false; } check = true; } catch (Exception) { return(check); } return(check); }
public IResult addUser(user user) { _user.add(user); return(new SuccessResult(bllMessages.userAdded, true)); }
public IResult deleteUserByEntity(user user) { _user.delete(user); return(new SuccessResult(bllMessages.userDeleted, true)); }
public void Update(string id, user User) => _users.ReplaceOne(u => u.UserName == id, User);
public user Create(user User) { _users.InsertOne(User); return(User); }
//get project_case details with company info public ActionResult Get(int id = 0) { if (id > 0) { project_case proj = Uof.Iproject_caseService.GetById(id); if (proj != null) { company company = proj.company; if (company != null) { user _user = company.user; if (_user != null) { var comobj = new { id = company.Id, name = company.name, logo_path = company.logo_path, mobile = _user.mobile, phone = _user.phone, address = company.address, company_phone = company.company_phone }; string user_name = ""; if (proj.user == null) { user_name = _user.real_name; } else { user_name = proj.user.real_name; } var obj = new { id = proj.Id, title = proj.title, descript = proj.descript, project_contact_phone = proj.project_contact_phone, project_address = proj.project_address, project_action_company = proj.project_action_company, project_design_company = proj.project_design_company, project_type = proj.project_type, project_name = proj.project_name, project_area = proj.project_area, product_metal = proj.product_metal, product_ruler = proj.product_ruler, product_cence = proj.product_cence, product_price = proj.product_price, product_address = proj.product_address, is_product = proj.is_product, type_name = proj.sys_dictionary == null ? "" : proj.sys_dictionary.value, type_id = proj.sys_dictionary == null ? "0" : proj.sys_dictionary.id.ToString(), update_time = proj.update_time.GetValueOrDefault(DateTime.Now).ToString("yy-MM-dd"), content = proj.content, main_image_path = proj.main_image_path, user_name = user_name, company = comobj }; return(Json(obj, JsonRequestBehavior.AllowGet)); } else { var obj = new { id = proj.Id, title = proj.title, descript = proj.descript, project_contact_phone = proj.project_contact_phone, project_address = proj.project_address, project_action_company = proj.project_action_company, project_design_company = proj.project_design_company, project_type = proj.project_type, project_name = proj.project_name, project_area = proj.project_area, product_metal = proj.product_metal, product_ruler = proj.product_ruler, product_cence = proj.product_cence, product_price = proj.product_price, product_address = proj.product_address, is_product = proj.is_product, type_name = proj.sys_dictionary == null ? "" : proj.sys_dictionary.value, type_id = proj.sys_dictionary == null ? "0" : proj.sys_dictionary.id.ToString(), update_time = proj.update_time.GetValueOrDefault(DateTime.Now).ToString("yy-MM-dd"), content = proj.content, main_image_path = proj.main_image_path, user_name = proj.user == null ? "" : proj.user.real_name, company = new { id = company.Id, name = company.name, logo_path = company.logo_path, mobile = "", phone = "", address = company.address, company_phone = company.company_phone } }; return(Json(obj, JsonRequestBehavior.AllowGet)); } } else { var obj = new { id = proj.Id, title = proj.title, descript = proj.descript, type_name = proj.sys_dictionary == null ? "" : proj.sys_dictionary.value, content = proj.content, main_image_path = proj.main_image_path, user_name = proj.user == null ? "" : proj.user.real_name, project_contact_phone = proj.project_contact_phone, project_address = proj.project_address, project_action_company = proj.project_action_company, project_design_company = proj.project_design_company, project_type = proj.project_type, project_name = proj.project_name, project_area = proj.project_area, product_metal = proj.product_metal, product_ruler = proj.product_ruler, product_cence = proj.product_cence, product_price = proj.product_price, product_address = proj.product_address, type_id = proj.sys_dictionary == null ? "0" : proj.sys_dictionary.id.ToString(), update_time = proj.update_time.GetValueOrDefault(DateTime.Now).ToString("yy-MM-dd"), is_product = proj.is_product, company = new { id = "", name = "", logo_path = "", mobile = "", phone = "", address = "" } }; return(Json(obj, JsonRequestBehavior.AllowGet)); } } } return(Json(new { result = false }, JsonRequestBehavior.AllowGet)); }
protected void btnsubmit_Click(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies["rowenref"]; //declaration of cookie user Usrs = db.users.First(u => u.username == cookie["username"]); //retrieve uer id string password = clssEncryptsecurity.psDescrypt(Usrs.password); //show password string Id = Request.QueryString["id"]; string Profilepic = Usrs.Image.ToString(); if (fileuserimage.PostedFile == null) { if (Profilepic == null) { db.sp_UPDATE_tbl_userInfo(Convert.ToInt16(Usrs.id), cookie["username"], clssEncryptsecurity.psEncrypt(password), txtfname.Text, txtlname.Text, txtemail.Text, dropgender.Text, txtmname.Text, txtaddress.Text, null); Label1.Text = "<div class='ok'>Update user info Successful</div>"; MultiView2.ActiveViewIndex = 0; } else { db.sp_UPDATE_tbl_userInfo(Convert.ToInt16(Usrs.id), cookie["username"], clssEncryptsecurity.psEncrypt(password), txtfname.Text, txtlname.Text, txtemail.Text, dropgender.Text, txtmname.Text, txtaddress.Text, Usrs.Image); Label1.Text = "<div class='ok'>Update user info Successful</div>"; MultiView2.ActiveViewIndex = 0; } } else { if (fileuserimage.PostedFile != null) { string sub = string.Empty, imagePath = string.Empty, imgFilename = string.Empty; // Check that there is a file if (fileuserimage.PostedFile != null) { //Path to store uploaded files on server - make sure your paths are unique string filePath = "../profilepic/oreginal/" + txtusername.Text + ".jpg"; string thumbPath = "../profilepic/thumb/" + txtusername.Text + ".jpg"; // Check file size (mustn’t be 0) HttpPostedFile myFile = fileuserimage.PostedFile; int nFileLen = myFile.ContentLength; if ((nFileLen > 0) && (System.IO.Path.GetExtension(myFile.FileName).ToLower() == ".jpg")) { // Read file into a data stream byte[] myData = new Byte[nFileLen]; myFile.InputStream.Read(myData, 0, nFileLen); myFile.InputStream.Dispose(); // Save the stream to disk as temporary file. make sure the path is unique! System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(filePath + "_temp.jpg"), System.IO.FileMode.Create); newFile.Write(myData, 0, myData.Length); // run ALL the image optimisations you want here..... make sure your paths are unique // you can use these booleans later if you need the results for your own labels or so. // dont call the function after the file has been closed. bool success = ResizeImageAndUpload(newFile, thumbPath, 300, 300); success = ResizeImageAndUpload(newFile, filePath, 1200, 900); // tidy up and delete the temp file. newFile.Close(); System.IO.File.Delete(Server.MapPath(filePath + "_temp.jpg")); } imgFilename = Path.GetFileName(thumbPath); Stream imgdatastream = fileuserimage.PostedFile.InputStream; int imgdatalen = fileuserimage.PostedFile.ContentLength; byte[] imgdata = new byte[imgdatalen]; int n = imgdatastream.Read(imgdata, 0, imgdatalen); db.sp_UPDATE_tbl_userInfo(Convert.ToInt16(Usrs.id), cookie["username"], clssEncryptsecurity.psEncrypt(password), txtfname.Text, txtlname.Text, txtemail.Text, dropgender.Text, txtmname.Text, txtaddress.Text, imgFilename); Label1.Text = "<div class='ok'>Update user info Successful</div>"; MultiView2.ActiveViewIndex = 0; Response.Redirect("account.aspx"); } } } }
public void set() { //site name sitename Sitnme = db.sitenames.First(); lbl_sitename.Text = Sitnme.title.ToString();//call sitename lblfootertitle.Text = Sitnme.title.ToString(); Page.Title = string.Format(Sitnme.title.ToString()); HttpCookie cookie = Request.Cookies["rowenref"];// declaration cookie if (cookie == null)//if cookie null { int ID = 4; soption options = db.soptions.First(use => use.id == ID);//call soption db var mnu = from p in db.menus where p.menu_type == ID orderby p.menu_id ascending select p; listmenu.DataSource = mnu; listmenu.DataBind(); var mnuvisible = from p in db.menus where p.status == 15 orderby p.menu_id ascending select p; listmenu.DataSource = mnuvisible; listmenu.DataBind(); lnklogin.Visible = true; lblSignUp.Visible = true; } else { cookie.Expires = DateTime.Now.AddMinutes(30); Response.Cookies.Add(cookie); user User = db.users.First(aa => aa.id == Convert.ToInt16(cookie["userid"])); lbluser.Text = "<li class='dropdown'><a href='#' class='dropdown-toggle' data-toggle='dropdown'>" + "Hi " + User.username + "<b class='caret'></b></a>" + "<ul class='dropdown-menu'>" + "<li><a href='account.aspx'>My Account</a></li>" + "<li><a href='logout.aspx'>Logout</a></li>" + "</ul></li>"; lnklogin.Visible = false; lblSignUp.Visible = false; if (cookie["usertype"] == "4") { var mnuvisible = from p in db.menus where p.status == 15 orderby p.menu_id ascending select p; listmenu.DataSource = mnuvisible; listmenu.DataBind(); } //acount type "admin" else if (cookie["perms"] == "3") { var mnuvisible = from p in db.menus where p.status == 15 orderby p.menu_id ascending select p; listmenu.DataSource = mnuvisible; listmenu.DataBind(); lbladmin.Visible = true; soption optiontab = db.soptions.First(use => use.id == 3); lbladmin.Text = "<li><a href='admin.aspx'>" + optiontab.name + "</a></li>"; } else if (cookie["perms"] == "5") { var mnuvisible = from p in db.menus where p.status == 15 orderby p.menu_id ascending select p; listmenu.DataSource = mnuvisible; listmenu.DataBind(); lbladmin.Visible = true; soption optiontab = db.soptions.First(use => use.id == 5); lbladmin.Text = "<li><a href='admin.aspx'>" + optiontab.name + "</a></li>"; } } }
public void insertUser(user user) { context.user.Add(user); context.SaveChanges(); }
public DataSet QuickSaveUserWithEmailorPhone(user objInstallUser) { return(InstallUserDAL.Instance.QuickSaveUserWithEmailorPhone(objInstallUser)); }
protected void Page_Load(object sender, EventArgs e) { if (Session["AdminLogin"] != null) { Response.Redirect("/Admin/NavigationTest.aspx", false); } string str = Request.QueryString["Action"]; if (!string.IsNullOrEmpty(str)) { if (str.ToLower() == "login") { string drag_hk = Request.Form["drag_hk"]; string pid = Request.Form["TxbPid"]; string pwd = Request.Form["TxbPwd"]; //pwd= MD5pwd.MD5zsgc.MD5Entry(pwd); string clientIp = Request.UserHostAddress; string sql = ""; sql = "select user_pwd from admin where User_Name='" + pid + "'"; string sql_pwd = SqlFunction.Sql_ReturnNumberES(sql); if (sql_pwd == "") { Response.Write("<script Language=\"javascript\">alert(\"帐号错误!\");</script>"); } else { user ua = new user(); DataSet ds = new DataSet(); ds = SqlFunction.Sql_DataAdapterToDS("select * from admin where User_Name='" + pid + "'"); ua.state = Convert.ToInt32(ds.Tables[0].Rows[0][5]); if (ua.state != 1) { Response.Write("<script Language=\"javascript\">alert(\"您的帐号权限异常!\");</script>"); } else { if (sql_pwd == pwd) { Session["AdminLogin"] = pid + "|" + pwd; ua.id = Convert.ToInt32(ds.Tables[0].Rows[0][0]); ua.name = ds.Tables[0].Rows[0][1].ToString(); ua.pwd = ds.Tables[0].Rows[0][2].ToString(); ua.email = ds.Tables[0].Rows[0][3].ToString(); ua.phone = ds.Tables[0].Rows[0][4].ToString(); ua.add = Convert.ToInt32(ds.Tables[0].Rows[0][6]); ua.update = Convert.ToInt32(ds.Tables[0].Rows[0][7]); ua.select = Convert.ToInt32(ds.Tables[0].Rows[0][8]); ua.delete = Convert.ToInt32(ds.Tables[0].Rows[0][9]); ua.register = Convert.ToInt32(ds.Tables[0].Rows[0][10]); ua.export = Convert.ToInt32(ds.Tables[0].Rows[0][11]); Session["Adminu"] = ua; Response.Redirect("/Admin/NavigationTest.aspx", false); } else { Response.Write("<script>alert(\"密码错误!\");</script>"); } } } } } }
public int QuickSaveInstallUser(user objInstallUser) { return(InstallUserDAL.Instance.QuickSaveInstallUser(objInstallUser)); }
public ActionResult pagos(string searchString = "", int searchState = -1) { if (Session["USER_ID"] != null) { try { bool state = false; long communityAct = Convert.ToInt64(Session["CURRENT_COMU"]); if (searchState == 1) { state = true; } else if (searchState == 0) { state = false; } long userId = (long)Session["USER_ID"]; user curUser = entities.users.Find(userId); List <payment> paymentList = new List <payment>(); if (searchState != -1) { if (searchString != "") { paymentList = entities.payments.Where(m => m.first_name.Contains(searchString) == true && m.state == state).ToList(); } else { paymentList = entities.payments.Where(m => m.state == state).ToList(); } } else { if (searchString != "") { paymentList = entities.payments.Where(m => m.first_name.Contains(searchString) == true).ToList(); } else { paymentList = entities.payments.ToList(); } } List <ShowMessage> pubMessageList = ep.GetChatMessages(userId); pagosCuotasViewModel viewModel = new pagosCuotasViewModel(); communityList = ep.GetCommunityList(userId); viewModel.communityList = communityList; viewModel.side_menu = "cuotas"; viewModel.side_sub_menu = "cuotas_pagos"; viewModel.document_category_list = entities.document_type.Where(x => x.community_id == communityAct).ToList(); viewModel.curUser = curUser; viewModel.pubTaskList = ep.GetNotifiTaskList(userId); viewModel.pubMessageList = pubMessageList; viewModel.messageCount = ep.GetUnreadMessageCount(pubMessageList); viewModel.paymentList = paymentList; viewModel.searchString = searchString; viewModel.searchState = searchState; return(View(viewModel)); } catch (Exception ex) { return(Redirect(Url.Action("Index", "Error"))); } } else { return(Redirect(ep.GetLogoutUrl())); } }
public IList <lesson> GetLessonsByUser(user user) { return(_lessonRepository.GetLessonsByUser(user)); }
public void GetObjectsBack() { try { var context = new AutoTestDataContextNonTrackerEnabled(); // Arrange. // Add a user. var user = new user() { name = "user1" }; // Add a location with that userId. var location = new location() { name = "location1", user = user }; // Add a facility with that locationId. var facility = new facility() { name = "facility1", facilityType = "Commercial", location = location }; var facilityRepository = new Repository <facility>(context); var facilityService = new Service <facility>(facilityRepository); facilityService.Add(facility, "xingl"); var facilityODataController = new ODataApiController <facility>(facilityService); facility.name = "facility1x"; // Act. var result = facilityODataController.Get(); // Assert. Assert.IsTrue(result != null); var posRes = ((System.Web.Http.Results.OkNegotiatedContentResult <System.Linq.IQueryable <AutoClutch.Test.Data.facility> >)result).Content; Assert.AreEqual(1, posRes.Count()); } finally { // Clean up database. var context = new AutoTestDataContextNonTrackerEnabled(); context.users.RemoveRange(context.users.ToList()); context.locations.RemoveRange(context.locations.ToList()); context.facilities.RemoveRange(context.facilities.ToList()); context.SaveChanges(); var context2 = new AutoTestDataContext(); context2.LogDetails.RemoveRange(context2.LogDetails.ToList()); context2.AuditLog.RemoveRange(context2.AuditLog.ToList()); context2.SaveChanges(); } }
partial void Deleteuser(user instance);
await newPlayerTryJoin(user, game);
public ActionResult regUser(user u) { if (u != null) { reflectModel.setValues(u); if (Tools.getStrLength(u.nick_name) < 3) { return(Content("用户名的长度必须大于3个字符")); } if (u.pwd.Length < 6) { return(Content("密码必须大于6个字符")); } if (!Tools.IsEmail(u.email)) { return(Content("邮箱格式不正确")); } u.pwd = HashTools.SHA1_Hash(u.pwd); DateTime dt = DateTime.Now; u.reg_date = dt; u.state = 1; int res = 0; try { TransactionOptions transactionOption = new TransactionOptions(); //设置事务隔离级别 transactionOption.IsolationLevel = IsolationLevel.ReadCommitted; // 设置事务超时时间为60秒 transactionOption.Timeout = new TimeSpan(0, 0, 60); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, transactionOption)) { using (WeiQingEntities db = new WeiQingEntities()) { var count = db.user.Where(p => p.nick_name.Equals(u.nick_name) || p.email.Equals(u.email)).Count(); if (count > 0) { return(Content("此用户名或者邮箱已被注册")); } u.is_admin = false; db.user.Add(u); res = db.SaveChanges(); // 创建用户 if (res == 0) { return(Content("注册失败")); } var user = db.user.Where(p => p.nick_name.Equals(u.nick_name)).FirstOrDefault(); string ip = Tools.GetRealIP(); login_log log = new login_log() { uid = (int)user.id, login_ip = ip, login_time = dt }; db.login_log.Add(log); res = db.SaveChanges(); if (res > 0) { Session["user"] = user; scope.Complete(); } else { return(Content("保存登录记录时出现异常")); } return(Content(res.ToString())); } } } catch (Exception ex) { return(Content("后台出现错误")); } } return(Content("没有获取到数据")); }
public ActionResult editar(long?editID) { if (Session["USER_ID"] != null) { if (Session["CURRENT_COMU"] != null) { if (editID != null) { try { long userId = (long)Session["USER_ID"]; fee feeItem = entities.fees.Where(m => m.id == editID).FirstOrDefault(); if (feeItem != null) { long communityAct = Convert.ToInt64(Session["CURRENT_COMU"]); user curUser = entities.users.Find(userId); List <bank> bankList = entities.banks.Where(m => m.user_id == userId).ToList(); List <ShowMessage> pubMessageList = ep.GetChatMessages(userId); agregarCuotasViewModel viewModel = new agregarCuotasViewModel(); communityList = ep.GetCommunityList(userId); viewModel.communityList = communityList; viewModel.side_menu = "cuotas"; viewModel.side_sub_menu = "cuotas_editar"; viewModel.document_category_list = entities.document_type.Where(x => x.community_id == communityAct).ToList(); viewModel.curUser = curUser; viewModel.pubTaskList = ep.GetNotifiTaskList(userId); viewModel.pubMessageList = pubMessageList; viewModel.messageCount = ep.GetUnreadMessageCount(pubMessageList); viewModel.feedId = Convert.ToInt64(editID); viewModel.bankList = bankList; viewModel.feeName = feeItem.name; viewModel.cost = feeItem.cost; viewModel.taxCharge = feeItem.tax_charge; viewModel.penalty = feeItem.penalty; viewModel.merchantAccount = feeItem.merchant_account; viewModel.bankId = feeItem.bank_id; return(View(viewModel)); } else { return(Redirect(Url.Action("listado", "cuotas", new { area = "coadmin", Error = "No existe ese elemento" }))); } } catch (Exception ex) { return(Redirect(Url.Action("Index", "Error"))); } } else { return(Redirect(Url.Action("NotFound", "Error"))); } } else { return(Redirect(Url.Action("listado", "cuotas", new { area = "coadmin", Error = "No puede editar cuotas. Usted no administra ninguna comunidad. Comuníquese con el Webmaster..." }))); } } else { return(Redirect(ep.GetLogoutUrl())); } }
public ActionResult listadoCategoria(string Error, string searchStr = "") { if (Session["USER_ID"] != null) { try { long userId = (long)Session["USER_ID"]; long communityAct = Convert.ToInt64(Session["CURRENT_COMU"]); user curUser = entities.users.Find(userId); List <ShowMessage> pubMessageList = ep.GetChatMessages(userId); List <document_type> document_category_list = new List <document_type>(); if (searchStr == "") { var query = (from r in entities.document_type where r.community_id == communityAct select r); document_category_list = query.ToList(); } else if (searchStr != "") { var query1 = (from r in entities.document_type where r.type_name.Contains(searchStr) == true && r.community_id == communityAct select r); document_category_list = query1.ToList(); } List <DocumentTypeItemViewModel> documentTypeItemList = new List <DocumentTypeItemViewModel>(); foreach (var item in document_category_list) { int ID = item.id; DocumentTypeItemViewModel itemViewModel = new DocumentTypeItemViewModel(); itemViewModel.ID = ID; itemViewModel.DocumentTypeName = item.type_name; itemViewModel.Documents = entities.documents.Where(m => m.type_id == ID && m.community_id == communityAct).ToList().Count; itemViewModel.Share = (int)item.share; documentTypeItemList.Add(itemViewModel); } categoriaViewModel viewModel = new categoriaViewModel(); communityList = ep.GetCommunityList(userId); viewModel.communityList = communityList; viewModel.searchStr = searchStr; viewModel.side_menu = "documentos"; viewModel.side_sub_menu = "documentos_categoria"; viewModel.document_category_list = document_category_list; viewModel.categoryList = entities.categories.ToList(); viewModel.curUser = curUser; viewModel.pubTaskList = ep.GetNotifiTaskList(userId); viewModel.pubMessageList = pubMessageList; viewModel.messageCount = ep.GetUnreadMessageCount(pubMessageList); viewModel.documentTypeItemList = documentTypeItemList; ViewBag.msgError = Error; return(View(viewModel)); } catch (Exception ex) { return(Redirect(Url.Action("error", "control", new { area = "coadmin", Error = "Listado Categorías: " + ex.Message }))); } } else { return(Redirect(ep.GetLogoutUrl())); } }
public bool UpdateInstallUser(user objuser, int id, int loggedInUserId) { return(InstallUserDAL.Instance.UpdateInstallUser(objuser, id, loggedInUserId)); }
partial void Updateuser(user instance);
public void Remove(user User) => _users.DeleteOne(wo => wo.UserName == User.UserName);
public Boolean UpdateUserProfile(user objuser) { return(InstallUserDAL.Instance.UpdateUserProfile(objuser)); }
partial void Insertuser(user instance);
public bool UpdateConfirmInstallUser(user objuser) { return(InstallUserDAL.Instance.UpdateConfirmInstallUser(objuser)); }