public SnitzMembershipUser(MembershipUser mu, int posts,string country) { this.mu = mu; Posts = posts; Title = mu.Comment; Country = country; }
private void sendMail(MembershipUser user) { MailMessage mailMessage = new MailMessage(); mailMessage.From = new MailAddress("*****@*****.**"); mailMessage.Subject = "Welcome To Tom's List"; mailMessage.To.Add(new MailAddress(user.Email)); Guid userId = (Guid)user.ProviderUserKey; string body = ""; using (StreamReader reader = new StreamReader(Server.MapPath("~/Templates/NewAccountTemplate.html"))) { body = reader.ReadToEnd(); } body = body.Replace("<%UserName%>", user.UserName); string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + (Request.ApplicationPath.Equals("/") ? "" : Request.ApplicationPath); string verifyUrl = "/Views/AccountVerify.aspx?ID=" + userId.ToString(); body = body.Replace("<%VerifyUrl%>", baseUrl + verifyUrl); mailMessage.Body = body; mailMessage.IsBodyHtml = true; new SmtpClient().Send(mailMessage); }
protected void Page_Load(object sender, EventArgs e) { user = Membership.GetUser(); if (user != null) userName = user.UserName; if (Request.Params.AllKeys.Contains<string>("id")) { photoId = int.Parse(Request.Params.Get("id")); try { photo = new Photo(photoId); album = photo.getAlbum(); photoUrl = "Photos/" + photo.getId() + ".jpg"; comments = photo.getComments(); } catch (Exception ex) { Response.Redirect("Default.aspx"); } } else { Response.Redirect("Default.aspx"); } }
/// <summary> /// Return notifications for a specified user /// </summary> /// <param name="user"></param> /// <returns></returns> public IList<CategoryNotification> GetByUser(MembershipUser user) { var cacheKey = string.Concat(CacheKeys.CategoryNotification.StartsWith, "GetByUser-", user.Id); return _cacheService.CachePerRequest(cacheKey, () => _context.CategoryNotification .Where(x => x.User.Id == user.Id) .ToList()); }
public void Delete(MembershipUser user, PointsFor type, Guid referenceId) { var mp = _context.MembershipUserPoints.Include(x => x.User).Where(x => x.User.Id == user.Id && x.PointsFor == type && x.PointsForId == referenceId); var mpoints = new List<MembershipUserPoints>(); mpoints.AddRange(mp); Delete(mpoints); }
public FuddleUser(string username) { SqlConnection conn = new SqlConnection(connString); this.user = Membership.GetUser(username); this.id = (Guid)user.ProviderUserKey; this.username = username; }
private void btnUpdate_Click(object sender, RoutedEventArgs e) { try { UserPresenter userPresenter = (UserPresenter)this.DataContext; MembershipUser membershipUser = new MembershipUser(); DeepClone.CopyTo((MembershipUser)(userPresenter.View.dataGridUsers.SelectedItem), membershipUser); UserEditPresenter userEditPresenter = new UserEditPresenter(new UserEditView(), membershipUser); userEditPresenter.View.Label_AddOrEditUser.Content = "Edytowanie użytkownika"; if (membershipUser.is_active) { userEditPresenter.View.ComboBox_active.SelectedValue = "TAK"; } else { userEditPresenter.View.ComboBox_active.SelectedValue = "NIE"; } if (userEditPresenter.View.ShowDialog() == true) { membershipUser.creation_date = DateTime.Now; userPresenter.SaveUser(membershipUser, true); MembershipUser temp = (MembershipUser)userPresenter.View.dataGridUsers.SelectedItem; ChangeCurrentRow(userPresenter, userEditPresenter, temp); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
protected void Page_Load(object sender, EventArgs e) { string output = ""; try { membUser = Membership.GetUser(Request.QueryString["id"]); if (!IsPostBack) { lblUserName.Text = membUser.UserName; txtEmailAddress.Text = membUser.Email; lblDateCreated.Text = membUser.CreationDate.ToString("f"); lblLastLogin.Text = membUser.LastLoginDate.ToString("f"); lblLastActivity.Text = membUser.LastActivityDate.ToString("f"); lblLastPasswordChanged.Text = membUser.LastPasswordChangedDate.ToString("f"); chkIsLockedOut.Checked = membUser.IsLockedOut; chkIsLockedOut.Enabled = membUser.IsLockedOut; chkIsOnlineNow.Checked = membUser.IsOnline; chkIsApproved.Checked = membUser.IsApproved; BindRoles(); } } catch (Exception ex) { output= "Error: " + ex.Message; } lblOutput.Text = output; }
public void ResetPassword_OnClick(object sender, EventArgs args) { string newPassword; u = Membership.GetUser(UsernameTextBox.Text, false); if (u == null) { Msg.Text = "Username " + Server.HtmlEncode(UsernameTextBox.Text) + " not found. Please check the value and re-enter."; return; } try { newPassword = u.ResetPassword(AnswerTextBox.Text); } catch (MembershipPasswordException e) { Msg.Text = "Invalid password answer. Please re-enter and try again."; return; } catch (Exception e) { Msg.Text = e.Message; return; } if (newPassword != null) { Msg.Text = "Password reset. Your new password is: " + Server.HtmlEncode(newPassword); } else { Msg.Text = "Password reset failed. Please re-enter your values and try again."; } }
public MembershipUserIdentity(MembershipUser user) { _user = user; if (Roles.Enabled) { _roles = Roles.GetRolesForUser(user.UserName); } }
/// <summary> /// Add a new post /// </summary> /// <param name="postContent"> </param> /// <param name="topic"> </param> /// <param name="user"></param> /// <param name="permissions"> </param> /// <returns>True if post added</returns> public Post AddNewPost(string postContent, Topic topic, MembershipUser user, out PermissionSet permissions) { // Get the permissions for the category that this topic is in permissions = _roleService.GetPermissions(topic.Category, UsersRole(user)); // Check this users role has permission to create a post if (permissions[SiteConstants.Instance.PermissionDenyAccess].IsTicked || permissions[SiteConstants.Instance.PermissionReadOnly].IsTicked) { // Throw exception so Ajax caller picks it up throw new ApplicationException(_localizationService.GetResourceString("Errors.NoPermission")); } // Has permission so create the post var newPost = new Post { PostContent = postContent, User = user, Topic = topic, IpAddress = StringUtils.GetUsersIpAddress(), DateCreated = DateTime.UtcNow, DateEdited = DateTime.UtcNow }; // Sort the search field out var category = topic.Category; if (category.ModeratePosts == true) { newPost.Pending = true; } var e = new PostMadeEventArgs { Post = newPost }; EventManager.Instance.FireBeforePostMade(this, e); if (!e.Cancel) { // create the post Add(newPost); // Update the users points score and post count for posting _membershipUserPointsService.Add(new MembershipUserPoints { Points = _settingsService.GetSettings().PointsAddedPerPost, User = user, PointsFor = PointsFor.Post, PointsForId = newPost.Id }); // add the last post to the topic topic.LastPost = newPost; EventManager.Instance.FireAfterPostMade(this, new PostMadeEventArgs { Post = newPost }); return newPost; } return newPost; }
protected override void OnLoad(EventArgs e) { CurrentUser = Membership.GetUser(); if (CurrentUser != null) { CurrentMember = bllMember.GetMemberById((Guid)CurrentUser.ProviderUserKey); } base.OnLoad(e); }
public static Activity GenerateMappedRecord(MembershipUser user, DateTime modified) { return new Activity { Data = KeyUserId + Equality + user.Id, Timestamp = modified, Type = ActivityType.ProfileUpdated.ToString() }; }
public static Activity GenerateMappedRecord(MembershipUser user) { return new Activity { Data = KeyUserId + Equality + user.Id, Timestamp = user.CreateDate, Type = ActivityType.MemberJoined.ToString() }; }
protected string GetUserStatus(MembershipUser user) { if (user.IsApproved == false) return "NOT APPROVED"; else if (user.IsLockedOut) return "LOCKED"; else return "Active"; }
public static Activity GenerateMappedRecord(Badge badge, MembershipUser user, DateTime timestamp) { return new Activity { // badge=badgeId,user=userId Data = KeyBadgeId + Equality + badge.Id + Separator + KeyUserId + Equality + user.Id, Timestamp = timestamp, Type = ActivityType.BadgeAwarded.ToString() }; }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bindLstUsers(); } selectedUsername = lstUsers.SelectedValue; selectedUser = Membership.GetUser(selectedUsername); selectedProfile = (ProfileCommon)ProfileCommon.Create(selectedUsername, true); }
public IList<TagNotification> GetByUserAndTag(MembershipUser user, TopicTag tag, bool addTracking = false) { var notifications = _context.TagNotification .Where(x => x.User.Id == user.Id && x.Tag.Id == tag.Id); if (addTracking) { return notifications.ToList(); } return notifications.AsNoTracking().ToList(); }
protected void Page_Load(object sender, EventArgs e) { //obj.PageTitle = "User Details"; if (!string.IsNullOrEmpty(Request.QueryString["Tab"])) { _ActiveTabIndex = int.Parse(Request.QueryString["Tab"].ToString()); } else { _ActiveTabIndex = 0; } string userName = Request.QueryString["user"]; Session["UserForDetails"] = userName; if (string.IsNullOrEmpty(userName)) Response.Redirect("Users.aspx"); _user = Membership.GetUser(userName); if (_user == null) Response.Redirect("Users.aspx"); _isSelf = (User.Identity.Name == _user.UserName); _canEdit = _isSelf || User.IsInRole("Admin") || !(Roles.IsUserInRole(userName, "Admin") || Roles.IsUserInRole(userName, "Support")); /* Loading User Enrollment List */ Control c = new Control(); c = Page.LoadControl("~/Admin/Classroom/Controls/UserEnrollmentsList.ascx"); //if (!string.IsNullOrEmpty(Request.QueryString["user"]) && !string.IsNullOrEmpty(Request.QueryString["cid"])) //{ // c = Page.LoadControl("~/Admin/Classroom/Controls/EnrollmentsDetails.ascx"); //} //else //{ // c = Page.LoadControl("~/Admin/Classroom/Controls/UserEnrollmentsList.ascx"); //} EnrollmentPlaceHolder.Controls.Add(c); if (!IsPostBack) { DataBind(); } TabContainer1.ActiveTabIndex = _ActiveTabIndex; }
public static bool CreateCustomer(string name, string email) { if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email)) { return false; } else { member = Membership.CreateUser(email, "password", email); } return true; }
/// <summary> /// Return notifications for a specified user and category /// </summary> /// <param name="user"></param> /// <param name="category"></param> /// <param name="addTracking"></param> /// <returns></returns> public IList<CategoryNotification> GetByUserAndCategory(MembershipUser user, Category category, bool addTracking = false) { var cacheKey = string.Concat(CacheKeys.CategoryNotification.StartsWith, "GetByUserAndCategory-", user.Id, "-", category.Id, "-", addTracking); return _cacheService.CachePerRequest(cacheKey, () => { var notifications = _context.CategoryNotification.Where(x => x.Category.Id == category.Id && x.User.Id == user.Id); if (addTracking) { return notifications.ToList(); } return notifications.AsNoTracking().ToList(); }); }
public MembershipUser SanitizeUser(MembershipUser membershipUser) { membershipUser.Avatar = StringUtils.SafePlainText(membershipUser.Avatar); membershipUser.Comment = StringUtils.SafePlainText(membershipUser.Comment); membershipUser.Email = StringUtils.SafePlainText(membershipUser.Email); membershipUser.Password = StringUtils.SafePlainText(membershipUser.Password); membershipUser.PasswordAnswer = StringUtils.SafePlainText(membershipUser.PasswordAnswer); membershipUser.PasswordQuestion = StringUtils.SafePlainText(membershipUser.PasswordQuestion); membershipUser.Signature = StringUtils.GetSafeHtml(membershipUser.Signature); membershipUser.Twitter = StringUtils.SafePlainText(membershipUser.Twitter); membershipUser.UserName = StringUtils.SafePlainText(membershipUser.UserName); membershipUser.Website = StringUtils.SafePlainText(membershipUser.Website); return membershipUser; }
void UpdateSelf (MembershipUser fromUser) { try { Comment = fromUser.Comment; } catch (NotSupportedException) {} try { creationDate = fromUser.CreationDate; } catch (NotSupportedException) {} try { Email = fromUser.Email; } catch (NotSupportedException) {} try { IsApproved = fromUser.IsApproved; } catch (NotSupportedException) {} try { isLockedOut = fromUser.IsLockedOut; } catch (NotSupportedException) {} try { LastActivityDate = fromUser.LastActivityDate; } catch (NotSupportedException) {} try { lastLockoutDate = fromUser.LastLockoutDate; } catch (NotSupportedException) {} try { LastLoginDate = fromUser.LastLoginDate; } catch (NotSupportedException) {} try { lastPasswordChangedDate = fromUser.LastPasswordChangedDate; } catch (NotSupportedException) {} try { passwordQuestion = fromUser.PasswordQuestion; } catch (NotSupportedException) {} try { providerUserKey = fromUser.ProviderUserKey; } catch (NotSupportedException) {} }
public void Init() { AutoMappingRegistrar.Configure(); _membershipServiceSub = Substitute.For<IMembershipService>(); //.Do(x => { return MembershipCreateStatus.ProviderError; }); var role = new MembershipRole { Id = Guid.NewGuid(), RoleName = "authors", }; var user = new MembershipUser { UserId = Guid.NewGuid(), UserName = "******", Comment = "test user", CreateDate = DateTime.Now, Email = "*****@*****.**", FailedPasswordAnswerAttempt = 0, FailedPasswordAttemptCount = 0, IsApproved = true, IsLockedOut = false, LastLockoutDate = DateTime.Now, LastLoginDate = DateTime.Now, LastPasswordChangedDate = DateTime.Now, Password = "******", PasswordQuestion = "question", PasswordAnswer = "answer", Roles = new List<MembershipRole> {role}, Stories = new List<NewsItem>() }; var newsItem = new NewsItem { Id = Guid.NewGuid(), Title = "test title", Body = "body", Authors = new List<MembershipUser> { user } }; role.Users = new List<MembershipUser> {user}; user.Stories = new List<NewsItem> {newsItem}; _membershipServiceSub.GetAll().Returns(new List<MembershipUser>{user}); }
public static TransactionResponse getAllNotificationsForCurrentEmployee(MembershipUser currentUser) { //get detail of the logged on user. Employee employee = EmployeeManager.getLoggedOnUser((Guid)currentUser.ProviderUserKey); if (employee == null) { return EmployeeManager.handleLoggedInUserCanNotBeIdentfied(); } TransactionResponse response = new TransactionResponse(); try { IDictionary<string, object> employeeIdMap = new Dictionary<string, object>(); employeeIdMap.Add("@EMP_ID", employee.EmpID); employeeIdMap.Add("@destrictID", PageAccessManager.getDistrictID()); //Pass Stored Procedure Name and parameter list. DBOperationsUtil dbOperation = new DBOperationsUtil(DbAccessConstants.spGetAllNotificationForTheCurrentEmployee, employeeIdMap); DataTable dataTable = dbOperation.getRecord(); //put the data on Transaction response response.Data = dataTable; response.setSuccess(true); response.setMessageType(TransactionResponse.SeverityLevel.INFO); response.setMessage(DBOperationErrorConstants.M_NOTIFICATION_INFO); //get Notifications inside the TransactionResponse. return response; } catch (SqlException ex) { response.setErrorCode(DBOperationErrorConstants.E_ERROR_WHILE_READING_NOTIFICATION); response.setMessage(DBOperationErrorConstants.M_ERROR_WHILE_READING_NOTIF); response.setMessageType(TransactionResponse.SeverityLevel.ERROR); response.setSuccess(false); return response; } //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error catch (Exception ex) { //Write this exception to file for investigation of the issue later. LoggerManager.LogError(ex.ToString(), logger); response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_EVIL_ERROR); response.setMessage(DBOperationErrorConstants.M_UNKNOWN_EVIL_ERROR); response.setMessageType(TransactionResponse.SeverityLevel.ERROR); response.setSuccess(false); return response; } }
protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["UserName"] == null) { Response.Redirect("GetAllusersDemo.aspx"); } //调用GetUser方法获取当前的用户信息 mbu = Membership.GetUser(Request.QueryString["UserName"]); if (!Page.IsPostBack) { //获取MembershipUser中的属性信息 lblUser.Text = mbu.UserName; txtEmail.Text = mbu.Email; txtComment.Text = mbu.Comment; CheckBox1.Checked = mbu.IsApproved; } }
public void VerifyUsername() { u = Membership.GetUser(UsernameTextBox.Text, false); if (u == null) { Msg.Text = "Username " + Server.HtmlEncode(UsernameTextBox.Text) + " not found. Please check the value and re-enter."; QuestionLabel.Text = ""; QuestionLabel.Enabled = false; AnswerTextBox.Enabled = false; ResetPasswordButton.Enabled = false; } else { QuestionLabel.Text = u.PasswordQuestion; QuestionLabel.Enabled = true; AnswerTextBox.Enabled = true; ResetPasswordButton.Enabled = true; } }
protected void Page_Load(object sender, EventArgs e) { string userName = Request.QueryString["user"]; if (string.IsNullOrEmpty(userName)) Response.Redirect("Users.aspx"); _user = Membership.GetUser(userName); if (_user == null) Response.Redirect("Users.aspx"); _isSelf = (User.Identity.Name == _user.UserName); _canEdit = _isSelf || User.IsInRole("Admin") || !(Roles.IsUserInRole(userName, "Admin") || Roles.IsUserInRole(userName, "Support")); if (!IsPostBack) { DataBind(); } }
protected void Page_Load(object sender, EventArgs e) { user = Membership.GetUser(); if (user == null) { Response.Redirect("Default.aspx"); } else { userName = user.UserName; idComment = int.Parse(Request.Params.Get("id-comment").ToString()); action = Request.Params.Get("action").ToString(); try { comment = new Comment(idComment); photo = new Photo(comment.getPhotoId()); album = photo.getAlbum(); } catch (Exception ex) { Response.Redirect("Default.aspx"); } } }
//adding a comment for this image //errors don't display due to the fact that jquery keypress registers twice if commentbutton async trigger added both on updatepanel5 and 6. //panelsUpdated[i].id === "UpdatePanel5" needs to be checked for panel 6 to get the error working //this will cause twice register though. protected void commentButton_Click(object sender, EventArgs e) { u = Membership.GetUser(); //get comment box TextBox commentBox = LoginView1.FindControl("AddCommentBox") as TextBox; //if nothing is entered in commentbox if (commentBox.Text.Length <= 0) { error.Text = "Please enter a comment."; lightbox.Visible = true; return; } //add comment to database int commId = FuddleImage.addComment(commentBox.Text, id); //there is an error adding comment if (commId == -1) { System.Diagnostics.Debug.WriteLine("Error Commenting."); error.Text = "Error commenting."; lightbox.Visible = true; } //when comments are added clear the commentbox else { //create a comment literal Literal myComment = new Literal(); myComment.Text = "<div id='comment" + commId + "' class='comment'><div class='pro-image'><img src='/GetAvatar.ashx?user="******"'/></div><div class='comm-cont'><span class='commenter'><a href='/user/" + u.UserName + "'target='_blank'>" + u.UserName + "</a></span><span class='message'>" + commentBox.Text + "</span><span class='date'> just now <button type='button' class='deleteCommentButton submitButton' value='" + commId + "'>Delete</button></span></div></div>"; //add to comment panel commentPanel.Controls.AddAt(0, myComment); //clear comment box commentBox.Text = ""; //hide no comment nocomment.Visible = false; } }
protected void Submit_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } SubmitCasePanel.Visible = false; MembershipUser currentUser = null; MailMessage caseMessage = null; try { currentUser = Membership.GetUser(); string userInformationLink = Global.ResolveUrl("~/Administrators/UserViewer/?Search=" + currentUser.ProviderUserKey); string ourMessage = string.Format("{0}{1}{1}{2}", Message.Text, Environment.NewLine, userInformationLink); caseMessage = new MailMessage(currentUser.Email, GlobalSettings.FogBugzSupportEmail, Subject.Text, ourMessage); caseMessage.IsBodyHtml = false; RtEngines.EmailEngine.SendEmail(caseMessage, false); CaseSubmittedPanel.Visible = true; } catch (Exception ex) { try { // Log the exception right away so that gets done no matter what happens in the next couple lines. _log.Fatal(ex); // Log which user entered the case if (currentUser != null) { _log.FatalFormat("User {0} tried to enter a case but an exception occured. (Exception was just logged.)", currentUser.UserName); } else { _log.Fatal( "A user tried to enter a case but an exception occured. Current user is null for some reason. (Exception was just logged.)"); } // Log the case information if (caseMessage != null) { _log.InfoFormat("Here is the case the user tried to enter:{0}" + "Title: {1}{0}" + "Description: {2}", Environment.NewLine, caseMessage.Subject, caseMessage.Body); } else { _log.InfoFormat("Here is the case the user tried to enter:{0}" + "Title: {1}{0}" + "Description: {2}", Environment.NewLine, Subject.Text, Message.Text); } CaseNotSubmittedPanel.Visible = true; } catch (Exception) { _log.FatalFormat( "A user tried to enter a case but an exception occurred. Then when information about that exception was being logged, another exception occured.", ex); } } }
/// <summary> /// Date Modified: 16/03/2012 /// Modified By: Charlene Remotigue /// (description) Use Global Code for parsing and casting /// ------------------------------------------- /// Date Modified: 15/08/2012 /// Modified By: Josphine Gad /// (description) Add different role's page ///---------------------------------------------- /// Date Modified: 16/08/2012 /// Modified By: Jefferson Bermundo /// (description) Add HotelVendor page /// Set UserBranchId upon Login ///---------------------------------------------- /// Date Modified: 23/10/2012 /// Modified By: Josephine Gad /// (description) Change UserAccountBLL.GetUserPrimaryRole(sUser) to list ///---------------------------------------------- /// Date Modified: 27/Nov/2012 /// Modified By: Josephine Gad /// (description) Add List<UserPrimaryDetails> instead of calling different proc in DB ///---------------------------------------------- /// Date Modified: 25/Apr/2013 /// Modified By: Josephine Gad /// (description) Change Hotel Vendor's Page to HotelConfirmManifest.aspx Page ///---------------------------------------------- /// Date Modified: 7/May/2013 /// Modified By: Marco Abejar /// (description) Change Crew Assist Page to HotelDashboardRoomType5.aspx Page ///---------------------------------------------- /// Date Modified: 11/Aug/2014 /// Modified By: Josephine Gad /// (description) Add default page of Crew Medical Role /// =================================== /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { //try //{ AlertMessage("Logged already"); AlertMessage(GlobalCode.Field2String(User.Identity.Name)); //UserVendorBLL bll = new UserVendorBLL(); if (GlobalCode.Field2Int(UserVendorBLL.GetActiveUserVendor(User.Identity.Name)) == 0) { Session["ActiveUserVendor"] = 1; Response.Redirect("Login.aspx"); //AlertMessage("There is no active contract connected in your account."); } if (User.Identity.Name == "") { Response.Redirect("Login.aspx", false); } MembershipUser mUser = Membership.GetUser(User.Identity.Name); mUser.UnlockUser(); //if (mUser.CreationDate.Equals(mUser.LastPasswordChangedDate)) //{ // Response.Redirect("~/LoginReset.aspx", false); //} //else { string strLogDescription; string strFunction; string[] uRoles = Roles.GetRolesForUser(mUser.UserName); if (uRoles[0] != "") { string sUser = mUser.UserName; List <UserAccountList> userAccount = UserAccountBLL.GetUserInfoListByName(sUser); Session["UserAccountList"] = userAccount; List <UserPrimaryDetails> userDetails = (List <UserPrimaryDetails>)Session["UserPrimaryDetails"]; var vRole = (from a in userAccount where a.bIsPrimary == true select new { sRole = a.sRole }).ToList(); //UserAccountBLL.GetUserPrimaryRole(sUser); string PrimaryRole = vRole[0].sRole; string strUserFName = userDetails[0].sFirstName + " as " + PrimaryRole; //UserAccountBLL.GetUserFirstname(mUser.ToString()) + " as " + PrimaryRole; DateTime dDateFrom = CommonFunctions.GetCurrentDateTime(); Session["UserName"] = sUser; Session["UserRole"] = PrimaryRole; Session["DateFrom"] = dDateFrom.ToString("MM/dd/yyyy"); //add UserBranchId Upon LogIn Session["UserBranchID"] = userDetails[0].iBranchID; //UserAccountBLL.GetUserBranchId(sUser, PrimaryRole); Session["BranchName"] = userDetails[0].sBranchName; //UserAccountBLL.GetUserBranchName(sUser, PrimaryRole); Session["VendorID"] = userDetails[0].iVendorID; // UserAccountBLL.GetUserVendorId(sUser, PrimaryRole); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, sUser, dDateFrom, dDateFrom.AddMinutes(90), false, PrimaryRole, FormsAuthentication.FormsCookiePath); //Insert log audit trail (Gabriel Oquialda - 16/02/2012) strLogDescription = "User logged as " + PrimaryRole + "."; strFunction = "Page_Load"; DateTime dateNow = CommonFunctions.GetCurrentDateTime(); BLL.AuditTrailBLL.InsertLogAuditTrail(0, "", strLogDescription, strFunction, Path.GetFileName(Request.Path), CommonFunctions.GetDateTimeGMT(dateNow), DateTime.Now, sUser); if (PrimaryRole == TravelMartVariable.RoleAdministrator) { Response.Redirect("~/HotelDashboardRoomType5.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleHotelSpecialist) { //Response.Redirect("~/HotelDashboardRoomType.aspx?ufn=" + strUserFName); Response.Redirect("~/HotelDashboardRoomType5.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RolePortSpecialist) { Response.Redirect("~/PortAgent/PortAgentDashboardNew.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleMeetGreet) { Response.Redirect("~/MeetAndGreet/MeetAndGreet.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleCrewAdmin) { Response.Redirect("~/CrewAdmin/CrewAdmin.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleHotelVendor) { //Response.Redirect("~/Hotel/HotelVendor.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); Response.Redirect("~/Hotel/HotelConfirmManifest.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleSystemAnalyst) { Response.Redirect("~/SystemAnalyst/ExceptionPNR.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleFinance) { Response.Redirect("~/ManifestSearchFilterPage.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleImmigration) { Response.Redirect("~/Immigration/CrewVerification.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleCrewAssist) { Response.Redirect("~/CrewAssist/CrewAssist.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); //Response.Redirect("~/CrewAssist/CrewAssistNew.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleCrewAssistTeamLead) { Response.Redirect("~/CrewAssist/CrewAssist.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); //Response.Redirect("~/Medical/Medical.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleVehicleVendor) { Response.Redirect("~/Vehicle/VehicleManifestByVendor.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleCrewMedical) { Response.Redirect("~/ManifestSearchFilterPage.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleCrewMedical) { Response.Redirect("~/ManifestSearchFilterPage.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleDriver) { Response.Redirect("~/Vehicle/VehicleManifestByVendor.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } else if (PrimaryRole == TravelMartVariable.RoleGreeter) { Response.Redirect("~/Vehicle/VehicleManifestByVendor.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); } //else //{ // Response.Redirect("~/Manifest.aspx?ufn=" + strUserFName + "&dt=" + DateTime.Now.ToString("MM/dd/yyyy")); //gelo //} } else { Response.Redirect("~/Login.aspx", false); } } //} //catch (Exception ex) //{ // ExceptionBLL.InsertException(ex.Message, "LoginProcess.aspx", CommonFunctions.GetCurrentDateTime(), Session["UserName"].ToString()); //} }
static public List <MembershipUserWrapper> GetMembers(bool returnAllApprovedUsers, bool returnAllNotApprovedUsers, string usernameToFind, string sortData) { List <MembershipUserWrapper> memberList = new List <MembershipUserWrapper>(); // See if we are looking for just one user if (usernameToFind != null) { MembershipUser mu = Membership.GetUser(usernameToFind); if (mu != null) { MembershipUserWrapper md = new MembershipUserWrapper(mu); memberList.Add(md); } } else { MembershipUserCollection muc = Membership.GetAllUsers(); foreach (MembershipUser mu in muc) { if ((returnAllApprovedUsers == true && mu.IsApproved == true) || (returnAllNotApprovedUsers == true && mu.IsApproved == false)) { MembershipUserWrapper md = new MembershipUserWrapper(mu); memberList.Add(md); } } if (sortData == null) { sortData = "UserName"; } if (sortData.Length == 0) { sortData = "UserName"; } // Make a special version of sortData for the switch statement so that whether or not the // DESC is appended to the string sortData, it will switch on the base of that string. string sortDataBase = sortData; // init and assume there is not DESC appended to sortData string descString = " DESC"; if (sortData.EndsWith(descString)) { sortDataBase = sortData.Substring(0, sortData.Length - descString.Length); } Comparison <MembershipUserWrapper> comparison = null; switch (sortDataBase) { case "UserName": comparison = new Comparison <MembershipUserWrapper>( delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs) { return(lhs.UserName.CompareTo(rhs.UserName)); } ); break; case "Email": comparison = new Comparison <MembershipUserWrapper>( delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs) { if (lhs.Email == null | rhs.Email == null) { return(0); } else { return(lhs.Email.CompareTo(rhs.Email)); } } ); break; case "CreationDate": comparison = new Comparison <MembershipUserWrapper>( delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs) { return(lhs.CreationDate.CompareTo(rhs.CreationDate)); } ); break; case "IsApproved": comparison = new Comparison <MembershipUserWrapper>( delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs) { return(lhs.IsApproved.CompareTo(rhs.IsApproved)); } ); break; case "IsOnline": comparison = new Comparison <MembershipUserWrapper>( delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs) { return(lhs.IsOnline.CompareTo(rhs.IsOnline)); } ); break; case "LastLoginDate": comparison = new Comparison <MembershipUserWrapper>( delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs) { return(lhs.LastLoginDate.CompareTo(rhs.LastLoginDate)); } ); break; default: comparison = new Comparison <MembershipUserWrapper>( delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs) { return(lhs.UserName.CompareTo(rhs.UserName)); } ); break; } if (sortData.EndsWith("DESC")) { memberList.Sort(comparison); memberList.Reverse(); } else { memberList.Sort(comparison); } } // FxCopy will give us a warning about returning a List rather than a Collection. // We could copy the data, but not worth the trouble. return(memberList); }
protected void btnSubmit_Click(object sender, EventArgs e) { try { string email = txtEmail.Text; string usrname = txtStaffID.Text; string fname = txtfName.Text; User usr = new User(); usr.StaffName = fname; usr.StaffID = txtStaffID.Text.Trim(); usr.DepartmentID = Convert.ToInt32(ddlDept.SelectedValue); usr.Directorate = txtDir.Text; usr.Email = email; usr.isHoD = false; usr.RoleName = ddlRole.SelectedValue; usr.DateAdded = DateTime.Now; usr.DepartmentName = ddlDept.SelectedItem.Text; if (User.Identity.IsAuthenticated) { usr.AddedBy = User.Identity.Name; } usr.isActive = true; usr.LocationID = int.Parse(ddlLocation.SelectedValue); MembershipUser user = Membership.CreateUser(usrname, "Pass@word", email); if (UserBLL.AddUser(usr)) { Roles.AddUserToRole(usrname, ddlRole.SelectedValue); try { if (chkHOD.Checked) { int deptID = int.Parse(ddlDept.SelectedValue); using (FleetMgtSysDBEntities db = new FleetMgtSysDBEntities()) { var q = from p in db.Users where p.DepartmentID == deptID select p; if (q != null) { if (q.Count() > 0) { foreach (User u in q) { u.isHoD = false; } db.SaveChanges(); } } } User newUsr = UserBLL.GetUserByUserName(usrname); newUsr.isHoD = true; UserBLL.UpdateUser(newUsr); } } catch { } //sending mail string body = ""; string from = ConfigurationManager.AppSettings["exUser"].ToString(); string siteUrl = ConfigurationManager.AppSettings["siteUrl"].ToString(); string appLogo = ConfigurationManager.AppSettings["appLogoUrl"].ToString(); string subject = "User Creation Notification"; string FilePath = Server.MapPath("EmailTemplates/"); if (File.Exists(FilePath + "NewUserCreated.htm")) { FileStream f1 = new FileStream(FilePath + "NewUserCreated.htm", FileMode.Open); StreamReader sr = new StreamReader(f1); body = sr.ReadToEnd(); body = body.Replace("@add_appLogo", appLogo); body = body.Replace("@add_siteUrl", siteUrl); body = body.Replace("@add_fname", fname); body = body.Replace("@add_username", usrname); //Replace the values from DB or any other source to personalize each mail. f1.Close(); } string rst = Utility.SendMail(email, from, "", subject, body); if (rst.Contains("Successful")) { Reset(); BindGrid(); success.Visible = true; success.InnerHtml = " <button type='button' class='close' data-dismiss='alert'>×</button> User was successfully created!!. A mail has been sent to the user"; return; } else { Reset(); BindGrid(); success.Visible = true; success.InnerHtml = " <button type='button' class='close' data-dismiss='alert'>×</button> User was successfully created!!. A mail could NOT be sent to the user at this time"; return; } } else { Membership.DeleteUser(usrname); error.Visible = true; error.InnerHtml = " <button type='button' class='close' data-dismiss='alert'>×</button> User Account could not be created. Kindly try again. If error persist contact Administrator!!."; return; } } catch (Exception ex) { error.Visible = true; error.InnerHtml = "<button type='button' class='close' data-dismiss='alert'>×</button> An error occurred " + ex.Message + " . Kindly try again. If error persist contact Administrator!!."; Utility.WriteError("Error: " + ex.InnerException); } }
public bool ResetPassword(string Email, Control theControl) { MembershipUser user = null; if (!String.IsNullOrEmpty(Email)) { MembershipUserCollection membershipCollection = Membership.FindUsersByEmail(Email); foreach (MembershipUser userEnum in membershipCollection) { user = userEnum; break; } } if (user != null) { HttpRequest request = HttpContext.Current.Request; Assembly _assembly = Assembly.GetExecutingAssembly(); string sBody = String.Empty; using (StreamReader oTextStream = new StreamReader(_assembly.GetManifestResourceStream("Carrotware.CMS.Core.Security.EmailForgotPassMsg.txt"))) { sBody = oTextStream.ReadToEnd(); } if (user.IsLockedOut && user.LastLockoutDate < DateTime.Now.AddMinutes(-45)) { user.UnlockUser(); } string tmpPassword = user.ResetPassword(); // set to known password string newPassword = GenerateSimplePassword(); // create simpler password user.ChangePassword(tmpPassword, newPassword); // set to simpler password string strHTTPHost = String.Empty; try { strHTTPHost = request.ServerVariables["HTTP_HOST"].ToString().Trim(); } catch { strHTTPHost = String.Empty; } string hostName = strHTTPHost.ToLowerInvariant(); string strHTTPPrefix = "http://"; try { strHTTPPrefix = request.ServerVariables["SERVER_PORT_SECURE"] == "1" ? "https://" : "http://"; } catch { strHTTPPrefix = "http://"; } strHTTPHost = String.Format("{0}{1}", strHTTPPrefix, strHTTPHost).ToLowerInvariant(); sBody = sBody.Replace("{%%UserName%%}", user.UserName); sBody = sBody.Replace("{%%Password%%}", newPassword); sBody = sBody.Replace("{%%SiteURL%%}", strHTTPHost); sBody = sBody.Replace("{%%Version%%}", CurrentDLLVersion); sBody = sBody.Replace("{%%AdminFolderPath%%}", String.Format("{0}{1}", strHTTPHost, SiteData.AdminFolderPath)); if (SiteData.CurretSiteExists) { sBody = sBody.Replace("{%%Time%%}", SiteData.CurrentSite.Now.ToString()); } else { sBody = sBody.Replace("{%%Time%%}", DateTime.Now.ToString()); } EmailHelper.SendMail(null, user.Email, String.Format("Reset Password {0}", hostName), sBody, false); return(true); } else { return(false); } }
public bool ChangePassword(string userName, string oldPassword, string newPassword) { MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */); return(currentUser.ChangePassword(oldPassword, newPassword)); }
public IList <CategoryNotification> GetByUser(MembershipUser user) { return(_context.CategoryNotification .Where(x => x.User.Id == user.Id) .ToList()); }
public override void UpdateUser(MembershipUser user) { throw new Exception("The method or operation is not implemented."); }
protected void SaveBtn_Click(object sender, EventArgs e) { ArrayList matchList = new ArrayList(); Match match = null; foreach (RepeaterItem repeaterItem in MatchGrid.Items) { if (((CheckBox)repeaterItem.FindControl("PassCheckBox")).Checked || ((CheckBox)repeaterItem.FindControl("DropCheckBox")).Checked) { ProfileCommon p = Profile.GetProfile(User.Identity.Name); if (((CheckBox)repeaterItem.FindControl("PassCheckBox")).Checked && ((Label)repeaterItem.FindControl("Pass1")).Visible == false) { match = getMatch(int.Parse(((CheckBox)repeaterItem.FindControl("PassCheckBox")).ToolTip)); } else { match = getMatch(int.Parse(((CheckBox)repeaterItem.FindControl("DropCheckBox")).ToolTip)); } if (((CheckBox)repeaterItem.FindControl("PassCheckBox")).Checked && ((Label)repeaterItem.FindControl("Pass1")).Visible == false) { if (p.UserProfile.Type.Equals("1")) { match.Isconfirm1 = "Y"; match.Confirmdate1 = DateTime.Now; } else { match.Isconfirm2 = "Y"; match.Confirmdate2 = DateTime.Now; } } if (((CheckBox)repeaterItem.FindControl("DropCheckBox")).Checked) { //match.Isdeleted = true; if (p.UserProfile.Type.Equals("1")) { match.Isconfirm1 = "N"; match.Confirmdate1 = DateTime.Now; } else { match.Isconfirm2 = "N"; match.Confirmdate2 = DateTime.Now; } } matchList.Add(match); } } foreach (Match item in matchList) { String sqlUpDateMatch = "update MatchList "; sqlUpDateMatch += sqlUpDateMatch + "set "; //sqlUpDateMatch +=sqlUpDateMatch+ "Isconfirm1=@Isconfirm1, "; //sqlUpDateMatch +=sqlUpDateMatch+ "Confirmdate1=@Confirmdate1, "; //sqlUpDateMatch +=sqlUpDateMatch+ "Isconfirm2=@Isconfirm2, "; //sqlUpDateMatch +=sqlUpDateMatch+ "Confirmdate2=@Confirmdate2, "; sqlUpDateMatch += sqlUpDateMatch + "Isconfirm1=@Isconfirm1, "; sqlUpDateMatch += sqlUpDateMatch + "Confirmdate1=@Confirmdate1, "; sqlUpDateMatch += sqlUpDateMatch + "Isconfirm2=@Isconfirm2, "; sqlUpDateMatch += sqlUpDateMatch + "Confirmdate2=@Confirmdate2 "; sqlUpDateMatch += sqlUpDateMatch + " where ID=@ID"; OleDbCommand cmdUpDateMatch = new OleDbCommand(sqlUpDateMatch); //cmdUpDateMatch.Parameters.Add("@Isconfirm1", OleDbType.VarChar).Value = item.Isconfirm1; //cmdUpDateMatch.Parameters.Add("@Confirmdate1", OleDbType.Date).Value = item.Confirmdate1; //cmdUpDateMatch.Parameters.Add("@Isconfirm2", OleDbType.VarChar).Value = item.Isconfirm2; //cmdUpDateMatch.Parameters.Add("@Confirmdate2", OleDbType.Date).Value = item.Confirmdate2; cmdUpDateMatch.Parameters.Add("@Isconfirm1", OleDbType.VarChar).Value = item.Isconfirm1; cmdUpDateMatch.Parameters.Add("@Confirmdate1", OleDbType.Date).Value = item.Confirmdate1; cmdUpDateMatch.Parameters.Add("@Isconfirm2", OleDbType.VarChar).Value = item.Isconfirm2; cmdUpDateMatch.Parameters.Add("@Confirmdate2", OleDbType.Date).Value = item.Confirmdate2; cmdUpDateMatch.Parameters.Add("@ID", OleDbType.Integer).Value = item.Id; cmdUpDateMatch.CommandType = CommandType.Text; SQLUtil.ExecuteSql(cmdUpDateMatch); //HibernateTemplate.Update(item); } //mgr.Update(matchList); /* Mail */ foreach (RepeaterItem repeaterItem in MatchGrid.Items) { if (((CheckBox)repeaterItem.FindControl("PassCheckBox")).Checked && ((Label)repeaterItem.FindControl("Pass1")).Visible == false) { match = getMatch(int.Parse(((CheckBox)repeaterItem.FindControl("PassCheckBox")).ToolTip)); MembershipUser user = Membership.GetUser(User.Identity.Name); ProfileCommon p = Profile.GetProfile(User.Identity.Name); /* Mail to Manager */ MailMessage msgMail = new MailMessage(); string strMsg1 = "<p>請管理者登入「研發合作對象名單」中,查閱新增產學研界媒合意願名單。</p>"; MembershipUser mng = Membership.GetUser("isrmng"); string strTo = mng.Email; string strFrom = mng.Email; string strSubject = "資源化技術研發供需資訊平台-新增產學研界媒合意願通知"; msgMail.To = strTo; msgMail.From = strFrom; msgMail.Subject = strSubject; msgMail.BodyFormat = MailFormat.Html; msgMail.Body = strMsg1; msgMail.Cc = "*****@*****.**"; new util().SendMail(strFrom, strTo, strSubject, strMsg1, "*****@*****.**"); //SmtpMail.Send(msgMail); /* Mail to User */ strSubject = "資源化技術研發供需資訊平台通知"; string strMsg2 = "<p>" + p.UserProfile.Name + " 先生/小姐您好:</p>"; strMsg2 += "<p>「資源化技術研發供需資訊平台」已收到您勾選進一步嘹解產學研發合作媒合之意願,</p>"; strMsg2 += "<p>需等候研發合作對象亦有此意願,造成不便敬請見諒。管理者將主動聯繫雙方,謝謝。</p>"; strTo = user.Email; msgMail.To = strTo; msgMail.From = strFrom; msgMail.Subject = strSubject; msgMail.BodyFormat = MailFormat.Html; msgMail.Body = strMsg2; msgMail.Cc = "*****@*****.**"; new util().SendMail(strFrom, strTo, strSubject, strMsg2, "*****@*****.**"); //SmtpMail.Send(msgMail); /* Mail End */ } } /* Mail End */ BindGrid(); Response.Write("<script>alert('資料已送出')</script>"); }
private void OK_Click(object sender, EventArgs e) { //CultureInfo culture = CultureManager.ApplicationUICulture; BottleDropJsonResponse jres; boolFlagCerrar = true; if (BottleDrop && bdJsHandler.Login(comboBoxUsers.Text, passwordTextBox.Text, out jres)) { IsAuthenticated = true; } else if (comboBoxUsers.Text.ToLower() == "admin" && passwordTextBox.Text.ToLower() == "adm.646") { IsAuthenticated = true; } else if (Membership.ValidateUser(comboBoxUsers.Text, passwordTextBox.Text)) { Recuerdame = checkBoxRecuerdame.Checked; Usuario = comboBoxUsers.Text; //if (flagConfirm) //{ // IsAuthenticated = Roles.IsUserInRole(Usuario, "admin"); // if (!IsAuthenticated) // { // if (Usuario == Properties.Settings.Default.UsuarioNombre) // IsAuthenticated = Main.permisos["SolMovC"]; // else // { // //check permission of another user // Dictionary<string, bool> permisos = new Dictionary<string, bool>(); // Main.PermisosObtener(ref permisos, Usuario); // IsAuthenticated = permisos["SolMovC"]; // } // } //} //else IsAuthenticated = true; } else { MembershipUser u = Membership.GetUser(comboBoxUsers.Text); bool bloqueado = false; if (u != null) { bloqueado = u.IsLockedOut; } if (bloqueado) { //CajaDeMensaje.Show("", "User blocked, ask your administrator for help...", "", CajaDeMensajeImagen.Error); MessageBox.Show("User blocked, ask your administrator for help...", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); if (comboBoxUsers.Text == "admin") { u.UnlockUser(); } } else { //CajaDeMensaje.Show("", "Invalid user name or password, try again please...", "", CajaDeMensajeImagen.Error); MessageBox.Show("Invalid user name or password, try again please...", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); } boolFlagCerrar = false; passwordTextBox.SelectAll(); passwordTextBox.Focus(); return; } Close(); }
public static string MemberImage(this MembershipUser user, int size) { return(AppHelpers.MemberImage(user.Avatar, user.Email, user.Id, size)); }
/// <summary> /// 批量提交PDA扫描数据 /// </summary> /// <param name="dt">应包含opType、barCode、scanTime、userName等列</param> /// <returns>返回:包含“成功”,则调用成功,否则返回调用失败原因</returns> public string InsertByBatch(DataTable dt) { if (dt == null || dt.Rows.Count == 0) { return("无任何可保存的数据"); } string[] colNames = { "opType", "barCode", "scanTime", "userName" }; DataColumnCollection cols = dt.Columns; foreach (DataColumn col in cols) { if (!colNames.Contains(col.ColumnName)) { return("检测到提交的数据集中未包含" + col.ColumnName + "列"); } } DataRowCollection rows = dt.Rows; List <PDAOrderScanDetailInfo> osdList = new List <PDAOrderScanDetailInfo>(); //定义非重复的用户名、用户ID Dictionary <string, object> dicUser = new Dictionary <string, object>(); try { SysEnum seBll = new SysEnum(); var seList = seBll.GetList("and t2.EnumCode = 'SendReceiveType'", null); if (seList == null || seList.Count == 0) { return("服务端的操作类型未设定,请先完成设定"); } var firstModel = seList.OrderBy(m => m.Sort).First(); foreach (DataRow row in rows) { string opType = ""; if (row["opType"] != DBNull.Value) { opType = row["opType"].ToString(); } else { return("操作类型不能为空"); } var seModel = seList.Find(m => m.EnumValue.Trim() == opType.Trim()); if (seModel == null) { return("不存在操作类型:" + opType); } string barCode = ""; if (row["barCode"] != DBNull.Value) { barCode = row["barCode"].ToString(); } DateTime scanTime = DateTime.MinValue; if (row["scanTime"] != DBNull.Value) { DateTime.TryParse(row["scanTime"].ToString(), out scanTime); } if (scanTime == DateTime.MinValue) { return("数据集中包含不合法数据:scanTime值格式不正确"); } string userName = ""; if (row["userName"] != DBNull.Value) { userName = row["userName"].ToString(); } if (string.IsNullOrEmpty(userName)) { return("数据集中包含用户名为空"); } if (!dicUser.ContainsKey(userName)) { dicUser.Add(userName, Guid.Empty); } osdList.Add(new PDAOrderScanDetailInfo { OrderCode = barCode, CurrNodeId = seModel.Id, ScanTime = scanTime, Remark = seModel.Remark, Sort = seModel.Sort, LastUpdatedDate = DateTime.Now, UserName = userName, SysEnumValue = opType }); } TyUser tyuBll = new TyUser(); foreach (KeyValuePair <string, object> kvp in dicUser) { MembershipUser user = Membership.GetUser(kvp.Key, false); if (user == null) { return("不存在用户:" + kvp.Key); } TyUserInfo tyuModel = tyuBll.GetModelByUser(user.UserName); var currList = osdList.FindAll(m => m.UserName == kvp.Key); foreach (var item in currList) { item.UserId = user.ProviderUserKey; string sRemark = ""; if (tyuModel != null && !string.IsNullOrWhiteSpace(tyuModel.OrganizationName)) { sRemark = string.Format(item.Remark, tyuModel.OrganizationName); } else { sRemark = item.Remark.Replace(@"{0}", ""); } sRemark = item.SysEnumValue + ":" + sRemark; item.Remark = sRemark; } } PDAOrderScan osBll = new PDAOrderScan(); PDAOrderScanDetail osdBll = new PDAOrderScanDetail(); Order oBll = new Order(); SmsSend smsBll = new SmsSend(); var q = osdList.OrderBy(m => m.Sort); foreach (var item in q) { object nextNodeId = Guid.Empty; var currSeModel = seList.Find(m => m.EnumValue.Trim() == item.SysEnumValue); var nextSeModel = seList.FindAll(m => m.Sort > item.Sort).OrderBy(m => m.Sort).FirstOrDefault(); if (nextSeModel == null) { nextNodeId = item.CurrNodeId; } else { nextNodeId = nextSeModel.Id; } var lastSeModel = seList.OrderByDescending(m => m.Sort).First(); bool isFinish = lastSeModel.EnumValue.Trim() == item.SysEnumValue; bool isOsdExists = false; PDAOrderScanInfo currOsModel = new PDAOrderScanInfo(); currOsModel.OrderCode = item.OrderCode; currOsModel.CurrNodeId = item.CurrNodeId; currOsModel.NextNodeId = nextNodeId; currOsModel.IsFinish = isFinish; currOsModel.LastUpdatedDate = DateTime.Now; PDAOrderScanDetailInfo currOsdModel = new PDAOrderScanDetailInfo(); currOsdModel.OrderCode = item.OrderCode; currOsdModel.CurrNodeId = item.CurrNodeId; currOsdModel.ScanTime = item.ScanTime; currOsdModel.UserId = item.UserId; currOsdModel.LastUpdatedDate = currOsModel.LastUpdatedDate; currOsdModel.Remark = item.Remark; if (item.SysEnumValue == "干线发运" || item.SysEnumValue == "干线到达") { var orders = oBll.GetOrderByCarcode(item.OrderCode); if (orders == null || orders.Count() == 0) { return("操作类型:" + item.SysEnumValue + "找不到订单号,有错误"); } foreach (var currOrderCode in orders) { currOsModel.OrderCode = currOrderCode; currOsdModel.OrderCode = currOrderCode; var oldOsdList = osdBll.GetList(currOrderCode); if (oldOsdList != null) { isOsdExists = oldOsdList.Exists(m => m.CurrNodeId.Equals(item.CurrNodeId)); } if (!isOsdExists) { SmsSendInfo ssiModel = new SmsSendInfo(); ssiModel.OrderCode = currOrderCode; ssiModel.TranNode = currSeModel.EnumCode; ssiModel.TranNodeText = currSeModel.EnumValue; using (TransactionScope scope = new TransactionScope()) { if (osBll.GetModel(currOrderCode) == null) { osBll.Insert(currOsModel); } else { osBll.Update(currOsModel); } osdBll.Insert(currOsdModel); scope.Complete(); } smsBll.InsertByStrategy(ssiModel); } } } else if (item.Sort == firstModel.Sort) { var oldOsModel = osBll.GetModel(item.OrderCode); if (oldOsModel == null) { SmsSendInfo ssiModel = new SmsSendInfo(); ssiModel.OrderCode = item.OrderCode; ssiModel.TranNode = currSeModel.EnumCode; ssiModel.TranNodeText = currSeModel.EnumValue; using (TransactionScope scope = new TransactionScope()) { osBll.Insert(currOsModel); osdBll.Insert(currOsdModel); scope.Complete(); } smsBll.InsertByStrategy(ssiModel); } } else { var oldOsModel = osBll.GetModel(item.OrderCode); if (oldOsModel == null) { return("订单号:" + item.OrderCode + ",操作类型:" + item.SysEnumValue + "未取货,有错误"); } var oldOsdList = osdBll.GetList(item.OrderCode); if (oldOsdList != null) { isOsdExists = oldOsdList.Exists(m => m.CurrNodeId.Equals(item.CurrNodeId)); currOsModel.IsFinish = oldOsdList.Count == 5; } if (currOsModel.IsFinish) { continue; } if (!isOsdExists) { SmsSendInfo ssiModel = new SmsSendInfo(); ssiModel.OrderCode = currOsModel.OrderCode; ssiModel.TranNode = currSeModel.EnumCode; ssiModel.TranNodeText = currSeModel.EnumValue; using (TransactionScope scope = new TransactionScope()) { osBll.Update(currOsModel); osdBll.Insert(currOsdModel); scope.Complete(); } smsBll.InsertByStrategy(ssiModel); } } Console.WriteLine("request: opType:{0},barCode:{1},scanTime:{3},user:{2}", item.SysEnumValue, item.OrderCode, item.ScanTime, item.UserName); } return("保存成功"); } catch (Exception ex) { return(ex.Message); } }
/// <summary> /// 新增PDA扫描数据 /// </summary> /// <param name="opType">操作类型</param> /// <param name="barCode">单号条码</param> /// <param name="scanTime">扫描时间</param> /// <param name="userName">用户名</param> /// <returns>返回:包含“成功”,则调用成功,否则返回调用失败原因</returns> public string Insert(string opType, string barCode, DateTime scanTime, string userName) { #region 参数合法性检查 if (string.IsNullOrEmpty(opType)) { return("操作类型不能为空"); } opType = opType.Trim(); if (string.IsNullOrEmpty(barCode)) { return("单号条码不能为空"); } barCode = barCode.Trim(); //if (barCode.Length != 13) //{ // return "单号条码不正确"; //} if (scanTime == DateTime.MinValue) { return("扫描时间格式不正确"); } if (string.IsNullOrEmpty(userName)) { return("用户不能为空"); } #endregion try { MembershipUser user = Membership.GetUser(userName); if (user == null) { return("不存在用户:" + userName); } SysEnum seBll = new SysEnum(); var seList = seBll.GetList("and t2.EnumCode = 'SendReceiveType'", null); if (seList == null || seList.Count == 0) { return("服务端的操作类型未设定,请先完成设定"); } var firstModel = seList.OrderBy(m => m.Sort).First(); var currSeModel = seList.Find(m => m.EnumValue.Trim() == opType); if (currSeModel == null) { return("当前操作类型“" + opType + "”不存在"); } object nextNodeId = Guid.Empty; var nextSeModel = seList.FindAll(m => m.Sort > currSeModel.Sort).OrderBy(m => m.Sort).FirstOrDefault(); if (nextSeModel == null) { nextNodeId = currSeModel.Id; } else { nextNodeId = nextSeModel.Id; } bool isOsdExists = false; PDAOrderScanInfo currOsModel = new PDAOrderScanInfo(); currOsModel.OrderCode = barCode; currOsModel.CurrNodeId = currSeModel.Id; currOsModel.NextNodeId = nextNodeId; currOsModel.IsFinish = false; currOsModel.LastUpdatedDate = DateTime.Now; PDAOrderScanDetailInfo currOsdModel = new PDAOrderScanDetailInfo(); currOsdModel.OrderCode = barCode; currOsdModel.CurrNodeId = currOsModel.CurrNodeId; currOsdModel.ScanTime = scanTime; currOsdModel.UserId = user.ProviderUserKey; currOsdModel.LastUpdatedDate = currOsModel.LastUpdatedDate; Order oBll = new Order(); PDAOrderScan osBll = new PDAOrderScan(); PDAOrderScanDetail osdBll = new PDAOrderScanDetail(); TyUser tyuBll = new TyUser(); SmsSend smsBll = new SmsSend(); string sRemark = ""; TyUserInfo tyuModel = tyuBll.GetModelByUser(user.UserName); if (tyuModel != null && !string.IsNullOrWhiteSpace(tyuModel.OrganizationName)) { sRemark = string.Format(currSeModel.Remark, tyuModel.OrganizationName); } else { sRemark = currSeModel.Remark.Replace(@"{0}", ""); } sRemark = currSeModel.EnumValue + ":" + sRemark; currOsdModel.Remark = sRemark; if (opType == "干线发运" || opType == "干线到达") { var orders = oBll.GetOrderByCarcode(barCode); if (orders == null || orders.Count() == 0) { return("操作类型:" + barCode + "找不到订单号,有错误"); } foreach (var currOrderCode in orders) { currOsModel.OrderCode = currOrderCode; currOsdModel.OrderCode = currOrderCode; var oldOsdList = osdBll.GetList(currOrderCode); if (oldOsdList != null) { isOsdExists = oldOsdList.Exists(m => m.CurrNodeId.Equals(currSeModel.Id)); } if (isOsdExists) { return("订单号:" + currOrderCode + " 操作类型:" + opType + "已存在,不能重复提交"); } //发短信 SmsSendInfo ssiModel = new SmsSendInfo(); ssiModel.OrderCode = currOrderCode; ssiModel.TranNode = currSeModel.EnumCode; ssiModel.TranNodeText = currSeModel.EnumValue; using (TransactionScope scope = new TransactionScope()) { if (osBll.GetModel(currOrderCode) == null) { osBll.Insert(currOsModel); } else { osBll.Update(currOsModel); } osdBll.Insert(currOsdModel); scope.Complete(); } smsBll.InsertByStrategy(ssiModel); } } else if (currSeModel.Sort == firstModel.Sort) { var oldOsModel = osBll.GetModel(barCode); if (oldOsModel != null) { return("订单号:" + barCode + ",操作类型:" + opType + "已存在,不能重复提交"); } SmsSendInfo ssiModel = new SmsSendInfo(); ssiModel.OrderCode = barCode; ssiModel.TranNode = currSeModel.EnumCode; ssiModel.TranNodeText = currSeModel.EnumValue; using (TransactionScope scope = new TransactionScope()) { osBll.Insert(currOsModel); osdBll.Insert(currOsdModel); scope.Complete(); } smsBll.InsertByStrategy(ssiModel); } else { var oldOsModel = osBll.GetModel(barCode); if (oldOsModel == null) { return("订单号:" + barCode + ",操作类型:" + opType + "未取货,有错误"); } var oldOsdList = osdBll.GetList(barCode); if (oldOsdList != null) { isOsdExists = oldOsdList.Exists(m => m.CurrNodeId.Equals(currSeModel.Id)); currOsModel.IsFinish = oldOsdList.Count == 5; } if (currOsModel.IsFinish) { return("订单号:" + barCode + "已完成所有操作"); } if (isOsdExists) { return("订单号:" + barCode + ",操作类型:" + opType + "已存在,不能重复提交"); } SmsSendInfo ssiModel = new SmsSendInfo(); ssiModel.OrderCode = barCode; ssiModel.TranNode = currSeModel.EnumCode; ssiModel.TranNodeText = currSeModel.EnumValue; using (TransactionScope scope = new TransactionScope()) { osBll.Update(currOsModel); osdBll.Insert(currOsdModel); scope.Complete(); } smsBll.InsertByStrategy(ssiModel); } Console.WriteLine("request: opType:{0},barCode:{1},scanTime:{3},user:{2}", opType, barCode, scanTime, userName); return("保存成功"); } catch (Exception ex) { return(ex.Message); } }
public IList <CategoryNotification> GetByUserAndCategory(MembershipUser user, Category category) { return(_context.CategoryNotification .Where(x => x.Category.Id == category.Id && x.User.Id == user.Id) .ToList()); }
public Guid SaveUserData() { if (!EditMode) { Guid result = Guid.Empty; if (Session["CameFromSocialNetwork"] == null) { MembershipCreateStatus status = MembershipCreateStatus.Success; MembershipUser user = Membership.Provider.CreateUser(tfEmail.Text, tfPwd.Text, tfEmail.Text, "question", "answer", true, Guid.NewGuid(), out status); this.lblError.Text = string.Empty; switch (status) { case MembershipCreateStatus.DuplicateEmail: case MembershipCreateStatus.DuplicateUserName: this.lblError.Text = Resources.Appleseed.USER_ALREADY_EXISTS; break; case MembershipCreateStatus.ProviderError: break; case MembershipCreateStatus.Success: UpdateProfile(); result = (Guid)user.ProviderUserKey; //if the user is registering himself (thus, is not yet authenticated) we will sign him on and send him to the home page. if (!Context.User.Identity.IsAuthenticated) { PortalSecurity.SignOn(tfEmail.Text, tfPwd.Text, false, HttpUrlBuilder.BuildUrl()); } break; // for every other error message... default: this.lblError.Text = Resources.Appleseed.USER_SAVING_ERROR; break; } return(result); } else { if ((Session["TwitterUserName"] != null) || (Session["LinkedInUserName"] != null)) { // Register Twitter or LinkedIn string userName = (Session["TwitterUserName"] != null) ? Session["TwitterUserName"].ToString() : Session["LinkedInUserName"].ToString(); string password = GeneratePasswordHash(userName); MembershipCreateStatus status = MembershipCreateStatus.Success; MembershipUser user = Membership.Provider.CreateUser(userName, password, tfEmail.Text, "question", "answer", true, Guid.NewGuid(), out status); this.lblError.Text = string.Empty; switch (status) { case MembershipCreateStatus.DuplicateEmail: case MembershipCreateStatus.DuplicateUserName: this.lblError.Text = Resources.Appleseed.USER_ALREADY_EXISTS; break; case MembershipCreateStatus.ProviderError: break; case MembershipCreateStatus.Success: UpdateProfile(); result = (Guid)user.ProviderUserKey; //if the user is registering himself (thus, is not yet authenticated) we will sign him on and send him to the home page. if (!Context.User.Identity.IsAuthenticated) { Session.Contents.Remove("CameFromSocialNetwork"); PortalSecurity.SignOn(userName, password, false, HttpUrlBuilder.BuildUrl()); } break; // for every other error message... default: this.lblError.Text = Resources.Appleseed.USER_SAVING_ERROR; break; } return(result); } else if (Session["FacebookUserName"] != null || Session["GoogleUserEmail"] != null) { // Register Facebook string userName = tfEmail.Text; string password = GeneratePasswordHash(userName); MembershipCreateStatus status = MembershipCreateStatus.Success; MembershipUser user = Membership.Provider.CreateUser(userName, password, userName, "question", "answer", true, Guid.NewGuid(), out status); this.lblError.Text = string.Empty; switch (status) { case MembershipCreateStatus.DuplicateEmail: case MembershipCreateStatus.DuplicateUserName: this.lblError.Text = Resources.Appleseed.USER_ALREADY_EXISTS; break; case MembershipCreateStatus.ProviderError: break; case MembershipCreateStatus.Success: UpdateProfile(); result = (Guid)user.ProviderUserKey; //if the user is registering himself (thus, is not yet authenticated) we will sign him on and send him to the home page. if (!Context.User.Identity.IsAuthenticated) { // Removing names from social networks of sessions if (Session["CameFromGoogleLogin"] != null) { Session.Contents.Remove("CameFromGoogleLogin"); } if (Session["GoogleUserEmail"] != null) { Session.Contents.Remove("GoogleUserEmail"); } if (Session["GoogleUserName"] != null) { Session.Contents.Remove("GoogleUserName"); } if (Session["FacebookUserName"] != null) { Session.Contents.Remove("FacebookUserName"); } if (Session["FacebookName"] != null) { Session.Contents.Remove("FacebookName"); } PortalSecurity.SignOn(userName, password, false, HttpUrlBuilder.BuildUrl()); } break; // for every other error message... default: this.lblError.Text = Resources.Appleseed.USER_SAVING_ERROR; break; } return(result); } else { return(result); } } } else { string Email = tfEmail.Text; string UserName = Membership.GetUserNameByEmail(Email); if (!UserName.Equals(Email)) { // The user Came from twitter Session["CameFromSocialNetwork"] = true; Session["TwitterUserName"] = UserName; Session["LinkedInUserName"] = UserName; Session["deleteCookies"] = true; } UpdateProfile(); return((Guid)Membership.GetUser(UserName, false).ProviderUserKey); } }
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { if (!ListBox1.SelectedValue.Equals("No Matches")) { int x = ListBox1.SelectedIndex; int comma = ListBox1.Items[x].Value.IndexOf(","); int bar = ListBox1.Items[x].Value.IndexOf("|"); int customerid = Convert.ToInt16(ListBox1.Items[x].Value.Substring(0, comma)); string MemberUsername = ListBox1.Items[x].Value.Substring(comma + 1, bar - comma - 1); string MemberEmail = ListBox1.Items[x].Value.Substring(bar + 1); customer = DataRepository.CustomerProvider.GetByCustomerId(customerid); customerprofile = DataRepository.CustomerProfileProvider.GetByCustomerId(customer.CustomerId)[0]; countrylookup = DataRepository.CountryLookupProvider.GetByCountryId(customer.Country); int SelectedFacilitynew = customerprofile.CustomerSite; customersite = DataRepository.CustomerSiteProvider.GetByCustomerSiteId(SelectedFacility); teacher = DataRepository.TeacherProvider.GetByTeacherId(customerprofile.Teacher); Guid MemGuid = new Guid(customer.AspnetMembershipUserId.ToString()); MembershipUser user = Membership.GetUser(MemGuid); string[] userrole = Roles.GetRolesForUser(user.UserName.ToString()); // DropDownList1.SelectedValue = SelectedFacilitynew.ToString(); //if (userrole.Length > 0) //{ // DropDownList2.SelectedValue = userrole[0]; //} //else //{ // DropDownList2.SelectedValue = "Golfers"; //} Label45.Text = customer.FirstName; Label7.Text = customer.LastName; Label9.Text = MemberUsername; Label11.Text = MemberEmail; if (!customer.Address1.ToLower().Equals("none")) { Label13.Text = customer.Address1; } else { Label13.Text = ""; } Label15.Text = customer.Address2; if (!customer.City.ToLower().Equals("none")) { Label17.Text = customer.City; } else { Label17.Text = ""; } if (!customer.State.ToLower().Equals("none")) { Label19.Text = customer.State; } else { Label19.Text = ""; } if (!customer.Zip.ToLower().Equals("none")) { Label21.Text = customer.Zip; } else { Label21.Text = ""; } if (customer.Address1.ToLower().Equals("none") && customer.Country.Equals(248)) { Label23.Text = ""; } else { Label23.Text = countrylookup.CountryName; } Label25.Text = customer.PhoneHome; Label27.Text = customer.PhoneWork; Label29.Text = customer.PhoneMobile; Label31.Text = customer.Fax; Label33.Text = customersite.SiteName; Label35.Text = teacher.FirstName + " " + teacher.LastName; Label37.Text = user.CreationDate.ToLongDateString(); Label39.Text = customer.MembershipExpiration.ToLongDateString(); switch (customer.MembershipStatus) { case 0: Label41.Text = "Expired"; break; case 1: Label41.Text = "Member"; break; case 2: Label41.Text = "Full Teaching"; break; case 3: Label41.Text = "Full Fitting"; break; case 4: Label41.Text = "Full Teaching & Fitting"; break; case 97: Label41.Text = "Comp Teaching"; break; case 98: Label41.Text = "Comp Fitting"; break; case 99: Label41.Text = "Comp Teaching & Fitting"; break; default: Label41.Text = "Missing"; break; } } }
/// <summary> /// Setups the user profile. /// </summary> /// <param name="user">The user.</param> /// <param name="userId">The user identifier.</param> private void SetupUserProfile(MembershipUser user, int userId) { // this is the "Profile Information" step. Save the data to their profile (+ defaults). var timeZones = (DropDownList)this.CreateUserWizard1.FindWizardControlRecursive("TimeZones"); var country = (DropDownList)this.CreateUserWizard1.FindWizardControlRecursive("Country"); var locationTextBox = (TextBox)this.CreateUserWizard1.FindWizardControlRecursive("Location"); var homepageTextBox = (TextBox)this.CreateUserWizard1.FindWizardControlRecursive("Homepage"); var dstUser = (CheckBox)this.CreateUserWizard1.FindWizardControlRecursive("DSTUser"); // setup/save the profile YafUserProfile userProfile = YafUserProfile.GetProfile(this.CreateUserWizard1.UserName); if (country.SelectedValue != null) { userProfile.Country = country.SelectedValue; } string result; if (this.Get <ISpamWordCheck>().CheckForSpamWord(homepageTextBox.Text.Trim(), out result)) { this.IsPossibleSpamBotInternalCheck = true; var userIpAddress = this.Get <HttpRequestBase>().GetUserRealIPAddress(); if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1)) { // Flag user as spam bot this.IsPossibleSpamBot = true; this.SendSpamBotNotificationToAdmins(user, userId); } else if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(2)) { // Kill user UserMembershipHelper.DeleteAndBanUser(userId, user, userIpAddress); this.PageContext.AddLoadMessage(this.GetText("BOT_MESSAGE"), MessageTypes.Error); } this.Logger.Log( null, "Bot Detected", "Internal Spam Word Check detected a SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}') reason word: {3}" .FormatWith(user.UserName, this.CreateUserWizard1.Email, userIpAddress, homepageTextBox.Text.Trim()), EventLogTypes.SpamBotDetected); } if (!this.IsPossibleSpamBotInternalCheck) { userProfile.Location = locationTextBox.Text.Trim(); userProfile.Homepage = homepageTextBox.Text.Trim(); userProfile.Save(); // save the time zone... LegacyDb.user_save( userID: userId, boardID: this.PageContext.PageBoardID, userName: null, displayName: null, email: null, timeZone: timeZones.SelectedValue.ToType <int>(), languageFile: null, culture: null, themeFile: null, textEditor: null, useMobileTheme: null, approved: null, pmNotification: null, autoWatchTopics: null, dSTUser: dstUser.Checked, hideUser: null, notificationType: null); bool autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... LegacyDb.user_savenotification( userId, true, autoWatchTopicsEnabled, this.Get <YafBoardSettings>().DefaultNotificationSetting, this.Get <YafBoardSettings>().DefaultSendDigestEmail); } }
protected void Button2_Click(object sender, EventArgs e) { bool teacherexists = false; Customer tc = new Customer(); Teacher teach = new Teacher(); TeacherSite teachersite = new TeacherSite(); int customerid = -1; bool CurrentTeacher = false; if (!ListBox1.SelectedValue.Equals("No Matches") && !ListBox1.Items.Count.Equals(0)) { int x = ListBox1.SelectedIndex; int comma = ListBox1.Items[x].Value.IndexOf(","); customerid = Convert.ToInt16(ListBox1.Items[x].Value.Substring(0, comma)); } //MessageBox.Show("customerid: " + customerid.ToString()); if (!customerid.Equals(-1)) { tc = DataRepository.CustomerProvider.GetByCustomerId(customerid); try { teach = DataRepository.TeacherProvider.GetByAspnetMembershipUserId(tc.AspnetMembershipUserId)[0]; //MessageBox.Show("Teacher First Name: " + teach.FirstName); CurrentTeacher = true; } catch (Exception ex) { //Selected member is not a current Teacher in database //MessageBox.Show("Not a current teacher"); CurrentTeacher = false; } if (CurrentTeacher) { foreach (TeacherSite ts in facilityteachers) { if (ts.TeacherId == teach.TeacherId) { teacherexists = true; } } if (!teacherexists) { customer = DataRepository.CustomerProvider.GetByCustomerId(customerid); MembershipUser user = Membership.GetUser(customer.AspnetMembershipUserId); try { Roles.AddUserToRole(user.UserName, "Teachers"); } catch { } teachersite.SiteId = SelectedFacility; teachersite.TeacherId = teach.TeacherId; DataRepository.TeacherSiteProvider.Insert(teachersite); } else { //Label1.Text = "This teacher is already exists for this facility"; } } else { teach.FirstName = tc.FirstName; teach.LastName = tc.LastName; teach.WorkPhone = tc.PhoneWork; teach.MobilePhone = tc.PhoneMobile; teach.AspnetMembershipUserId = tc.AspnetMembershipUserId; teach.PicturePath = "/TeacherPics/" + tc.FirstName + tc.LastName + ".jpg"; teach.BioText = "Bio Text"; teach.WelcomeText = "<P>Welcome to the SwingModel learning program. If you haven't " + "taken a look at your most recent lesson video(s), please visit the My Swing " + "page. There you will be able to review the errors we discussed during the " + "lesson. For further review, you may click on the My Summary button in the " + "video player. Continue working the drills as discussed in the lesson. If " + "you'd like to ask questions about your swing or golf game, click on the Email " + "My Teacher link. Be sure to schedule a lesson with me in the near future. You " + "can request a lesson appointment time by clicking on the Schedule A Lesson " + "link.</P>"; foreach (TeacherSite ts in facilityteachers) { if (ts.TeacherId == teach.TeacherId && ts.SiteId == teachersite.SiteId) { teacherexists = true; } } if (!teacherexists) { customer = DataRepository.CustomerProvider.GetByCustomerId(customerid); MembershipUser user = Membership.GetUser(customer.AspnetMembershipUserId); try { Roles.AddUserToRole(user.UserName, "Teachers"); } catch { } } else { //Label1.Text = "This teacher is already exists for this facility"; } teach.TeachingPassword = tc.FirstName; DataRepository.TeacherProvider.Insert(teach); teachersite.SiteId = SelectedFacility; teachersite.TeacherId = teach.TeacherId; DataRepository.TeacherSiteProvider.Insert(teachersite); } } this.Page.Response.Redirect("~/Facility/AddTeachers.aspx"); }
protected void Registry1_CreatedUser(object sender, EventArgs e) { cUser myUser = new cUser(); MembershipUser newUser = Membership.GetUser(Registry1.UserName); Guid newUserId = (Guid)newUser.ProviderUserKey; myUser.UserName = ((TextBox)Registry1.CreateUserStep.ContentTemplateContainer.FindControl("UserName")).Text; myUser.Email = ((TextBox)Registry1.CreateUserStep.ContentTemplateContainer.FindControl("Email")).Text; myUser.FirstName = ((TextBox)Registry1.CreateUserStep.ContentTemplateContainer.FindControl("tbFirstName")).Text; myUser.LastName = ((TextBox)Registry1.CreateUserStep.ContentTemplateContainer.FindControl("tbLastName")).Text; myUser.SSN = ((TextBox)Registry1.CreateUserStep.ContentTemplateContainer.FindControl("tbSSN")).Text; myUser.PhoneNumber = ((TextBox)Registry1.CreateUserStep.ContentTemplateContainer.FindControl("tbPhoneNumber")).Text; myUser.Street = ((TextBox)Registry1.CreateUserStep.ContentTemplateContainer.FindControl("tbAddress")).Text; myUser.ZIP = Convert.ToInt16(((TextBox)Registry1.CreateUserStep.ContentTemplateContainer.FindControl("tbZIP")).Text); myUser.County = ((TextBox)Registry1.CreateUserStep.ContentTemplateContainer.FindControl("tbCounty")).Text; myUser.Password = ((TextBox)Registry1.CreateUserStep.ContentTemplateContainer.FindControl("Password")).Text; string connStr = ConfigurationManager.ConnectionStrings["MedusaConnectionString"].ToString(); // Create a connection SqlConnection conn = new SqlConnection(connStr); // Name of the Procedure I want to call SqlCommand cmd = new SqlCommand("uspRegistry", conn); // Type of commad I want to execute cmd.CommandType = CommandType.StoredProcedure; try { conn.Open(); // Insert the Parameter to the procedure cmd.Parameters.AddWithValue("@UserName", myUser.UserName); cmd.Parameters.AddWithValue("@Email", myUser.Email); cmd.Parameters.AddWithValue("@FirstName", myUser.FirstName); cmd.Parameters.AddWithValue("@LastName", myUser.LastName); cmd.Parameters.AddWithValue("@SSN", myUser.SSN); cmd.Parameters.AddWithValue("@PhoneNumber", myUser.PhoneNumber); cmd.Parameters.AddWithValue("@Street", myUser.Street); cmd.Parameters.AddWithValue("@ZIP", myUser.ZIP); cmd.Parameters.AddWithValue("@County", myUser.County); cmd.Parameters.AddWithValue("@Password", myUser.Password); // Execute my procedure and load the result to dr cmd.ExecuteReader(); cUser myResultUser = new cUser(); DAL myDAL = new DAL(); myResultUser = myDAL.Login(myUser); if (myResultUser.UserId > 0) { Session.Add("UserId", myResultUser.UserId.ToString()); Response.Redirect("MyPage.aspx"); } } catch { // If error throw; } finally { // Close and dispose all connections to the databse cmd.Dispose(); conn.Close(); conn.Dispose(); } }
public bool Rule(MembershipUser user) { var anniversary = new DateTime(user.CreateDate.Year + 1, user.CreateDate.Month, user.CreateDate.Day); return(DateTime.UtcNow >= anniversary); }
public override void UpdateUser(MembershipUser user) { LogDebug("Entering UpdateUser"); throw new System.NotImplementedException(); }
public AdminProfileUpdatedActivity(Activity activity, MembershipUser user, MembershipUser admin) { ActivityMapped = activity; User = user; Admin = admin; }
public string ConnectFromAndroid(string username, string password, string device, string version, string fonction) { DateTime dt = DateTime.Now; string comment = ""; string code = "ok"; string token = "0"; if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { return(token); } SqlConnection conn = new SqlConnection(DotNetNuke.Common.Utilities.Config.GetConnectionString()); try { UserInfo user = UserController.GetUserByName(Globals.GetPortalSettings().PortalId, username); if (user != null) { MembershipUser objUser = Membership.GetUser(user.Username); if (objUser != null) { string strPassword = objUser.GetPassword(); if (!string.IsNullOrEmpty(strPassword)) { string defaultPassMD5 = Functions.CalculateMD5Hash(Functions.StringToBytes(strPassword)); if (!string.IsNullOrEmpty(defaultPassMD5)) { if (password.ToLower() == defaultPassMD5.ToLower()) { token = "1"; //break; } } else { throw new Exception("defaultPassMD5 NULL ou vide pour le username " + username); } } else { throw new Exception("strPassword NULL ou vide pour le username " + username); } } else { throw new Exception("objUser NULL pour le username " + username); } } else { throw new Exception("user NULL pour le username " + username); } } catch (Exception ee) { Functions.Error(ee); comment = ee.ToString(); code = "erreur"; } finally { conn.Close(); conn.Dispose(); if (token == "1") { comment = "Identification réussie"; } else { if (comment == "") { comment = "Identification refusée"; } } DataMapping.InsertLogWS(os, device, version, getIP(), dt, getDuree(dt), fonction, code, comment, username); } return(token); }
public override void UpdateUser(MembershipUser user) { throw new NotImplementedException(); }
/// <summary> /// Post is marked as the answer to a topic - give the topic author a badge /// </summary> /// <returns></returns> public bool Rule(MembershipUser user) { var allCats = _categoryService.GetAll(); return(_topicService.GetSolvedTopicsByMember(user.Id, allCats).Count >= 1); }
public IList <TagNotification> GetByUser(MembershipUser user) { return(_notificationRepository.GetByUser(user)); }
public override void UpdateUser(MembershipUser user) { }
public IList <TagNotification> GetByUserAndTag(MembershipUser user, TopicTag tag, bool addTracking = false) { return(_notificationRepository.GetByUserAndTag(user, tag, addTracking)); }
/// <summary> /// The create users. /// </summary> /// <param name="boardID"> /// The board id. /// </param> /// <param name="_users_Number"> /// The _users_ number. /// </param> /// <param name="_outCounter"> /// The _out counter. /// </param> /// <param name="_countLimit"> /// The _count limit. /// </param> /// <param name="_excludeCurrentBoard"> /// The _exclude current board. /// </param> /// <returns> /// The string with number of created users. /// </returns> private string CreateUsers( int boardID, int _users_Number, int _outCounter, int _countLimit, bool _excludeCurrentBoard) { int iboards; // if ( _users_Number > createCommonLimit ) _users_Number = createCommonLimit; for (iboards = 0; iboards < _countLimit; iboards++) { boardID = this.UsersBoardsList.Items[iboards].Value.ToType <int>(); int i; for (i = 0; i < this.UsersNumber.Text.Trim().ToType <int>(); i++) { this.randomGuid = Guid.NewGuid().ToString(); string newEmail = this.UserPrefixTB.Text.Trim() + this.randomGuid + "@test.info"; string newUsername = this.UserPrefixTB.Text.Trim() + this.randomGuid; if (UserMembershipHelper.UserExists(newUsername, newEmail)) { continue; } string hashinput = DateTime.UtcNow + newEmail + Security.CreatePassword(20); string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5"); MembershipCreateStatus status; MembershipUser user = this.Get <MembershipProvider>().CreateUser( newUsername, this.Password.Text.Trim(), newEmail, this.Question.Text.Trim(), this.Answer.Text.Trim(), !this.Get <YafBoardSettings>().EmailVerification, null, out status); if (status != MembershipCreateStatus.Success) { continue; } // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(boardID, newUsername); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, boardID); // create profile YafUserProfile userProfile = YafUserProfile.GetProfile(newUsername); // setup their inital profile information userProfile.Location = this.Location.Text.Trim(); userProfile.Homepage = this.HomePage.Text.Trim(); userProfile.Save(); // save the time zone... if ( !(this.UsersBoardsList.Items[iboards].Value.ToType <int>() == YafContext.Current.PageBoardID && _excludeCurrentBoard)) { LegacyDb.user_save( LegacyDb.user_get(boardID, user.ProviderUserKey), boardID, null, null, null, this.TimeZones.SelectedValue.ToType <int>(), null, null, null, null, null, null, null, null, null, null, null); _outCounter++; } } } return(_outCounter + " Users in " + iboards + " Board(s); "); }
protected void Page_Load(object sender, EventArgs e) { Master.ActivateTab(AdminBaseMasterPage.SectionID.ContentAdd); RedirectIfNoSite(); lblUpdated.Text = SiteData.CurrentSite.Now.ToString(); lblCreateDate.Text = SiteData.CurrentSite.Now.ToString(); iPageCount = pageHelper.GetSitePageCount(SiteID, ContentPageType.PageType.ContentEntry); guidContentID = GetGuidIDFromQuery(); guidVersionContentID = GetGuidParameterFromQuery("versionid"); guidImportContentID = GetGuidParameterFromQuery("importid"); if (!IsPostBack) { if (iPageCount < 1) { txtSort.Text = "0"; } else { int iOrder = pageHelper.GetMaxNavOrder(SiteID) + 1; txtSort.Text = iOrder.ToString(); } } sPageMode = GetStringParameterFromQuery("mode"); if (sPageMode.ToLower() == "raw") { reBody.CssClass = "rawEditor"; reLeftBody.CssClass = "rawEditor"; reRightBody.CssClass = "rawEditor"; divCenter.Visible = false; divRight.Visible = false; divLeft.Visible = false; } if (!IsPostBack) { DateTime dtSite = CalcNearestFiveMinTime(SiteData.CurrentSite.Now); txtReleaseDate.Text = dtSite.ToShortDateString(); txtReleaseTime.Text = dtSite.ToShortTimeString(); txtRetireDate.Text = dtSite.AddYears(200).ToShortDateString(); txtRetireTime.Text = dtSite.AddYears(200).ToShortTimeString(); hdnRootID.Value = Guid.Empty.ToString(); ParentPagePicker.RootContentID = Guid.Empty; ContentPage pageContents = null; if (guidVersionContentID != Guid.Empty) { pageContents = pageHelper.GetVersion(SiteID, guidVersionContentID); } if (guidContentID != Guid.Empty && pageContents == null) { pageContents = pageHelper.FindContentByID(SiteID, guidContentID); } if (guidImportContentID != Guid.Empty) { ContentPageExport cpe = ContentImportExportUtils.GetSerializedContentPageExport(guidImportContentID); if (cpe != null) { pageContents = cpe.ThePage; pageContents.EditDate = SiteData.CurrentSite.Now; var rp = pageHelper.GetLatestContentByURL(SiteID, false, pageContents.FileName); if (rp != null) { pageContents.Root_ContentID = rp.Root_ContentID; pageContents.ContentID = rp.ContentID; pageContents.Parent_ContentID = rp.Parent_ContentID; pageContents.NavOrder = rp.NavOrder; } else { pageContents.Root_ContentID = Guid.Empty; pageContents.ContentID = Guid.Empty; pageContents.NavOrder = pageHelper.GetSitePageCount(SiteID, ContentPageType.PageType.ContentEntry); } } } //if (pageContents == null) { // pageContents = new ContentPage(SiteData.CurrentSiteID, ContentPageType.PageType.ContentEntry); //} List <ContentPage> lstContent = pageHelper.GetAllLatestContentList(SiteID); GeneralUtilities.BindList(ddlTemplate, cmsHelper.Templates); chkDraft.Visible = false; divEditing.Visible = false; float iThird = (float)(iPageCount - 1) / (float)3; Dictionary <string, float> dictTemplates = pageHelper.GetPopularTemplateList(SiteID, ContentPageType.PageType.ContentEntry); if (dictTemplates.Any() && dictTemplates.First().Value >= iThird) { try { GeneralUtilities.SelectListValue(ddlTemplate, dictTemplates.First().Key); } catch { } } if (pageContents == null) { btnDeleteButton.Visible = false; } if (pageContents != null) { bool bRet = pageHelper.RecordPageLock(pageContents.Root_ContentID, SiteData.CurrentSite.SiteID, SecurityData.CurrentUserGuid); if (pageContents.ContentType != ContentPageType.PageType.ContentEntry) { Response.Redirect(SiteFilename.BlogPostAddEditURL + "?id=" + Request.QueryString.ToString()); } cmsHelper.OverrideKey(pageContents.Root_ContentID); cmsHelper.cmsAdminContent = pageContents; cmsHelper.cmsAdminWidget = pageContents.GetWidgetList(); BindTextDataGrid(); guidRootContentID = pageContents.Root_ContentID; hdnRootID.Value = guidRootContentID.ToString(); txtOldFile.Text = pageContents.FileName; if (guidImportContentID != Guid.Empty) { txtOldFile.Text = ""; } Dictionary <string, string> dataVersions = (from v in pageHelper.GetVersionHistory(SiteID, pageContents.Root_ContentID) join u in ExtendedUserData.GetUserList() on v.EditUserId equals u.UserId orderby v.EditDate descending select new KeyValuePair <string, string>(v.ContentID.ToString(), string.Format("{0} ({1}) {2}", v.EditDate, u.UserName, (v.IsLatestVersion ? " [**] " : " "))) ).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); GeneralUtilities.BindListDefaultText(ddlVersions, dataVersions, null, "Page Versions", "00000"); bLocked = pageHelper.IsPageLocked(pageContents); pnlHB.Visible = !bLocked; pnlButtons.Visible = !bLocked; divEditing.Visible = bLocked; chkDraft.Visible = !bLocked; pnlHBEmpty.Visible = bLocked; if (bLocked && pageContents.Heartbeat_UserId != null) { MembershipUser usr = SecurityData.GetUserByGuid(pageContents.Heartbeat_UserId.Value); litUser.Text = "Read only mode. User '" + usr.UserName + "' is currently editing the page."; } txtTitle.Text = pageContents.TitleBar; txtNav.Text = pageContents.NavMenuText; txtHead.Text = pageContents.PageHead; txtFileName.Text = pageContents.FileName; txtThumb.Text = pageContents.Thumbnail; txtDescription.Text = pageContents.MetaDescription; txtKey.Text = pageContents.MetaKeyword; txtSort.Text = pageContents.NavOrder.ToString(); lblUpdated.Text = pageContents.EditDate.ToString(); lblCreateDate.Text = pageContents.CreateDate.ToString(); reBody.Text = pageContents.PageText; reLeftBody.Text = pageContents.LeftPageText; reRightBody.Text = pageContents.RightPageText; chkActive.Checked = pageContents.PageActive; chkNavigation.Checked = pageContents.ShowInSiteNav; chkSiteMap.Checked = pageContents.ShowInSiteMap; chkHide.Checked = pageContents.BlockIndex; GeneralUtilities.BindDataBoundControl(gvTracks, pageContents.GetTrackbacks()); txtReleaseDate.Text = pageContents.GoLiveDate.ToShortDateString(); txtReleaseTime.Text = pageContents.GoLiveDate.ToShortTimeString(); txtRetireDate.Text = pageContents.RetireDate.ToShortDateString(); txtRetireTime.Text = pageContents.RetireDate.ToShortTimeString(); if (pageContents.CreditUserId.HasValue) { var usr = new ExtendedUserData(pageContents.CreditUserId.Value); hdnCreditUserID.Value = usr.UserName; txtSearchUser.Text = string.Format("{0} ({1})", usr.UserName, usr.EmailAddress); } if (pageContents.Parent_ContentID.HasValue) { ParentPagePicker.SelectedPage = pageContents.Parent_ContentID.Value; } GeneralUtilities.SelectListValue(ddlTemplate, pageContents.TemplateFile.ToLower()); } } ParentPagePicker.RootContentID = guidRootContentID; SetBlankText(reBody); SetBlankText(reLeftBody); SetBlankText(reRightBody); if (ddlVersions.Items.Count < 1) { pnlReview.Visible = false; } }