protected void ButtonAddMembership_Click(object sender, EventArgs e) { // TODO: Re-authorize? int organizationId = Convert.ToInt32(dropOrganizations.SelectedValue); Person person = Person.FromIdentity(Convert.ToInt32("" + Request["id"])); if (_authority.HasPermission(Permission.CanEditMemberships, organizationId, -1, Authorization.Flag.AnyGeography)) { int viewingPersonId = Convert.ToInt32(HttpContext.Current.User.Identity.Name); DateTime paidUntil = DateTime.Now.AddYears(1); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MembershipAdd, "Membership in " + Organization.FromIdentity(organizationId).NameShort + " added manually.", "Membership was added by " + Person.FromIdentity(viewingPersonId) + " (#" + viewingPersonId.ToString() + ") to last until " + paidUntil.ToString("yyyy-MMM-dd") + "."); Membership.Create(person.PersonId, organizationId, paidUntil); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.PirateWeb, EventType.AddedMembership, viewingPersonId, organizationId, person.GeographyId, person.PersonId, 0, string.Empty); ReadMembershipList(); gridMemberships.DataBind(); PopulateOrganizations(); } }
internal static void RemindExpiries(DateTime dateExpiry) { Organizations orgs = Organizations.GetAll(); foreach (Organization org in orgs) { Memberships memberships = Memberships.GetExpiring(org, dateExpiry); // Mail each expiring member foreach (Membership membership in memberships) { try { SendReminderMail(membership); PWLog.Write(PWLogItem.Person, membership.PersonId, PWLogAction.MembershipRenewReminder, "Mail was sent to " + membership.Person.Mail + " reminding to renew membership in " + membership.Organization.Name + ".", string.Empty); } catch (Exception ex) { ExceptionMail.Send( new Exception("Failed to create reminder mail for person " + membership.PersonId, ex)); } } } }
protected void AuditField(string field, string oldVal, string newVal) { if (executor != null && ("" + oldVal).Trim() != ("" + newVal).Trim()) { PWLog.Write(executor, PWLogItem.Person, this.person.Identity, PWLogAction.PersonFieldChange, actionDescr, "", field, "" + oldVal, "" + newVal); } }
protected void GridMemberships_RowCommand(object sender, GridViewCommandEventArgs e) { // TODO: Re-authorize? int index = Convert.ToInt32(e.CommandArgument); int viewingPersonId = Convert.ToInt32(HttpContext.Current.User.Identity.Name); int membershipId = Convert.ToInt32(this.gridMemberships.DataKeys[index].Value); Membership membership = Membership.FromIdentity(membershipId); BasicPerson person = Person.FromIdentity(membership.PersonId); switch (e.CommandName) { case "Extend": if (membership.Expires.Year <= DateTime.Now.Year || membership.Active == false) { if (membership.Active == false && membership.Expires < DateTime.Now.AddYears(1)) { membership.Expires = DateTime.Now.AddYears(1); } else if (membership.Expires > DateTime.Now.AddYears(1)) { membership.Expires = membership.Expires.AddSeconds(1); } else { membership.Expires = membership.Expires.AddYears(1); } PWLog.Write(Person.FromIdentity(viewingPersonId), PWLogItem.Person, person.Identity, PWLogAction.MembershipRenewed, "Membership in " + Organization.FromIdentity(membership.OrganizationId).NameShort + " extended manually.", "Membership was extended by " + Person.FromIdentity(viewingPersonId).Name + " (#" + viewingPersonId.ToString() + ") to last until " + membership.Expires.ToString("yyyy-MMM-dd") + "."); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.PirateWeb, EventType.ExtendedMembership, viewingPersonId, membership.OrganizationId, person.GeographyId, membership.PersonId, membershipId, string.Empty); } ReadMembershipList(); break; case "Terminate": if (membership.Active) { Membership.FromIdentity(membershipId).Terminate(EventSource.PirateWeb, Person.FromIdentity(viewingPersonId), "Membership in " + Organization.FromIdentity(membership.OrganizationId).NameShort + " removed manually."); ReadMembershipList(); PopulateOrganizations(); CheckStillVisible(); } break; default: throw new InvalidOperationException("Not supported: Command \"" + e.CommandName + "\""); } gridMemberships.DataBind(); }
protected void ButtonDelete_Click(object sender, EventArgs e) { if (_authority.HasPermission(Permission.CanEditMailDB, Organization.PPSEid, -1, Authorization.Flag.AnyGeographyExactOrganization)) { MailServerDatabase.DeleteAccount(account); PWLog.Write(_currentUser, PWLogItem.MailAccount, 0, PWLogAction.MailAccountChanged, "Deleted account", "Manually changed in PW", account, "", ""); ScriptManager.RegisterStartupScript(this, this.GetType(), "saved", "CloseAndRebind();", true); } }
protected void ButtonDeleteMail_Click(object sender, EventArgs e) { Person _currentUser = Person.FromIdentity(Convert.ToInt32(HttpContext.Current.User.Identity.Name)); Authority _authority = _currentUser.GetAuthority(); if (_authority.HasPermission(Permission.CanEditMailDB, Organization.PPSEid, -1, Authorization.Flag.AnyGeographyExactOrganization)) { MailServerDatabase.DeleteAccount(TextPartyEmail.Text); PWLog.Write(_currentUser, PWLogItem.MailAccount, 0, PWLogAction.MailAccountChanged, "Deleted account", "Manually changed in PW", TextPartyEmail.Text, "", ""); TextPartyEmail.Text = ""; } }
protected void Button1_Click(object sender, EventArgs e) { if (_authority.HasRoleType(Activizr.Basic.Enums.RoleType.SystemAdmin)) { int persId = Int32.Parse("" + TextBoxPersId.Text); int currentUserId = _currentUser.Identity; Person p = Person.FromIdentity(persId); FormsAuthentication.SetAuthCookie("" + persId, false); PWLog.Write(currentUserId, PWLogItem.Person, persId, PWLogAction.StartImpersonation, "Impersonating user #" + p.Identity + " " + p.Name, ""); Session["ImpersonationInProgress"] = currentUserId; Label1.Text = "Logged in as #" + p.Identity + " " + p.Name; Panel1.Visible = false; } }
public override bool Handle(PhoneMessage msg) { string from = "*****@*****.**"; string to = "*****@*****.**"; string subject = "SMS från '" + msg.FromNumber + "'"; string body = "Inkommet från telefonnummer: " + msg.FromNumber + "\r\n" + "Meddelande: " + msg.Message + "\r\n" + "Skickades: " + msg.SentAt.ToShortDateString() + " " + msg.SentAt.ToShortTimeString() + "\r\n\r\n"; if (msg.People.Count > 0) { foreach (BasicPerson bp in msg.People.Values) { body += "Det telefonnumret tillhör medlem/aktivistnummer: "; Person person = Person.FromBasic(bp); body += person.Identity + " ("; if (!person.IsActivist) { body += "ej "; } body += "aktivist) \r\n"; } string numbers = ""; foreach (BasicPerson bp in msg.People.Values) { numbers += "," + bp.PersonId; } body += "\r\n\r\n" + numbers.Substring(1); } else { body += "Hittade ingen medlem/aktivist i databasen med det numret.\r\n\r\n"; } if (msg.ErrorMessage != "") { body += "\r\nComment from SMS processing: " + msg.ErrorMessage; } ForwardMessage(from, to, subject, body); msg.ReplyMessage += "\r\nDitt meddelande har vidarebefordrats till [email protected]. Kontakta oss om du undrar över något."; PWLog.Write(PWLogItem.None, 0, PWLogAction.SMSHandled, "Forwarded SMS from " + msg.FromNumber + " to " + to, msg.Message + "\r\n" + msg.ErrorMessage); return(true); }
protected void ButtonClose_Click(object sender, EventArgs e) { string volunteerIdString = Request.QueryString["VolunteerId"]; int volunteerId = Int32.Parse(volunteerIdString); Volunteer volunteer = Volunteer.FromIdentity(volunteerId); int currentUserId = Convert.ToInt32(HttpContext.Current.User.Identity.Name); Person currentUser = Person.FromIdentity(currentUserId); int organizationId = 0; Memberships memberships = volunteer.Person.GetMemberships(); foreach (Membership membership in memberships) { if (volunteer.Roles.Count > 0 && membership.OrganizationId == volunteer.Roles[0].OrganizationId) { organizationId = volunteer.Roles[0].OrganizationId; // Assume same org across all roles } } foreach (VolunteerRole role in volunteer.Roles) { bool assigned = this.ChecksVolunteerRoles.Items.FindByValue(role.Identity.ToString()).Selected; role.Close(assigned); if (organizationId == role.OrganizationId && assigned) { // If identified as member, autoassign & log volunteer.Person.AddRole(role.RoleType, role.OrganizationId, role.GeographyId); PWLog.Write(currentUser, PWLogItem.Person, volunteer.PersonId, PWLogAction.RoleAssigned, "Assigned Role [" + role.RoleType.ToString() + "] for organization [" + Organization.FromIdentity(role.OrganizationId).Name + "] and geography [" + role.Geography.Name + "]", string.Empty); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.PirateWeb, EventType.AddedRole, currentUserId, Organization.PPSEid, role.GeographyId, volunteer.PersonId, 0, string.Empty); } } volunteer.Close(this.TextAssessment.Text); // Close window and force refresh ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind();", true); }
protected void Page_Load(object sender, EventArgs e) { string result = "Tyvärr kunde vi inte tolka parametrarna riktigt. Kontakta medlemsservice på [email protected]."; int personId = 0; if (Int32.TryParse(Request.QueryString ["MemberId"], out personId)) { // Ok, at least we have a valid person id. Person person = Person.FromIdentity(personId); DateTime newExpiry = DateTime.MinValue; Memberships memberships = person.GetRecentMemberships(Membership.GracePeriod); bool ok = false; foreach (Membership membership in memberships) { string expectedHash = SHA1.Hash("Pirate" + person.Identity.ToString() + membership.Expires.Date.ToString("yyyyMMdd")).Replace(" ", "").Substring(0, 8); if (Request.QueryString ["SecHash"] == expectedHash) { ok = true; newExpiry = membership.Expires.Date.AddYears(1); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.ReceivedMembershipPayment, person.Identity, membership.OrganizationId, person.Geography.Identity, person.Identity, 0, Request.UserHostAddress); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MembershipRenewed, "Membership in " + membership.Organization.NameShort + " renewed.", "Membership was renewed from IP " + Request.UserHostAddress + "."); break; } } if (ok) { result = "Tack för att du förnyar! Ditt medlemskap går nu ut " + newExpiry.ToString("yyyy-MM-dd") + ". Du kommer också att få ett mail som bekräftar din förnyelse."; } else { PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.Failure, "Members failed to renew:" + Request.RawUrl, "Membership was renewed from IP " + Request.UserHostAddress + "."); } this.LabelResults.Text = result; } }
protected void Page_Load(object sender, EventArgs e) { string result = "Tyvärr kunde vi inte tolka parametrarna riktigt. Kontakta medlemsservice på [email protected]."; int personId = 0; if (Int32.TryParse(Request.QueryString ["MemberId"], out personId)) { // Ok, at least we have a valid person id. Person person = Person.FromIdentity(personId); DateTime newExpiry = DateTime.MinValue; bool ok = false; string expectedHash = person.PasswordHash.Replace(" ", "").Substring(0, 8); if (person.IsActivist == true) { result = "Du är redan pirataktivist."; } else if (Request.QueryString ["SecHash"] == expectedHash) { ok = true; Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.NewActivist, person.Identity, Organization.PPSEid, person.Geography.Identity, person.Identity, 0, string.Empty); } if (ok) { result = "Tack för att du väljer att bli aktivist! Du får strax ett email som förklarar mer. "; person.CreateActivist(false, true); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.ActivistJoin, "Joined as activist", string.Empty); } this.LabelResults.Text = result; } }
internal static void RemindExpiriesSms(DateTime dateExpiry, string message) { // For the time being, only remind for org 1. int[] organizationIds = new int[] { Organization.PPSEid }; foreach (int organizationId in organizationIds) { Memberships memberships = Memberships.GetExpiring(Organization.FromIdentity(organizationId), dateExpiry); // Mail each expiring member foreach (Membership membership in memberships) { Person person = membership.Person; if (People.FromPhoneNumber("SE", person.Phone).Count == 1) { if (SendReminderSms(person, message)) { PWLog.Write(PWLogItem.Person, membership.PersonId, PWLogAction.MembershipRenewReminder, "SMS was sent to " + membership.Person.Phone + " reminding to renew membership.", string.Empty); } else { PWLog.Write(PWLogItem.Person, membership.PersonId, PWLogAction.MembershipRenewReminder, "Unable to send SMS to " + membership.Person.Phone + "; tried to remind about renewing membership.", string.Empty); } } } } }
/// <summary> /// Find a log entry in PWLog that corresponds to the event and return the IP address from it /// </summary> /// <param name="dateTime"></param> /// <param name="affectedPersonId"></param> /// <param name="actingPersonId"></param> /// <returns></returns> private static string FindIPForEventInLog(DateTime dateTime, int affectedPersonId, int actingPersonId) { BasicPWLog[] logArr = PWLog.GetLatestEvents(PWLogItem.Person, DateTime.Now, new int[] { affectedPersonId }, new PWLogAction[] { PWLogAction.MemberAdd, PWLogAction.MemberJoin, PWLogAction.MembershipAdd, PWLogAction.MembershipRenewed }); foreach (BasicPWLog log in logArr) { if (log.AffectedItemId == affectedPersonId && log.ActingPersonId == actingPersonId && !string.IsNullOrEmpty(log.IpAddress) && Math.Abs(log.DateTimeUtc.Subtract(dateTime.ToUniversalTime()).TotalMinutes) < 140) { return(log.IpAddress); } } foreach (BasicPWLog log in logArr) { if (log.AffectedItemId == affectedPersonId && !string.IsNullOrEmpty(log.IpAddress) && Math.Abs(log.DateTimeUtc.Subtract(dateTime.ToUniversalTime()).TotalMinutes) < 122) { return(log.IpAddress); } } return(""); }
protected void Page_Load(object sender, EventArgs e) { bool success = false; string expectedHash1 = ""; string expectedHash2 = ""; Person person = null; string redirectUrl = string.Empty; int personId = 0; //New or old variant? MemberId indicates old variant with common date for all orgs. if (Int32.TryParse(Request.QueryString["MemberId"], out personId)) { // Ok, at least we have a valid person id. person = Person.FromIdentity(personId); DateTime currentExpiry = DateTime.MaxValue; DateTime newExpiry = DateTime.MinValue; Memberships memberships = person.GetRecentMemberships(Membership.GracePeriod); string[] mIds = ("" + Request.QueryString["MID"]).Split(','); bool membershipExists = false; Membership membershipToExtend = null; if (mIds.Length > 0) { memberships = new Memberships(); foreach (string mId in mIds) { try { Membership membership = Membership.FromIdentity(Convert.ToInt32(mId)); memberships.Add(membership); //find earliest expiry in expiring orgs if (membership.Expires < currentExpiry) { currentExpiry = membership.Expires; newExpiry = currentExpiry.AddYears(1); membershipExists = true; membershipToExtend = membership; } } catch (Exception) { } } } // Get the new expiry from org 1 Organization.PPSEid bool isPpMember = false; bool isUPMember = false; foreach (Membership membership in person.GetRecentMemberships(Membership.GracePeriod)) { if (membership.OrganizationId == Organization.PPSEid) { isPpMember = true; } else if (membership.Organization.IsOrInherits(Organization.UPSEid)) { isUPMember = true; } if (membership.Expires < currentExpiry && (membership.Organization.IsOrInherits(Organization.UPSEid) || membership.OrganizationId == Organization.PPSEid)) { currentExpiry = membership.Expires; newExpiry = currentExpiry.AddYears(1); membershipExists = true; membershipToExtend = membership; } } if (membershipExists) { // The default is to renew all existing memberships. However, a person can also // request a transfer or to leave one specific organization. // This is built into the security token. string token1 = person.Name.Replace(" ", "-") + person.PasswordHash + "-" + currentExpiry.Year.ToString(); string token2 = person.PasswordHash + "-" + currentExpiry.Year.ToString(); int leaveOrgId = 0; int transferOldOrgId = 0; int transferNewOrgId = 0; string leaveString = Request.QueryString["Leave"]; string transferString = Request.QueryString["Transfer"]; if (!string.IsNullOrEmpty(leaveString)) { leaveOrgId = Int32.Parse(leaveString); token1 += "-Leave" + leaveOrgId.ToString(); token2 += "-Leave" + leaveOrgId.ToString(); } if (!string.IsNullOrEmpty(transferString)) { string[] tokens = transferString.Split(','); transferOldOrgId = Int32.Parse(tokens[0]); transferNewOrgId = Int32.Parse(tokens[1]); token1 += "-Transfer" + transferOldOrgId.ToString() + "/" + transferNewOrgId.ToString(); token2 += "-Transfer" + transferOldOrgId.ToString() + "/" + transferNewOrgId.ToString(); } expectedHash1 = SHA1.Hash(token1).Replace(" ", "").Substring(0, 8); expectedHash2 = SHA1.Hash(token2).Replace(" ", "").Substring(0, 8); if (Request.QueryString["SecHash"] == expectedHash1 || Request.QueryString["SecHash"] == expectedHash2) { success = true; this.LabelExpires.Text = newExpiry.ToString("yyyy-MM-dd"); if (leaveOrgId > 0) { Membership membership = person.GetRecentMembership(Membership.GracePeriod, leaveOrgId); // Might have been terminated already if (membership != null && membership.Active) { //Terminate logs and creates appropriate events membership.Terminate(EventSource.SignupPage, person, "Membership in " + membership.Organization.NameShort + " was terminated while renewing."); } this.PanelLeft.Visible = true; this.LiteralLeftOrganizations.Text = "<b>" + Server.HtmlEncode( Organization.FromIdentity(leaveOrgId).Name) + "</b>"; } if (transferOldOrgId > 0) { Membership oldMembership = person.GetRecentMembership(Membership.GracePeriod, transferOldOrgId); // Might have been terminated already if (oldMembership != null) { Membership newMembership = Membership.Create(person.Identity, transferNewOrgId, oldMembership.Expires); //Terminate logs and creates appropriate events oldMembership.Terminate(EventSource.SignupPage, person, "Membership in " + oldMembership.Organization.NameShort + " was transferred to " + newMembership.Organization.NameShort + " while renewing."); } this.LabelTransferOldOrganization.Text = Organization.FromIdentity(transferOldOrgId).Name; this.LabelTransferNewOrganization.Text = Organization.FromIdentity(transferNewOrgId).Name; this.PanelTransferred.Visible = true; } Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.ReceivedMembershipPayment, person.Identity, membershipToExtend.OrganizationId, person.Geography.Identity, person.Identity, 0, Request.UserHostAddress); string orgList = string.Empty; foreach (Membership membership in person.GetRecentMemberships(Membership.GracePeriod)) { if (membership.OrganizationId != leaveOrgId) { if ((isPpMember && membership.OrganizationId == Organization.PPSEid) || (isUPMember && membership.Organization.IsOrInherits(Organization.UPSEid)) || (memberships.Contains(membership))) { PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MembershipRenewed, "Membership in " + membership.Organization.NameShort + " renewed.", "Membership was renewed from IP " + Request.UserHostAddress + "."); orgList += ", <b>" + Server.HtmlEncode(membership.Organization.Name) + "</b>"; } } } orgList = orgList.Substring(2); this.LiteralRenewedOrganizations.Text = orgList; } } else { // There were no existing memberships. Create new ones. This is the PPSE path, so create a new membership for just PPSE. // Verify security token. string tokenBase = person.Name.Replace(" ", "-") + person.PasswordHash + "-" + DateTime.Today.Year.ToString(); string expectedSecurityHash = SHA1.Hash(tokenBase).Replace(" ", "").Substring(0, 8); if (Request.QueryString["SecHash"] == expectedSecurityHash) { Membership.Create(person, Organization.PPSE, DateTime.Today.AddYears(1)); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.ReceivedMembershipPayment, person.Identity, Organization.PPSEid, person.Geography.Identity, person.Identity, 0, Request.UserHostAddress); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MembershipRenewed, "A renewed membership in " + Organization.PPSE.NameShort + " was signed up.", "Membership was created from IP " + Request.UserHostAddress + "."); success = true; } } } string errorType = ""; try { // This is the new path - we expect all renewals from Dec 14, 2010 and onward to follow this. Delete the old path (with "MemberId") some time February 2011. if (Int32.TryParse(Request.QueryString["PersonId"], out personId)) { // Ok, at least we have a valid person id. person = Person.FromIdentity(personId); string transferString = Request.QueryString["Transfer"]; Membership membership = null; DateTime newExpiry = DateTime.MinValue;; int transferOldOrgId = 0; int transferNewOrgId = 0; try { if (Request.QueryString["MembershipId"] != null) { membership = Membership.FromIdentity(Int32.Parse(Request.QueryString["MembershipId"])); newExpiry = membership.Expires; //do not mess with lifetime memberships (100 years) if (newExpiry < DateTime.Today.AddYears(10)) { newExpiry = newExpiry.AddYears(1); if (newExpiry > DateTime.Now.AddYears(1)) { newExpiry = DateTime.Now.AddYears(1).AddDays(1); } } if (membership.OrganizationId == Organization.PPSEid) { redirectUrl = "http://www.piratpartiet.se/fornyelse"; // HACK, have an org parameter for this later } if (membership.PersonId != personId) { throw new ArgumentException("Mismatching membership and person"); } } else if (Request.QueryString["Transfer"] != null) { if (!string.IsNullOrEmpty(transferString)) { string[] tokens = transferString.Split(','); transferOldOrgId = Int32.Parse(tokens[0]); } membership = person.GetRecentMembership(Membership.GracePeriod, transferOldOrgId); if (membership == null) { throw new ArgumentException("Can't find membership"); } //do not mess with lifetime memberships (100 years) if (membership.Expires < DateTime.Today.AddYears(10)) { if (membership.Expires > DateTime.Today.AddYears(1)) { newExpiry = membership.Expires; } else { newExpiry = DateTime.Today.AddYears(1); } } } else { throw new ArgumentException("No MembershipId given"); } } catch (Exception ex) { throw new Exception("No Membership found: " + ex.Message, ex); } if (!membership.Active) { if (membership.DateTerminated.AddDays(Membership.GracePeriod) < DateTime.Today) { throw new ArgumentException("Membership has expired beyond recovery"); } newExpiry = DateTime.Today.AddYears(1); if (membership.OrganizationId == Organization.PPSEid) { redirectUrl = "http://www.piratpartiet.se/fornyelse"; // HACK, have an org parameter for this later } } string tokenBase = person.PasswordHash + "-" + membership.Identity.ToString() + "-" + membership.Expires.Year.ToString(); if (!string.IsNullOrEmpty(transferString)) { string[] tokens = transferString.Split(','); transferOldOrgId = Int32.Parse(tokens[0]); transferNewOrgId = Int32.Parse(tokens[1]); tokenBase += "-Transfer" + transferOldOrgId.ToString() + "/" + transferNewOrgId.ToString(); } if (transferOldOrgId != 0 && transferOldOrgId != membership.OrganizationId) { throw new ArgumentException("Invalid Transfer Order"); } string expectedHash = SHA1.Hash(tokenBase).Replace(" ", "").Substring(0, 8); if (Request.QueryString["SecHash"] == expectedHash) { success = true; this.LabelExpires.Text = newExpiry.ToString("yyyy-MM-dd"); int orgMembershipToExtend = membership.OrganizationId; if (transferOldOrgId > 0) { Membership oldMembership = person.GetRecentMembership(Membership.GracePeriod, transferOldOrgId); Membership newMembership = membership; // Might have been terminated already if (oldMembership != null) { newMembership = Membership.Create(person.Identity, transferNewOrgId, oldMembership.Expires); //Terminate logs and creates appropriate events oldMembership.Terminate(EventSource.SignupPage, person, "Membership in " + oldMembership.Organization.NameShort + " was transferred to " + newMembership.Organization.NameShort + " while renewing."); membership = newMembership; } this.LabelTransferOldOrganization.Text = Organization.FromIdentity(transferOldOrgId).Name; this.LabelTransferNewOrganization.Text = Organization.FromIdentity(transferNewOrgId).Name; this.PanelTransferred.Visible = true; orgMembershipToExtend = transferNewOrgId; } Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.ReceivedMembershipPayment, person.Identity, orgMembershipToExtend, person.Geography.Identity, person.Identity, 0, Request.UserHostAddress); PWLog.Write(person.Identity, PWLogItem.Person, person.Identity, PWLogAction.MembershipRenewed, "Membership in " + membership.Organization.NameShort + " renewed.", "Membership was renewed from IP " + Request.UserHostAddress + "."); this.LiteralRenewedOrganizations.Text = Organization.FromIdentity(orgMembershipToExtend).Name; } } } catch (ArgumentException e2) { // Something failed parsing the parameters. Do not renew. errorType = e2.Message; } if (!success) { // Send a couple mails PWLog.Write(person.Identity, PWLogItem.Person, person.Identity, PWLogAction.Failure, "Tech failure on membership renewal: " + Request.RawUrl + " Errormessage:" + errorType, "Renewal attempt from from IP " + Request.UserHostAddress + "."); person.SendNotice("Vill du f\xF6rnya?", "Alldeles nyss f\xF6rs\xF6kte n\xE5gon, troligtvis du, f\xF6rnya ditt medlemskap i Piratpartiet " + "och/eller Ung Pirat. Det misslyckades p\xE5 grund av en felaktig s\xE4kerhetskod.\r\n\r\n" + "Det kan bero p\xE5 ett antal anledningar, men f\xF6r att vara s\xE4ker p\xE5 att det inte \xE4r " + "on\xF6" + "diga tekniska fel som hindrar dig fr\xE5n att forts\xE4tta vara medlem, s\xE5 kan vi ocks\xE5 f\xF6rnya " + "ditt medlemskap manuellt.\r\n\r\nAllt som kr\xE4vs \xE4r att du svarar JA p\xE5 det h\xE4r brevet och " + "skickar tillbaka det till Medlemsservice (avs\xE4ndaren).\r\n\r\n" + "Vill du f\xF6rnya ditt eller dina befintliga medlemskap i Piratpartiet och/eller Ung Pirat " + "f\xF6r ett \xE5r till?\r\n\r\n", Organization.PPSEid); Person.FromIdentity(1).SendNotice("Misslyckad f\xF6rnyelse", person.Name + " (#" + person.Identity.ToString() + ") f\xF6rs\xF6kte f\xF6rnya medlemskapet. Det misslyckades:" + errorType + "Ett mail har skickats ut.\r\n", Organization.PPSEid); } else { this.PanelSuccess.Visible = success; this.PanelFail.Visible = !success; if (!String.IsNullOrEmpty(redirectUrl)) { Response.Redirect(redirectUrl); } } }
private void CreateMember() { // If youthOrg is true, then the person opted for youth league membership. bool youthOrgSelected = this.RadioYouthLeague.Checked || this.RadioYouthLeagueOnly.Checked == true; PaymentCode paymentCode = null; /* * // Payments disabled * * if (!youthOrgSelected) * { * paymentCode = PaymentCode.FromCode(this.TextPaymentCode.Text); * }*/ string name = this.TextName.Text; string password = ViewState["pw"] as string; string email = this.TextEmail.Text.Replace(",", "."); // for some reason 1 in 500 mistypes this string phone = this.TextPhone.Text; string street = this.TextStreet.Text; string postal = this.TextPostal.Text; string city = this.TextCity.Text; string countryCode = this.DropCountries.SelectedValue; int birthDay = Convert.ToInt32(this.TextBirthDay.Text); int birthMonth = Convert.ToInt32(this.DropBirthMonths.SelectedValue); int birthYear = Convert.ToInt32(this.TextBirthYear.Text); DateTime birthdate = new DateTime(birthYear, birthMonth, birthDay); PersonGender gender = (PersonGender)Enum.Parse(typeof(PersonGender), this.DropGenders.SelectedValue); // This will stop the Create to be called twice even if doubleclick SessionMemberDuplicateStop = DateTime.Now;; // We are ready to create the new person. Person person = Person.Create(name, email, password, phone, street, postal, city, countryCode, birthdate, gender); // The creation resolves the appropriate geography, so we can determine the correct // organization to join the person to. // In some cases PostalCode does not indicate the geography uniquely if (DropDownKommun.SelectedIndex >= 0) { person.Geography = Geography.FromIdentity(int.Parse(DropDownKommun.SelectedValue)); } // Add memberships, as appropriate. Organization youthOrg = null; this.LabelMemberOfOrganizations.Text = string.Empty; if (youthOrgSelected) { try { youthOrg = Organizations.GetMostLocalOrganization(person.GeographyId, Organization.UPDKid); } catch (ArgumentException ex) { //didnt find any, Does the org itself accept members? youthOrg = Organization.FromIdentity(Organization.UPDKid); if (!youthOrg.AcceptsMembers) { throw ex; //rethrow } } Activizr.Logic.Pirates.Membership newMembership = person.AddMembership(youthOrg.Identity, DateTime.Now.AddYears(1)); newMembership.SetPaymentStatus(MembershipPaymentStatus.NewlyRegistered, DateTime.Now); this.LabelMemberOfOrganizations.Text = "<br><b>" + Server.HtmlEncode(youthOrg.Name) + "</b> og <br/>"; } if (!this.RadioYouthLeagueOnly.Checked) { person.AddMembership(Organization.PPDKid, DateTime.Now.AddYears(1)); this.LabelMemberOfOrganizations.Text += "<b>Piratpartiet</b>"; } // Create events. if (RadioYouthLeague.Checked) { Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, youthOrg.Identity, person.GeographyId, person.Identity, 0, youthOrg.Identity.ToString() + " " + Organization.PPDKid.ToString() + "," + Request.UserHostAddress + "," + this.LabelReferrer.Text); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "New member joined organization " + youthOrg.NameShort + " and Piratpartiet DK.", "The self-signup came from IP address " + Request.UserHostAddress + "."); } else if (RadioYouthLeagueOnly.Checked) { Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, youthOrg.Identity, person.GeographyId, person.Identity, 0, youthOrg.Identity.ToString() + "," + Request.UserHostAddress + "," + this.LabelReferrer.Text); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "New member joined organizations " + youthOrg.NameShort, "The self-signup came from IP address " + Request.UserHostAddress + "."); } else { Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, Organization.PPDKid, person.GeographyId, person.Identity, 0, Organization.PPDKid.ToString() + "," + Request.UserHostAddress + "," + this.LabelReferrer.Text); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "New member joined Piratpartiet DK.", "The self-signup came from IP address " + Request.UserHostAddress + "."); } // Claim the payment. if (paymentCode != null) { paymentCode.Claim(person); } // If activity level was not passive (activist or officer), then register as activist. if (!this.RadioActivityPassive.Checked) { person.CreateActivist(false, false); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.NewActivist, person.Identity, Organization.PPDKid, person.GeographyId, person.Identity, 0, string.Empty); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "Joined as activist.", string.Empty); } // If activity level was officer, register as officer volunteer. if (this.RadioActivityOfficer.Checked) { int[] chairman = Authorization.PersonsWithRoleInOrg(RoleType.OrganizationChairman, Organization.PPFIid, false); if (chairman.Length > 0) { Person defaultOwner = Person.FromIdentity(chairman[0]); Volunteer volunteer = Volunteer.Create(person, defaultOwner); // RF owns new volunteers //Autoassign will try to assign to ElectoralCircuit lead or //if not possible, to its parent org lead, or if not possible to defaultOwner //TODO:Ugly hack sweden hardcoded (30) volunteer.AutoAssign(person.Geography, Organization.PPDKid, defaultOwner, Geography.SwedenId); volunteer.AddRole(Organization.PPDKid, person.GeographyId, RoleType.LocalLead); volunteer.AddRole(Organization.PPDKid, person.GeographyId, RoleType.LocalDeputy); volunteer.AddRole(Organization.PPDKid, person.GeographyId, RoleType.LocalAdmin); string textParameter = person.Name.Replace("|", "") + "|" + person.Phone.Replace("|", "") + "|Yes|KL1 KL2 KLA"; Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.NewVolunteer, 0, Organization.PPDKid, person.GeographyId, 0, 0, textParameter); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "Volunteered for local officership.", string.Empty); } } }
protected void Wizard_NextButtonClick(object sender, WizardNavigationEventArgs e) { // Validate data for the various steps, or (on page 4) finalize the membership. // ------------------------------------- // VALIDATE PAGE: CHOICE OF ORGANIZATION // ------------------------------------- if (e.CurrentStepIndex == 0) { // Validate the choice of organization. if (this.RadioParty.Checked == false && this.RadioYouthLeague.Checked == false) { /* * this.LabelOrganizationError.Text = "Du måste välja en organisation!"; * e.Cancel = true;*/ } else { this.LabelOrganizationError.Text = string.Empty; // Clear on success } // If youth league is selected, make sure that the payment page is skipped. if (this.RadioYouthLeague.Checked == true) { this.LabelSmsMessageText.Text = "PP UNG"; this.LabelOrganization.Text = "Ung Pirat (och Piratpartiet)"; Wizard.ActiveStepIndex = 2; // Remove this on 2007 expiry // Set the focus to the name control on the member details page. this.TextName.Focus(); } else if (this.RadioParty.Checked == true) { this.LabelSmsMessageText.Text = "PP MEDLEM"; this.LabelOrganization.Text = "Piratpartiet"; Wizard.ActiveStepIndex = 2; // Zero cost payment // Set the focus to the payment code control. this.TextPaymentCode.Focus(); } } // --------------------------- // VALIDATE PAGE: PAYMENT CODE // --------------------------- if (e.CurrentStepIndex == 1) { // Validate the payment code page. PaymentCode code = null; try { code = PaymentCode.FromCode(this.TextPaymentCode.Text.Trim()); } catch (Exception) { // If we can't get the payment code, it will remain null, which is fine. } if (code == null || code.Claimed) { this.LabelPaymentError.Text = "Hittar inte kvittokoden!"; e.Cancel = true; } else { this.LabelPaymentError.Text = string.Empty; // Clear on success if (code.IssuedToPhoneNumber.Length > 0) { this.TextPhone.Text = code.IssuedToPhoneNumber; } } // Set the focus to the name control on the member details page. this.TextName.Focus(); } // ----------------------------- // VALIDATE PAGE: MEMBER DETAILS // ----------------------------- if (e.CurrentStepIndex == 2) { // Validate member details. This is going to be quite a long validation. // Start by clearing all the error labels, for readability later. this.LabelNameError.Text = string.Empty; this.LabelStreetError.Text = string.Empty; this.LabelPostalError.Text = string.Empty; this.LabelPhoneError.Text = string.Empty; this.LabelEmailError.Text = string.Empty; this.LabelBirthdateError.Text = string.Empty; this.LabelGenderError.Text = string.Empty; // Check for errors. // Name if (this.TextName.Text.Length < 3 || !this.TextName.Text.Contains(" ")) { this.LabelNameError.Text = "Skriv ditt namn"; e.Cancel = true; } // Street if (this.TextStreet.Text.Length < 4) { this.LabelStreetError.Text = "Skriv gatuadress"; e.Cancel = true; } // Postal code & city -- also validate postal code length for given country if (this.TextPostal.Text.Length < 4) { this.LabelPostalError.Text = "Skriv postnummer"; e.Cancel = true; } else { Country country = Country.FromCode(DropCountries.SelectedValue); if (country.PostalCodeLength != 0) { string postalCode = this.TextPostal.Text; postalCode = postalCode.Replace(" ", ""); if (postalCode.Length != country.PostalCodeLength) { this.LabelPostalError.Text = "Felaktigt postnr"; e.Cancel = true; } } } if (this.TextCity.Text.Length < 3 && this.LabelPostalError.Text.Length < 2) { this.LabelPostalError.Text = "Skriv postort"; e.Cancel = true; } // Phone number if (this.TextPhone.Text.Length < 7) { this.LabelPhoneError.Text = "Skriv telefonnummer"; e.Cancel = true; } // Email /*AddressValidationResult addressValidationResult = * PirateWeb.Logic.Special.Mail.AddressValidator.Validate (this.TextEmail.Text);*/ if (this.TextEmail.Text.Length < 5) { this.LabelEmailError.Text = "Skriv email"; e.Cancel = true; } /* * else switch (addressValidationResult) * { * case AddressValidationResult.Unknown: * case AddressValidationResult.Valid: * // Address ok * break; * case AddressValidationResult.BadSyntax: * this.LabelEmailError.Text = "Ogiltig emailadress"; * e.Cancel = true; * break; * case AddressValidationResult.ServerInvalid: * this.LabelEmailError.Text = "Mailservern finns inte"; * e.Cancel = true; * break; * case AddressValidationResult.AccountInvalid: * this.LabelEmailError.Text = "Mailkontot finns inte"; * e.Cancel = true; * break; * default: * throw new NotImplementedException ("Not implemented AddressValidationResult: " + addressValidationResult); * }*/ // Birthdate try { int day = Convert.ToInt32(this.TextBirthDay.Text); int year = Convert.ToInt32(this.TextBirthYear.Text); int month = Convert.ToInt32(this.DropBirthMonths.SelectedValue); DateTime test = new DateTime(year, month, day); if (test > DateTime.Now) { throw new Exception("No, you can't be born on a future date."); } if (test < DateTime.Now.AddYears(-125)) { throw new Exception("And you're not over 125 years old, either."); } } catch (Exception) { this.LabelBirthdateError.Text = "Välj födelsedatum"; e.Cancel = true; } // Gender try { PersonGender gender = (PersonGender)Enum.Parse(typeof(PersonGender), this.DropGenders.SelectedValue); if (gender == PersonGender.Unknown) { throw new Exception(); // Gender not selected - just throw something to produce the error message. } } catch (Exception) { this.LabelGenderError.Text = "Välj kön"; e.Cancel = true; } if (!e.Cancel) { this.TextPassword1.Focus(); } } // --------------------------------- // VALIDATE PAGE: PIRATEWEB PASSWORD // --------------------------------- if (e.CurrentStepIndex == 3) { string password1 = this.TextPassword1.Text; string password2 = this.TextPassword2.Text; if (password1 != password2) { this.LabelPasswordError.Text = "Skriv samma lösen i båda rutorna!"; e.Cancel = true; } else if (password1 == string.Empty) { this.LabelPasswordError.Text = "Välj ett lösenord"; e.Cancel = true; } else if (password1.Length < 5) { this.LabelPasswordError.Text = "Lösenordet är för kort"; e.Cancel = true; } if (e.Cancel == true) { this.TextPassword1.Focus(); // Set focus to first (now empty) text box } if (e.Cancel == false) { // This is the final page. When we get here, all data is good. This code // creates and commits the member. // If youthOrg is true, then the person opted for youth league membership. bool youthOrgSelected = this.RadioYouthLeague.Checked; PaymentCode paymentCode = null; /* * // Payments disabled * * if (!youthOrgSelected) * { * paymentCode = PaymentCode.FromCode(this.TextPaymentCode.Text); * }*/ string name = this.TextName.Text; string password = this.TextPassword1.Text; string email = this.TextEmail.Text; string phone = this.TextPhone.Text; string street = this.TextStreet.Text; string postal = this.TextPostal.Text; string city = this.TextCity.Text; string countryCode = this.DropCountries.SelectedValue; int birthDay = Convert.ToInt32(this.TextBirthDay.Text); int birthMonth = Convert.ToInt32(this.DropBirthMonths.SelectedValue); int birthYear = Convert.ToInt32(this.TextBirthYear.Text); DateTime birthdate = new DateTime(birthYear, birthMonth, birthDay); PersonGender gender = (PersonGender)Enum.Parse(typeof(PersonGender), this.DropGenders.SelectedValue); // We are ready to create the new person. Person person = Person.Create(name, email, password, phone, street, postal, city, countryCode, birthdate, gender); // The creation resolves the appropriate geography, so we can determine the correct // organization to join the person to. // Add memberships, as appropriate. Organization youthOrg = null; this.LabelMemberOfOrganizations.Text = string.Empty; if (youthOrgSelected) { youthOrg = Organizations.GetMostLocalOrganization(person.GeographyId, Organization.UPSEid); person.AddMembership(youthOrg.Identity, DateTime.Now.AddYears(1)); this.LabelMemberOfOrganizations.Text = "<b>" + Server.HtmlEncode(youthOrg.Name) + "</b> och<br/>"; } //TODO: hardcoded norway person.AddMembership(Organization.PPNOid, DateTime.Now.AddYears(1)); this.LabelMemberOfOrganizations.Text += "<b>Piratpartiet NO</b>"; // Create events. if (youthOrgSelected) { Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, youthOrg.Identity, person.GeographyId, person.Identity, 0, youthOrg.Identity.ToString() + " " + Organization.PPNOid.ToString() + "," + Request.UserHostAddress + "," + this.LabelReferrer.Text); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "New member joined organizations " + youthOrg.NameShort + " and Piratpartiet SE.", "The self-signup came from IP address " + Request.UserHostAddress + "."); } else { Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, Organization.PPNOid, person.GeographyId, person.Identity, 0, Organization.PPNOid.ToString() + "," + Request.UserHostAddress + "," + this.LabelReferrer.Text); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "New member joined Piratpartiet NO.", "The self-signup came from IP address " + Request.UserHostAddress + "."); } // Claim the payment. if (paymentCode != null) { paymentCode.Claim(person); } } } }
private void CompleteSignup() { string name = this.TextFirstName.Text + "|" + this.TextLastName.Text; string password = ViewState["pwpass"] as string; string email = this.TextEmail.Text.Replace(",", "."); // for some reason 1 in 500 mistypes this, even with repeats string phone = this.TextPhone.Text; string street = this.TextStreet.Text; string postal = this.TextPostalCode.Text; string city = this.TextCity.Text; string countryCode = this.DropCountries.SelectedValue; int birthDay = Convert.ToInt32(this.DropBirthDay.SelectedValue); int birthMonth = Convert.ToInt32(this.DropBirthMonth.SelectedValue); int birthYear = Convert.ToInt32(this.DropBirthYear.SelectedValue); DateTime birthdate = new DateTime(birthYear, birthMonth, birthDay); PersonGender gender = (PersonGender)Enum.Parse(typeof(PersonGender), this.DropGenders.SelectedValue); // We are ready to create the new person. Person person = Person.Create(name, email, password, phone, street, postal, city, countryCode, birthdate, gender); // The creation resolves the appropriate geography, so we can determine the correct // organization to join the person to. // In some cases PostalCode does not indicate the geography uniquely if (DropGeographies.SelectedIndex >= 0) { person.Geography = Geography.FromIdentity(int.Parse(DropGeographies.SelectedValue)); } else { person.Geography = Country.FromCode(countryCode).Geography; } person.AddMembership(Organization.PPSEid, DateTime.Now.AddYears(1)); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, Organization.PPSEid, person.GeographyId, person.Identity, 0, Organization.PPSEid.ToString() + "," + Request.UserHostAddress + "," + ViewState["Referrer"] as string); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "New member joined Piratpartiet SE.", "The self-signup came from IP address " + Request.UserHostAddress + "."); // If activity level was not passive (activist or officer), then register as activist. if (!this.RadioActivityPassive.Checked) { person.CreateActivist(false, false); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.NewActivist, person.Identity, Organization.PPSEid, person.GeographyId, person.Identity, 0, string.Empty); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "Joined as activist.", string.Empty); } // If activity level was officer, register as officer volunteer. if (this.RadioActivityOfficer.Checked) { Person defaultOwner = Person.FromIdentity(1); Volunteer volunteer = Volunteer.Create(person, defaultOwner); // RF owns new volunteers //Autoassign will try to assign to ElectoralCircuit lead or //if not possible, to its parent org lead, or if not possible to defaultOwner //TODO:Ugly hack sweden hardcoded (30) volunteer.AutoAssign(person.Geography, Organization.PPSEid, defaultOwner, Geography.SwedenId); volunteer.AddRole(Organization.PPSEid, person.GeographyId, RoleType.LocalLead); volunteer.AddRole(Organization.PPSEid, person.GeographyId, RoleType.LocalDeputy); volunteer.AddRole(Organization.PPSEid, person.GeographyId, RoleType.LocalAdmin); // TODO: Add more specifics about how the volunteer would like to work. string textParameter = person.Name.Replace("|", "") + "|" + person.Phone.Replace("|", "") + "|Yes|KL1 KL2 KLA"; Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.NewVolunteer, 0, Organization.PPSEid, person.GeographyId, 0, 0, textParameter); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "Volunteered for local officership.", string.Empty); } // If Ung Pirat was checked, process. if (this.CheckUngPirat.Checked) { Organization youthOrg = Organizations.GetMostLocalOrganization(person.GeographyId, Organization.UPSEid); person.AddMembership(youthOrg.Identity, DateTime.Now.AddYears(1)); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, youthOrg.Identity, person.GeographyId, person.Identity, 0, youthOrg.Identity.ToString() + " " + Organization.PPSEid.ToString() + "," + Request.UserHostAddress + "," + ViewState["Referrer"] as string); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "New member joined organization " + youthOrg.NameShort + ".", "The self-signup came from IP address " + Request.UserHostAddress + "."); } }
protected void Button1_Click(object sender, EventArgs e) { int col_firstNames = 0; int col_lastName = 1; int col_dateOfBirth = 2; int col_email = 3; int col_municipality = 4; int col_address = 5; int col_postalCode = 6; int col_city = 7; int col_phone = 8; int col_dateJoined = 9; int col_active = 10; int currentRow = -1; int currentImported = 0; DateTime T0 = DateTime.Now; Dictionary <string, BasicCity> postcodes = PirateDb.GetDatabase().GetCitiesPerPostalCode(loadCntry.Identity); Dictionary <string, BasicCity> cityPerName = new Dictionary <string, BasicCity>(); Dictionary <int, BasicCity> cityPerId = new Dictionary <int, BasicCity>(); foreach (BasicCity bc in postcodes.Values) { cityPerName[bc.Name.ToLower().Replace(" ", "")] = bc; cityPerId[bc.Identity] = bc; } People allpeople = People.GetAll(); Dictionary <string, Person> peoplePerKey = new Dictionary <string, Person>(); foreach (Person p in allpeople) { peoplePerKey[p.Email.ToLower().Replace(" ", "") + p.Birthdate.ToString("yyMMdd")] = p; } Memberships memberships = Memberships.ForOrganization(currentOrg); Dictionary <int, Membership> membershipsDict = new Dictionary <int, Membership>(); foreach (Membership ms in memberships) { membershipsDict[ms.PersonId] = ms; } string[] rows = TextBoxImport.Text.Replace("\r\n", "\n").Split('\n'); using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 30, 0))) { foreach (string row in rows) { ++currentRow; string[] cols = (row + "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t").Split('\t'); Geography mainGeo = null; string name = cols[col_firstNames] + " " + cols[col_lastName]; if (!Formatting.ValidateEmailFormat(cols[col_email])) { AddError(currentRow, "Bad email format:" + cols[col_email]); continue; } BasicCity foundCity = null; Dictionary <int, Geography> geos = new Dictionary <int, Geography>(); string pcode = cols[col_postalCode].Trim(); if (pcode != "") { while (pcode.Length < loadCntry.PostalCodeLength) { pcode = "0" + pcode; } if (!postcodes.ContainsKey(pcode)) { AddError(currentRow, "Invalid postal code:" + pcode); } else { foundCity = postcodes[pcode]; mainGeo = Geography.FromIdentity(foundCity.GeographyId); geos[foundCity.GeographyId] = mainGeo; } } else if (cols[col_city].Trim() != "") { if (!cityPerName.ContainsKey(cols[col_city].ToLower().Replace(" ", ""))) { AddError(currentRow, "Invalid postal code:" + pcode); } else { foundCity = cityPerName[cols[col_city].ToLower().Replace(" ", "")]; mainGeo = Geography.FromIdentity(foundCity.GeographyId); geos[foundCity.GeographyId] = mainGeo; } } foreach (Geography g in geotree) { string[] names = g.Name.ToLower().Replace(" ", "").Split('/'); foreach (string partName in names) { if (partName == cols[col_municipality].ToLower().Replace(" ", "")) { mainGeo = g; geos[g.Identity] = g; } } } if (geos.Count == 0 || geos.Count > 1) { AddError(currentRow, "Warning only: can not find a specific local geography"); } DateTime dob = NormalizeDate(cols[col_dateOfBirth]); DateTime doj = NormalizeDate(cols[col_dateJoined]); string key = cols[col_email].ToLower().Replace(" ", "") + dob.ToString("yyMMdd"); Person currentPerson = null; if (!peoplePerKey.ContainsKey(key)) { if (mainGeo == null) { mainGeo = loadCntry.Geography; } currentPerson = Person.Create(name, cols[col_email], "ABCABCABCABC", cols[col_phone], cols[col_address], pcode, cols[col_city], loadCntry.Code, dob, PersonGender.Unknown); currentPerson.Geography = mainGeo; PWLog.Write(PWLogItem.Person, currentPerson.Identity, PWLogAction.PersonCreated, "Created Person from Import", "Import for " + currentOrg.Name); } else { currentPerson = peoplePerKey[key]; AddError(currentRow, "Warning only: Person with email already existed "); if (currentPerson.Birthdate < new DateTime(1901, 1, 1)) { currentPerson.Birthdate = dob; } if (currentPerson.Phone.Length < cols[col_phone].Length) { currentPerson.Phone = cols[col_phone]; } if (currentPerson.Street.Length < cols[col_address].Length) { currentPerson.Street = cols[col_address]; } if (currentPerson.PostalCode.CompareTo(pcode) < 0) { currentPerson.PostalCode = pcode; } if (currentPerson.CityName.Length < cols[col_city].Length) { currentPerson.CityName = cols[col_city]; } if (mainGeo != null && mainGeo.Identity != currentPerson.GeographyId) { currentPerson.Geography = mainGeo; } } // add membership if (!membershipsDict.ContainsKey(currentPerson.Identity)) { Membership newMs = Membership.Import(currentPerson, currentOrg, doj, nowValue.AddYears(100)); newMs.SetPaymentStatus(MembershipPaymentStatus.PaymentRecieved, nowValue); } // add activist if (cols[col_active] == "1") { currentPerson.CreateActivist(true, true); PWLog.Write(currentPerson, PWLogItem.Person, currentPerson.Identity, PWLogAction.ActivistJoin, "New activist joined.", "Import for " + currentOrg.Name); } ++currentImported; } txScope.Complete(); } StringBuilder sb = new StringBuilder(); sb.AppendLine("ProcessTime= " + Math.Round(DateTime.Now.Subtract(T0).TotalSeconds)); sb.AppendLine("Rows read= " + currentRow); sb.AppendLine("Rows imported= " + currentImported); sb.AppendLine("Errors and warnings"); foreach (int row in errRows.Keys) { sb.AppendLine("Line: " + row); sb.AppendLine(rows[row]); foreach (string err in errRows[row]) { sb.AppendLine(" " + err); } sb.AppendLine(""); } TextBoxResult.Text = sb.ToString(); }
//public void Terminate () //{ // Terminate(EventSource.Unknown); //} public void Terminate(EventSource eventSource, Person actingPerson, string description) { if (base.Active) { //Added removal of Roles here to make SURE they always are removed with the membership. Authority authority = Person.GetAuthority(); int actingPersonId = actingPerson == null ? 0 : actingPerson.Identity; BasicPersonRole[] roles = authority.AllPersonRoles; List <PersonRole> theRoles = new List <PersonRole>(); foreach (BasicPersonRole basicRole in roles) { PersonRole personRole = PersonRole.FromBasic(basicRole); theRoles.Add(personRole); if (personRole.OrganizationId == OrganizationId) { PWEvents.CreateEvent(eventSource, EventType.DeletedRole, actingPersonId, personRole.OrganizationId, personRole.GeographyId, Person.Identity, (int)personRole.Type, string.Empty); PWLog.Write(actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.RoleDeleted, "Role " + personRole.Type + " of " + personRole.Geography.Name + " was deleted with membership.", string.Empty); personRole.Delete(); } } //now check if this means that you no longer are a member of some uplevel org, then remove those roles as well foreach (PersonRole personRole in theRoles) { if (!Person.MemberOfWithInherited(personRole.Organization)) { PWEvents.CreateEvent(eventSource, EventType.DeletedRole, actingPersonId, personRole.OrganizationId, personRole.GeographyId, Person.Identity, (int)personRole.Type, string.Empty); PWLog.Write(actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.RoleDeleted, "Role " + personRole.Type + " of " + personRole.Geography.Name + " was deleted with membership of all suborgs.", string.Empty); personRole.Delete(); } } EventSource src = EventSource.PirateWeb; try { if (HttpContext.Current == null) { src = EventSource.PirateBot; } } catch { src = EventSource.PirateBot; } PWLog.Write(actingPersonId, PWLogItem.Person, Person.Identity, PWLogAction.MemberLost, eventSource + ":" + description, string.Empty); PWEvents.CreateEvent(src, EventType.LostMember, actingPersonId, OrganizationId, Person.GeographyId, Person.Identity, 0, OrganizationId.ToString()); //Added LogChurn here to make SURE they always are logged with the membership. if (PersonId > 0 && OrganizationId > 0 && base.Expires != new DateTime(1900, 1, 1)) { ChurnData.LogChurn(PersonId, OrganizationId); } SwarmDb.GetDatabaseForWriting().TerminateMembership(Identity); base.Active = false; base.DateTerminated = DateTime.Now; // Remove all newsletter subscriptions once the membership is terminated (to make sure default is now off and only turn off explicitly turned-on subscriptions) // HACK HACK HACK: uses feed IDs in an extremely ugly way to loop 1-9. Should use NewsletterFeeds.ForOrganization() once support for newsletters in different orgs are established. for (int newsletterFeedId = 1; newsletterFeedId < 10; newsletterFeedId++) { try { if (this.person.IsSubscribing(newsletterFeedId)) { this.person.SetSubscription(newsletterFeedId, false); } } catch (Exception) { // ignore nonexisting newsletter feeds -- this is a hack anyway } } } }
protected void ButtonPerformActions_Click(object sender, EventArgs e) { // Iterate through the grid, find the datakey and the selected action, and perform them. foreach (GridDataItem item in this.GridInbox.Items) { DropDownList listActions = (DropDownList)item.FindControl("DropActions"); if (listActions == null) { continue; } int caseId = (int)item.GetDataKeyValue("CaseId"); SupportCase openCase = SupportDatabase.GetCase(caseId); string phone = ExtractPhoneFromTitle(openCase.Title); People people = GetPeopleFromPhone(phone); bool closeCase = true; foreach (Person person in people) { string selectedValue = listActions.SelectedValue; switch (selectedValue) { case "TerminateAll": // terminate everything: all activistships, all memberships if (person.IsActivist) { person.TerminateActivist(); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.ActivistLost, "Activist Lost", "SMS message from phone# " + phone + " declined all further contact"); } Memberships terminateMemberships = person.GetMemberships(); foreach (Membership membership in terminateMemberships) { membership.Terminate(EventSource.SMS, _currentUser, "Membership in " + membership.Organization.Name + " terminated after person declined further contact over SMS."); } break; case "RenewAll": Memberships renewedMemberships = person.GetRecentMemberships(Membership.GracePeriod); // Get PPSE new expiry date, use as master DateTime masterNewExpiry = DateTime.Today.AddYears(1); foreach (Membership membership in renewedMemberships) { if (membership.OrganizationId == Organization.PPSEid) { if (membership.Expires > DateTime.Now) { // Set to one year from today or one year from previous expiry, whichever is greater masterNewExpiry = membership.Expires.AddYears(1); } } } foreach (Membership renewedMembership in renewedMemberships) { renewedMembership.Expires = masterNewExpiry; Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SMS, EventType.ReceivedMembershipPayment, person.Identity, renewedMembership.OrganizationId, person.Geography.Identity, person.Identity, 0, Request.UserHostAddress); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MembershipRenewed, "Membership in " + renewedMembership.Organization.NameShort + " renewed.", "Membership was renewed over SMS from phone# " + phone + " and will expire " + masterNewExpiry.ToString("yyyy-MM-dd") + "."); } // Renew all memberships. Easist done by logging an event of repayment break; default: closeCase = false; break; } if (closeCase) { openCase.CloseWithComment("Handled from PirateWeb interface, using option " + selectedValue + "."); } } } PopulateGrid(); this.GridInbox.Rebind(); }
public static void RemindExpiriesMail() { // Get expiring Console.WriteLine("Inside RemindExpiriesMail()"); Organizations orgs = Organizations.GetAll(); Dictionary <int, bool> personLookup = new Dictionary <int, bool>(); Dictionary <string, int> dateLookup = new Dictionary <string, int>(); DateTime lowerBound = DateTime.Today; DateTime upperBound = lowerBound.AddDays(31); List <string> failedReminders = new List <string>(); int weekDayInteger = (int)DateTime.Today.DayOfWeek; foreach (Organization org in orgs) { Memberships memberships = Memberships.GetExpiring(org, lowerBound, upperBound); foreach (Membership membership in memberships) { if (membership.OrganizationId % 7 != weekDayInteger) { continue; } try { Console.Write("Reminding " + membership.Person.Canonical + " about " + membership.Organization.Name + "."); SendReminderMail(membership); Console.Write("."); PWLog.Write(PWLogItem.Person, membership.PersonId, PWLogAction.MembershipRenewReminder, "Mail was sent to " + membership.Person.Mail + " reminding to renew membership in " + membership.Organization.Name + ".", string.Empty); Console.Write("."); string dateString = membership.Expires.ToString("yyyy-MM-dd"); if (!dateLookup.ContainsKey(dateString)) { dateLookup[dateString] = 0; } dateLookup[dateString]++; Console.WriteLine(" done."); } catch (Exception x) { string logText = "FAILED sending mail to " + membership.Person.Mail + " for reminder of pending renewal in " + membership.Organization.Name + "."; failedReminders.Add(membership.Person.Canonical); PWLog.Write(PWLogItem.Person, membership.PersonId, PWLogAction.MembershipRenewReminder, logText, string.Empty); ExceptionMail.Send(new Exception(logText, x)); } } } string notifyBody = String.Format("Sending renewal reminders to {0} people:\r\n\r\n", personLookup.Count); Console.WriteLine("Sending renewal reminders to {0} people", personLookup.Count); List <string> dateSummary = new List <string>(); int total = 0; foreach (string dateString in dateLookup.Keys) { dateSummary.Add(string.Format("{0}: {1,5}", dateString, dateLookup[dateString])); total += dateLookup[dateString]; } dateSummary.Sort(); foreach (string dateString in dateSummary) { notifyBody += dateString + "\r\n"; Console.WriteLine(dateString); } notifyBody += string.Format("Total sent: {0,5}\r\n\r\n", total); Console.WriteLine("Total sent: {0,5}\r\n\r\n", total); notifyBody += "FAILED reminders:\r\n"; Console.WriteLine("FAILED reminders:"); foreach (string failed in failedReminders) { notifyBody += failed + "\r\n"; Console.WriteLine(failed); } if (failedReminders.Count == 0) { notifyBody += "none.\r\n"; Console.WriteLine("none."); } /* no. just no. we should do a global search for "FromIdentity(1)" * Person.FromIdentity(1).SendOfficerNotice("Reminders sent today", notifyBody, 1); */ }
protected void ButtonSaveChanges_Click(object sender, EventArgs e) { LabelSaveError.Text = "Not Allowed."; if (_authority.HasPermission(Permission.CanEditMailDB, Organization.PPSEid, -1, Authorization.Flag.AnyGeographyExactOrganization)) { LabelSaveError.Text = "Saved."; string suggestedAccount = (TextBoxAccount.Text.Trim() + "@" + DropDownMailDomain.SelectedValue).ToLower(); if (state == "add") { if (CheckAvailability() == "") { if (!Formatting.ValidateEmailFormat(suggestedAccount)) { suggestedAccount = (TextBoxAccount.Text.Trim()).ToLower(); } try { //MailServerDatabase.AddAccount(suggestedAccount, TextBoxPassword.Text, 1024); PWLog.Write(_currentUser, PWLogItem.MailAccount, 0, PWLogAction.MailAccountChanged, "Created account", "Manually changed in PW", suggestedAccount, "", ""); string forwardAccount = TextBoxForward.Text.Trim().ToLower(); if (forwardAccount != "") { MailServerDatabase.StartForwarding(suggestedAccount, forwardAccount); PWLog.Write(_currentUser, PWLogItem.MailAccount, 0, PWLogAction.MailAccountChanged, "Changed forwarding", "Manually changed in PW", account, "", forwardAccount); } ScriptManager.RegisterStartupScript(this, this.GetType(), "saved", "CloseAndRebind();", true); } catch (Exception ex) { LabelSaveError.Text = ex.Message; } } else { LabelSaveError.Text = "Account is NOT available"; } } else { try { List <MailServerDatabase.MailAccount> objAccList = MailServerDatabase.SearchAccount(account); string wasForwarded = objAccList.Count > 0 ? "" + (objAccList[0].forwardedTo.Count > 0 ? objAccList[0].forwardedTo[0] : "") : ""; if (TextBoxPassword.Text != "") { MailServerDatabase.SetNewPassword(account, TextBoxPassword.Text); PWLog.Write(_currentUser, PWLogItem.MailAccount, 0, PWLogAction.MailAccountChanged, "Changed password", "Manually changed in PW", account, "", ""); } string forwardAccount = TextBoxForward.Text.Trim().ToLower(); if (forwardAccount == "" && wasForwarded != "") { MailServerDatabase.StopForwarding(account); PWLog.Write(_currentUser, PWLogItem.MailAccount, 0, PWLogAction.MailAccountChanged, "Stopped forwarding", "Manually changed in PW", account, forwardAccount, ""); } else if (forwardAccount != wasForwarded) { MailServerDatabase.StartForwarding(account, forwardAccount); PWLog.Write(_currentUser, PWLogItem.MailAccount, 0, PWLogAction.MailAccountChanged, "Changed forwarding", "Manually changed in PW", account, wasForwarded, forwardAccount); } ScriptManager.RegisterStartupScript(this, this.GetType(), "saved", "CloseAndRebind();", true); } catch (Exception ex) { LabelSaveError.Text = ex.Message; } } } }
protected void Page_Load(object sender, EventArgs e) { bool success = false; string expectedHash1 = ""; string membershipsIds = "" + Request.QueryString["MID"]; int personId = 0; if (Int32.TryParse(Request.QueryString["MemberId"], out personId)) { // Ok, at least we have a valid person id. Person person = Person.FromIdentity(personId); DateTime currentExpiry = DateTime.MinValue; DateTime newExpiry = DateTime.MinValue; Memberships memberships = person.GetRecentMemberships(Membership.GracePeriod); { // The default is to renew all existing memberships. However, a person can also // request a transfer or to leave one specific organization. // This is built into the security token. string token1 = person.PasswordHash + "-" + membershipsIds; expectedHash1 = SHA1.Hash(token1).Replace(" ", "").Substring(0, 8); if (Request.QueryString["SecHash"] == expectedHash1) { success = true; foreach (Membership membership in memberships) { if (membership != null && membership.Active && (membership.OrganizationId == Organization.PPSEid || membership.Organization.Inherits(Organization.PPSEid))) { membership.Terminate(EventSource.SignupPage, person, "Membership in " + membership.Organization.NameShort + " was terminated while renewing."); } } } } if (!success) { // Send a couple mails PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.Failure, "Members failed to terminate:" + Request.RawUrl, ""); person.SendNotice("Vill du f\xF6rnya?", "Alldeles nyss f\xF6rs\xF6kte n\xE5gon, troligtvis du, f\xF6rnya ditt medlemskap i Piratpartiet " + "och/eller Ung Pirat. Det misslyckades p\xE5 grund av en felaktig s\xE4kerhetskod.\r\n\r\n" + "Det kan bero p\xE5 ett antal anledningar, men f\xF6r att vara s\xE4ker p\xE5 att det inte \xE4r " + "on\xF6" + "diga tekniska fel som hindrar dig fr\xE5n att forts\xE4tta vara medlem, s\xE5 kan vi ocks\xE5 f\xF6rnya " + "ditt medlemskap manuellt.\r\n\r\nAllt som kr\xE4vs \xE4r att du svarar JA p\xE5 det h\xE4r brevet och " + "skickar tillbaka det till Medlemsservice (avs\xE4ndaren).\r\n\r\n" + "Vill du f\xF6rnya ditt eller dina befintliga medlemskap i Piratpartiet och/eller Ung Pirat " + "f\xF6r ett \xE5r till?\r\n\r\n", Organization.PPSEid); Person.FromIdentity(1).SendNotice("Misslyckad f\xF6rnyelse", person.Name + " (#" + person.Identity.ToString() + ") f\xF6rs\xF6kte f\xF6rnya medlemskapet. Det misslyckades. " + "Ett mail har skickats ut.\r\n", Organization.PPSEid); } else { Response.Redirect("http://www.piratpartiet.se/fornyelse"); } this.PanelSuccess.Visible = success; this.PanelFail.Visible = !success; } }
public static void SendReminderMail(Person person, Memberships memberships) { // First, determine the organization template to use. Prioritize a long ancestry. // This is a hack for the Swedish structure. ReminderMail remindermail = new ReminderMail(); int longestAncestry = 0; // "ancestry" as a length means distance to organization tree root int shortestAncestry = 999; Organization topOrg = null; Organization lowOrg = null; DateTime currentExpiry = DateTime.MinValue; foreach (Membership membership in memberships) { if (membership.Organization.AutoAssignNewMembers) { Organizations ancestry = membership.Organization.GetLine(); if (ancestry.Count > longestAncestry) { longestAncestry = ancestry.Count; lowOrg = membership.Organization; remindermail.pOrgName = lowOrg.MailPrefixInherited; } if (ancestry.Count < shortestAncestry) { shortestAncestry = ancestry.Count; topOrg = membership.Organization; } } if (membership.OrganizationId == Organization.PPSEid) { topOrg = membership.Organization; remindermail.pOrgName = membership.Organization.MailPrefixInherited; currentExpiry = membership.Expires; } } DateTime newExpiry = currentExpiry; if (newExpiry < DateTime.Today.AddYears(10)) { //do not mess with lifetime memberships newExpiry = newExpiry.AddYears(1); if (newExpiry > DateTime.Today.AddYears(1)) { newExpiry = DateTime.Today.AddYears(1).AddDays(1); } } //Person sender = Person.FromIdentity(1); //Rick remindermail.pExpirationDate = currentExpiry; remindermail.pNextDate = newExpiry; remindermail.pPreamble = "<p> Vi är glada att du vill <strong>förnya ditt medlemskap</strong> i Piratpartiet och/eller Ung Pirat.<br /><br />Använd en av länkarna nedan så genomförs förnyelsen.<br />"; string tokenBase = person.PasswordHash + "-" + currentExpiry.Year.ToString(); Organization expectedLowOrg = Organizations.GetMostLocalOrganization(person.GeographyId, Organization.UPSEid); int ageThisYear = DateTime.Now.Year - person.Birthdate.Year; //Hardcoded: age = 26 if (ageThisYear >= 26 && lowOrg.Inherits(Organization.UPSEid)) { // If this person is older than 26, suggest that they leave UP. remindermail.pCurrentAge = ageThisYear.ToString(); remindermail.pCurrentOrg = lowOrg.Name; remindermail.pOtherOrg = topOrg.Name; string link = "https://pirateweb.net/Pages/Public/SE/People/MemberRenew.aspx?MemberId=" + person.Identity.ToString() + "&Leave=" + lowOrg.Identity.ToString() + "&SecHash=" + SHA1.Hash(tokenBase + "-Leave" + lowOrg.Identity.ToString()). Replace(" ", "").Substring(0, 8); remindermail.pOtherRenewLink = link; remindermail.pWrongOrgSpan = " "; //clear the other span } else if (lowOrg.Inherits(Organization.UPSEid) && lowOrg.Identity != expectedLowOrg.Identity) { // Is this person in the wrong locale? remindermail.pCurrentOrg = lowOrg.Name; remindermail.pOtherOrg = expectedLowOrg.Name; remindermail.pGeographyName = person.Geography.Name; //mailBody += "Du är medlem i " + lowOrg.Name + ", men när du bor i [b]" + person.Geography.Name + // "[/b] så rekommenderar " + // "vi att du byter till din lokala organisation, [b]" + expectedLowOrg.Name + // "[/b]. Klicka här för att göra det:\r\n\r\n"; string link = "https://pirateweb.net/Pages/Public/SE/People/MemberRenew.aspx?MemberId=" + person.Identity.ToString() + "&Transfer=" + lowOrg.Identity.ToString() + "," + expectedLowOrg.Identity.ToString() + "&SecHash=" + SHA1.Hash(tokenBase + "-Transfer" + lowOrg.Identity.ToString() + "/" + expectedLowOrg.Identity.ToString()).Replace(" ", "").Substring(0, 8); remindermail.pOtherRenewLink = link; remindermail.pTooOldForYouthOrgSpan = " "; //clear the other span //mailBody += "[a href=\"" + link + "\"]" + link + "[/a]\r\n\r\n" + // "Det är naturligtvis inget krav, utan du kan fortsätta precis som förut om du vill. " + // "För att fortsätta i dina befintliga föreningar, klicka här:\r\n\r\n"; } else { remindermail.pTooOldForYouthOrgSpan = " "; //clear the other span remindermail.pWrongOrgSpan = " "; //clear the other span } string stdLink = "https://pirateweb.net/Pages/Public/SE/People/MemberRenew.aspx?MemberId=" + person.Identity.ToString() + "&SecHash=" + SHA1.Hash(tokenBase).Replace(" ", "").Substring(0, 8); remindermail.pStdRenewLink = stdLink; OutboundMail mail = remindermail.CreateFunctionalOutboundMail(MailAuthorType.MemberService, OutboundMail.PriorityNormal, topOrg, Geography.Root); if (mail.Body.Trim() == "") { throw new Exception("Failed to create a mailBody"); } else { mail.AddRecipient(person.Identity, false); mail.SetRecipientCount(1); mail.SetResolved(); mail.SetReadyForPickup(); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MembershipRenewReminder, "Mail was sent to " + person.Email + " on request to renew membership.", string.Empty); } }
public static void RemindChangeOrg() { HeartBeater.Instance.Beat(); // Get expiring DateTime starttime = DateTime.Now; Organizations orgs = Organization.FromIdentity(Organization.UPSEid).GetTree(); Dictionary <int, Person> personLookup = new Dictionary <int, Person>(); Dictionary <int, Memberships> personMembershipsLookup = new Dictionary <int, Memberships>(); Dictionary <int, Organization> orgLookup = new Dictionary <int, Organization>(); Dictionary <int, Organization> mostLocalOrganizationCache = new Dictionary <int, Organization>(); List <ChangeOrgReport> report = new List <ChangeOrgReport>(); foreach (Organization org in orgs) { orgLookup[org.OrganizationId] = org; } Memberships allMemberships = Memberships.ForOrganizations(orgs); foreach (Membership ms in allMemberships) { //Handle defunct Memberships.ForOrganizations if (orgLookup.ContainsKey(ms.OrganizationId)) { if (!personLookup.ContainsKey(ms.PersonId)) { personLookup[ms.PersonId] = null; personMembershipsLookup[ms.PersonId] = new Memberships(); } personMembershipsLookup[ms.PersonId].Add(ms); } } allMemberships = null; People peeps = People.FromIdentities((new List <int>(personLookup.Keys)).ToArray()); foreach (Person p in peeps) { personLookup[p.PersonId] = p; } if (Debugger.IsAttached) { Console.WriteLine("Found " + personLookup.Count + " people"); } int processedCounter = 0; int sentCounter = 0; int failCounter = 0; DateTime lastDisplay = DateTime.Now; foreach (Person person in personLookup.Values) { ++processedCounter; if ((processedCounter % 50) == 0) { HeartBeater.Instance.Beat(); if (Debugger.IsAttached) { Console.WriteLine("Processed " + processedCounter + " t=" + DateTime.Now.Subtract(lastDisplay).TotalSeconds); } lastDisplay = DateTime.Now; } int geoid = person.GeographyId; //check for error, geography broken. if (person.GeographyId == 0) { geoid = person.Geography.GeographyId; //Will force resolve Geography if (geoid != 0) { person.Geography = person.Geography; } ; //repair person. } if (geoid == 0) { continue; //give up on that... } Organization expectedLowOrg = null; if (mostLocalOrganizationCache.ContainsKey(geoid)) { expectedLowOrg = mostLocalOrganizationCache[geoid]; } else { expectedLowOrg = Organizations.GetMostLocalOrganization(geoid, Organization.UPSEid); mostLocalOrganizationCache[geoid] = expectedLowOrg; } bool found = false; Dictionary <int, Membership> personMS = new Dictionary <int, Membership>(); foreach (Membership ms in personMembershipsLookup[person.PersonId]) { if (orgLookup.ContainsKey(ms.OrganizationId)) { //Its an UP org personMS[ms.OrganizationId] = ms; } if (ms.OrganizationId == expectedLowOrg.Identity) { found = true; break; } } if (found == false) { //OK we didnt find the recommended org. Find out why. // loop thru the persons up orgs to find an inactive List <Organization> foundInactiveOrg = new List <Organization>(); List <Organization> foundActiveOrg = new List <Organization>(); Membership membership = null; try { Organization org = null; foreach (Membership ms in personMS.Values) { org = orgLookup[ms.OrganizationId]; if (org.AcceptsMembers == false) { foundInactiveOrg.Add(org); } else if (org.AutoAssignNewMembers == true) { foundActiveOrg.Add(org); } } if (foundInactiveOrg.Count > 0) { //inactive membership = personMS[foundInactiveOrg[0].Identity]; } else if (foundActiveOrg.Count > 0) { //change membership = personMS[foundActiveOrg[0].Identity]; } else { //already a member but not of an autoassign org if (Debugger.IsAttached) { Console.WriteLine("Debug:nochange " + person.Name + ";" + person.Geography.Name + ";" + (org != null ? org.Name : "UnknownOrg") + ";" + expectedLowOrg.Name); } continue; } DateTime lastReminder = PWLog.CheckLatest(PWLogItem.Person, membership.PersonId, PWLogAction.MembershipRenewReminder); if (DateTime.Now.Subtract(lastReminder).TotalDays > 25) { if (Debugger.IsAttached) { Console.Write("Debug:" + person.Name + ";" + person.Geography.Name + ";" + membership.Organization.Name + ";" + expectedLowOrg.Name); foreach (var o in foundActiveOrg) { Console.Write(";" + o.Name); } Console.WriteLine(""); } SendChangeOrgMail(person, membership, expectedLowOrg); report.Add(new ChangeOrgReport { FromOrg = membership.Organization, ToOrg = expectedLowOrg }); ++sentCounter; PWLog.Write(PWLogItem.Person, membership.PersonId, PWLogAction.MembershipRenewReminder, "Mail was sent to " + membership.Person.Mail + " for recommendation of organisation change in " + membership.Organization.Name + ".", membership.Organization.Identity.ToString() + "/" + expectedLowOrg.Identity.ToString()); } } catch (Exception x) { ++failCounter; string logText = "FAILED sending mail to " + membership.Person.Mail + " for recommendation of organisation change in " + membership.Organization.Name + "."; PWLog.Write(PWLogItem.Person, membership.PersonId, PWLogAction.MembershipRenewReminder, logText, string.Empty); ExceptionMail.Send(new Exception(logText, x)); } } } Dictionary <Organization, Dictionary <Organization, int> > fromdict = new Dictionary <Organization, Dictionary <Organization, int> >(); StringBuilder fromOrgReport = new StringBuilder(); report.ForEach(delegate(ChangeOrgReport r) { if (!fromdict.ContainsKey(r.FromOrg)) { fromdict[r.FromOrg] = new Dictionary <Organization, int>(); } if (!fromdict[r.FromOrg].ContainsKey(r.ToOrg)) { fromdict[r.FromOrg][r.ToOrg] = 0; } fromdict[r.FromOrg][r.ToOrg]++; }); foreach (var fd in fromdict.Keys) { StringBuilder tmp = new StringBuilder(); int cnt = 0; foreach (var td in fromdict[fd].Keys) { tmp.Append(", " + td.Name); cnt += fromdict[fd][td]; } fromOrgReport.Append("\r\nFrån " + fd.Name + " (" + cnt + " st) till " + tmp.ToString().Substring(2)); } Dictionary <Organization, Dictionary <Organization, int> > todict = new Dictionary <Organization, Dictionary <Organization, int> >(); StringBuilder toOrgReport = new StringBuilder(); report.ForEach(delegate(ChangeOrgReport r) { if (!todict.ContainsKey(r.ToOrg)) { todict[r.ToOrg] = new Dictionary <Organization, int>(); } if (!todict[r.ToOrg].ContainsKey(r.FromOrg)) { todict[r.ToOrg][r.FromOrg] = 0; } todict[r.ToOrg][r.FromOrg]++; }); foreach (var td in todict.Keys) { StringBuilder tmp = new StringBuilder(); int cnt = 0; foreach (var fd in todict[td].Keys) { tmp.Append(", " + fd.Name); cnt += todict[td][fd]; } toOrgReport.Append("\r\nTill " + td.Name + " (" + cnt + " st) från " + tmp.ToString().Substring(2)); } string reportMessage = string.Format( "Result from running recommendation to change org mails:\r\n" + "Time: {0,10:#0.0} minutes. \r\n" + "Checked: {1,10:g}\r\n" + "Sent: {2,10:g}\r\n" + "Failed: {3,10:g}\r\n", DateTime.Now.Subtract(starttime).TotalMinutes, processedCounter, sentCounter, failCounter) + fromOrgReport + "\r\n" + toOrgReport; BasicPersonRole[] UPSecretary = SwarmDb.GetDatabaseForReading().GetPeopleWithRoleType(RoleType.OrganizationSecretary, new int[] { Organization.UPSEid }, new int[] { }); if (UPSecretary.Length > 0) { Person.FromIdentity(UPSecretary[0].PersonId).SendOfficerNotice("ChangeOrg Mails Job report", reportMessage, Organization.UPSEid); } Person.FromIdentity(7838).SendOfficerNotice("ChangeOrgMails run", reportMessage, Organization.UPSEid);//Debug }
protected void Wizard_NextButtonClick(object sender, WizardNavigationEventArgs e) { // Validate data for the various steps, or (on page 4) finalize the membership. // ------------------------------------- // VALIDATE PAGE: CHOICE OF ORGANIZATION // ------------------------------------- if (e.CurrentStepIndex == 0) { // Validate the choice of organization. if (this.RadioParty.Checked == false && this.RadioYouthLeague.Checked == false) { this.LabelOrganizationError.Text = "Du måste välja en organisation!"; e.Cancel = true; } else { this.LabelOrganizationError.Text = string.Empty; // Clear on success } // If youth league is selected, make sure that the payment page is skipped. if (this.RadioYouthLeague.Checked == true) { this.LabelSmsMessageText.Text = "PP UNG"; this.LabelOrganization.Text = "Ung Pirat (och Piratpartiet, som du blir medlem i samtidigt)"; Wizard.ActiveStepIndex = 2; // Remove this on 2007 expiry // Set the focus to the name control on the member details page. this.TextName.Focus(); } else if (this.RadioParty.Checked == true) { this.LabelSmsMessageText.Text = "PP MEDLEM"; this.LabelOrganization.Text = "Piratpartiet"; Wizard.ActiveStepIndex = 2; // Zero cost payment // Set the focus to the payment code control. this.TextPaymentCode.Focus(); } } // --------------------------- // VALIDATE PAGE: PAYMENT CODE // --------------------------- if (e.CurrentStepIndex == 1) { // Validate the payment code page. PaymentCode code = null; try { code = PaymentCode.FromCode(this.TextPaymentCode.Text.Trim()); } catch (Exception) { // If we can't get the payment code, it will remain null, which is fine. } if (code == null || code.Claimed) { this.LabelPaymentError.Text = "Hittar inte kvittokoden!"; e.Cancel = true; } else { this.LabelPaymentError.Text = string.Empty; // Clear on success if (code.IssuedToPhoneNumber.Length > 0) { this.TextPhone.Text = code.IssuedToPhoneNumber; } } // Set the focus to the name control on the member details page. this.TextName.Focus(); } // ----------------------------- // VALIDATE PAGE: MEMBER DETAILS // ----------------------------- if (e.CurrentStepIndex == 2) { // Validate member details. This is going to be quite a long validation. // Check for errors. // Name if (this.TextName.Text.Length < 3 || !this.TextName.Text.Contains(" ")) { this.LabelNameError.Visible = true; e.Cancel = true; } // Street if (this.TextStreet.Text.Length < 4) { this.LabelStreetError.Visible = true; e.Cancel = true; } // Postal code & city -- also validate postal code length for given country if (this.TextPostal.Text.Length < 4) { this.LabelPostalError.Text = "Skriv postnummer"; this.LabelPostalError.Visible = true; e.Cancel = true; } else { Country country = Country.FromCode(DropCountries.SelectedValue); if (country.PostalCodeLength != 0) { string postalCode = this.TextPostal.Text; postalCode = postalCode.Replace(" ", ""); if (postalCode.Length != country.PostalCodeLength) { this.LabelPostalError.Visible = true; e.Cancel = true; } } } if (this.TextCity.Text.Length < 3 && this.LabelPostalError.Text.Length < 2) { this.LabelCityError.Visible = true; e.Cancel = true; } // Phone number if (this.TextPhone.Text.Length < 7) { this.LabelPhoneError.Visible = true; e.Cancel = true; } // Email this.TextEmail.Text = this.TextEmail.Text.Trim(); if (this.TextEmail.Text.Length < 5) { this.LabelEmailError.Visible = true; e.Cancel = true; } else if (!Formatting.ValidateEmailFormat(this.TextEmail.Text)) { this.LabelEmailError.Visible = true; e.Cancel = true; } // Birthdate try { int day = Convert.ToInt32(this.TextBirthDay.Text); int year = Convert.ToInt32(this.TextBirthYear.Text); int month = Convert.ToInt32(this.DropBirthMonths.SelectedValue); DateTime test = new DateTime(year, month, day); if (test > DateTime.Now) { throw new Exception("No, you can't be born on a future date."); } if (test < DateTime.Now.AddYears(-125)) { throw new Exception("And you're not over 125 years old, either."); } } catch (Exception) { this.LabelBirthdateError.Visible = true; e.Cancel = true; } // Gender try { PersonGender gender = (PersonGender)Enum.Parse(typeof(PersonGender), this.DropGenders.SelectedValue); if (gender == PersonGender.Unknown) { throw new Exception(); // Gender not selected - just throw something to produce the error message. } } catch (Exception) { this.LabelGenderError.Text = "Välj kön"; e.Cancel = true; } if (!e.Cancel) { this.TextPassword1.Focus(); } } // --------------------------------- // VALIDATE PAGE: PIRATEWEB PASSWORD // --------------------------------- if (e.CurrentStepIndex == 3 && DateTime.Now.Subtract(SessionMemberDuplicateStop).TotalSeconds > 2) { string password1 = this.TextPassword1.Text; string password2 = this.TextPassword2.Text; if (password1 != password2) { this.LabelPasswordErrorSame.Visible = true; e.Cancel = true; } else if (password1 == string.Empty) { this.LabelPasswordError.Visible = true; e.Cancel = true; } else if (password1.Length < 5) { this.LabelPasswordErrorLength.Visible = true; e.Cancel = true; } if (e.Cancel == true) { this.TextPassword1.Focus(); // Set focus to first (now empty) text box } ViewState["pw"] = password1; } if (e.CurrentStepIndex == 4 && DateTime.Now.Subtract(SessionMemberDuplicateStop).TotalSeconds > 2) { // This is the final page. When we get here, all data is good. This code // creates and commits the member. // If youthOrg is true, then the person opted for youth league membership. bool youthOrgSelected = this.RadioYouthLeague.Checked; PaymentCode paymentCode = null; /* * // Payments disabled * * if (!youthOrgSelected) * { * paymentCode = PaymentCode.FromCode(this.TextPaymentCode.Text); * }*/ string name = this.TextName.Text; string password = ViewState["pw"] as string; string email = this.TextEmail.Text.Replace(",", "."); // for some reason 1 in 500 mistypes this string phone = this.TextPhone.Text; string street = this.TextStreet.Text; string postal = this.TextPostal.Text; string city = this.TextCity.Text; string countryCode = this.DropCountries.SelectedValue; int birthDay = Convert.ToInt32(this.TextBirthDay.Text); int birthMonth = Convert.ToInt32(this.DropBirthMonths.SelectedValue); int birthYear = Convert.ToInt32(this.TextBirthYear.Text); DateTime birthdate = new DateTime(birthYear, birthMonth, birthDay); PersonGender gender = (PersonGender)Enum.Parse(typeof(PersonGender), this.DropGenders.SelectedValue); // Tis will stop the Create to be called twice even if doubleclick SessionMemberDuplicateStop = DateTime.Now; // We are ready to create the new person. Person person = Person.Create(name, email, password, phone, street, postal, city, countryCode, birthdate, gender); // The creation resolves the appropriate geography, so we can determine the correct // organization to join the person to. // In some cases PostalCode does not indicate the geography uniquely if (DropDownKommun.SelectedIndex >= 0) { person.Geography = Geography.FromIdentity(int.Parse(DropDownKommun.SelectedValue)); } // Add memberships, as appropriate. Organization youthOrg = null; this.LabelMemberOfOrganizations.Text = string.Empty; if (youthOrgSelected) { youthOrg = Organizations.GetMostLocalOrganization(person.GeographyId, Organization.UPSEid); person.AddMembership(youthOrg.Identity, DateTime.Now.AddYears(1)); this.LabelMemberOfOrganizations.Text = "<b>" + Server.HtmlEncode(youthOrg.Name) + "</b> och<br/>"; } person.AddMembership(Organization.PPSEid, DateTime.Now.AddYears(1)); this.LabelMemberOfOrganizations.Text += "<b>Piratpartiet</b>"; // Create events. if (youthOrgSelected) { Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, youthOrg.Identity, person.GeographyId, person.Identity, 0, youthOrg.Identity.ToString() + " " + Organization.PPSEid.ToString() + "," + Request.UserHostAddress + "," + this.LabelReferrer.Text); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "New member joined organizations " + youthOrg.NameShort + " and Piratpartiet SE.", "The self-signup came from IP address " + Request.UserHostAddress + "."); } else { Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, Organization.PPSEid, person.GeographyId, person.Identity, 0, Organization.PPSEid.ToString() + "," + Request.UserHostAddress + "," + this.LabelReferrer.Text); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "New member joined Piratpartiet SE.", "The self-signup came from IP address " + Request.UserHostAddress + "."); } // Claim the payment. if (paymentCode != null) { paymentCode.Claim(person); } // If activity level was not passive (activist or officer), then register as activist. if (!this.RadioActivityPassive.Checked) { person.CreateActivist(false, false); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.NewActivist, person.Identity, Organization.PPSEid, person.GeographyId, person.Identity, 0, string.Empty); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "Joined as activist.", string.Empty); } // If activity level was officer, register as officer volunteer. if (this.RadioActivityOfficer.Checked) { Person defaultOwner = Person.FromIdentity(1); Volunteer volunteer = Volunteer.Create(person, defaultOwner); // RF owns new volunteers //Autoassign will try to assign to ElectoralCircuit lead or //if not possible, to its parent org lead, or if not possible to defaultOwner //TODO:Ugly hack sweden hardcoded (30) volunteer.AutoAssign(person.Geography, Organization.PPSEid, defaultOwner, Geography.SwedenId); volunteer.AddRole(Organization.PPSEid, person.GeographyId, RoleType.LocalLead); volunteer.AddRole(Organization.PPSEid, person.GeographyId, RoleType.LocalDeputy); volunteer.AddRole(Organization.PPSEid, person.GeographyId, RoleType.LocalAdmin); string textParameter = person.Name.Replace("|", "") + "|" + person.Phone.Replace("|", "") + "|Yes|KL1 KL2 KLA"; Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.NewVolunteer, 0, Organization.PPSEid, person.GeographyId, 0, 0, textParameter); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "Volunteered for local officership.", string.Empty); } Wizard.ActiveStepIndex = 6; } if (e.CurrentStepIndex == 5) { Wizard.ActiveStepIndex = 0; } }
protected void ButtonAdd_Click(object sender, EventArgs e) { Person viewingPerson = Person.FromIdentity(Int32.Parse(HttpContext.Current.User.Identity.Name)); DateTime birthDate = DateTime.MinValue; string name = this.TextName.Text.Trim(); string email = this.TextEmail.Text.Trim(); string phone = this.TextPhone.Text.Trim(); string street = this.TextStreet.Text.Trim(); string postalCode = this.TextPostalCode.Text.Replace(" ", "").Trim(); string city = this.TextCity.Text.Trim(); string countryCode = this.DropCountries.SelectedValue; string personalNumber = this.TextPersonalNumber.Text.Trim(); string bankName = this.TextBank.Text.Trim(); string bankAccount = this.TextBankAccount.Text.Trim(); PersonGender gender = (PersonGender)Enum.Parse(typeof(PersonGender), this.DropGender.SelectedValue); Organization organization = Organization.FromIdentity(Convert.ToInt32(DropOrganizations.SelectedValue)); // Validate data bool dataGood = true; // Birthdate string[] formats = new string[] { "yyMMdd", "yyyyMMdd", "yy-MM-dd", "yyyy-MM-dd", "yyyy-MMM-dd" }; if (!DateTime.TryParseExact(this.TextBirthDate.Text.Trim(), formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate)) { this.LabelBirthDateMessage.Text = "Invalid - write like 1972-Jan-21"; this.LabelBirthDateMessage.CssClass = "ErrorMessage"; dataGood = false; } else { this.LabelBirthDateMessage.Text = string.Empty; this.LabelBirthDateMessage.CssClass = "EditComment"; } // Gender if (gender == PersonGender.Unknown) { dataGood = false; this.LabelGenderMessage.Text = "Select Gender!"; this.LabelGenderMessage.CssClass = "ErrorMessage"; } else { this.LabelGenderMessage.Text = string.Empty; } // Name if (name.Length < 0) { dataGood = false; this.LabelNameMessage.Text = "Must write name!"; this.LabelNameMessage.CssClass = "ErrorMessage"; } else if (!name.Contains(" ")) { dataGood = false; this.LabelNameMessage.Text = "Need full name!"; this.LabelNameMessage.CssClass = "ErrorMessage"; } else { this.LabelNameMessage.Text = string.Empty; } // Street address if (street.Length < 4) { dataGood = false; this.LabelStreetMessage.Text = "Need street address!"; this.LabelStreetMessage.CssClass = "ErrorMessage"; } else { this.LabelStreetMessage.Text = string.Empty; } // Postal code, city int supposedPostalCodeLength = Country.FromCode(this.DropCountries.SelectedValue).PostalCodeLength; if (supposedPostalCodeLength != 0 && supposedPostalCodeLength != postalCode.Length) { dataGood = false; this.LabelPostalMessage.Text = "Bad postal code!"; this.LabelPostalMessage.CssClass = "ErrorMessage"; } else if (city.Length < 2) { dataGood = false; this.LabelPostalMessage.Text = "Need city!"; this.LabelPostalMessage.CssClass = "ErrorMessage"; } else { this.LabelPostalMessage.Text = string.Empty; } // Phone if (phone.Length < 6) { dataGood = false; this.LabelPhoneMessage.Text = "Need phone number!"; this.LabelPhoneMessage.CssClass = "ErrorMessage"; } else { this.LabelPhoneMessage.Text = string.Empty; } // Email /* -- this validator has been decommissioned * * AddressValidationResult validationResult = AddressValidator.Validate (email); * * if (validationResult != AddressValidationResult.Valid && validationResult != AddressValidationResult.Unknown && validationResult != AddressValidationResult.AccountInvalid) * { * dataGood = false; * this.LabelEmailMessage.CssClass = "ErrorMessage"; * * switch (validationResult) * { * case AddressValidationResult.ServerInvalid: * this.LabelEmailMessage.Text = "Invalid email: Bad domain/host"; * break; * case AddressValidationResult.AccountInvalid: // Won't come here no more - branch disabled in conditional above * this.LabelEmailMessage.Text = "Invalid email: No such mailbox"; * break; * case AddressValidationResult.BadSyntax: * this.LabelEmailMessage.Text = "Invalid email: Syntax error"; * break; * } * } * else * { * this.LabelEmailMessage.Text = string.Empty; * } * */ // TODO: Check the rest of the data fields if (!dataGood) { Page.ClientScript.RegisterStartupScript(typeof(Page), "SuccessMessage", string.Empty, true); } else { string randomPassword = Activizr.Logic.Security.Authentication.CreateRandomPassword(8); // Create the person Person person = Person.Create(name, email, randomPassword, phone, street, postalCode, city, countryCode, birthDate, gender); // Add optional data if (personalNumber.Length > 0) { person.PersonalNumber = personalNumber; } if (bankAccount.Length > 0) { person.BankName = bankName; person.BankAccount = bankAccount; } // Create the membership DateTime expiry = DateTime.Now.AddYears(1).Date; person.AddMembership(organization, expiry); // Create memberships in master organizations Organizations masterOrgs = organization.GetMasterOrganizations(); foreach (Organization masterOrg in masterOrgs) { person.AddMembership(masterOrg, expiry); } // Send message about randomized password // TODO: Localize string mailBody = "A PirateWeb administrator has manually added you to the organization \"" + organization.Name + "\". " + "You are now a member of this organization. In order to access your member profile, you will need to log " + "on to the PirateWeb site at pirateweb.net with your name or email address, together with the following randomized password:\r\n\r\n" + "Password: "******"\r\n\r\n" + "You will be able to change this password once you have logged onto PirateWeb.\r\n\r\n" + "For more information, please contact the organization you just joined. Most welcome to the worldwide pirate movement.\r\n\r\n"; person.SendNotice("Your PirateWeb password", mailBody, organization.OrganizationId); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.PirateWeb, EventType.AddedMember, Convert.ToInt32(HttpContext.Current.User.Identity.Name), organization.Identity, person.GeographyId, person.Identity, 0, string.Empty); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "Added manually to " + organization.NameShort, "The member was added manually by " + viewingPerson.Name + " (#" + viewingPerson.Identity.ToString() + ")"); string masterOrgString = string.Empty; foreach (Organization masterOrg in masterOrgs) { /* * -- comment out the extra event when somebody is added to UP * * PirateWeb.Logic.Support.PWEvents.CreateEvent (EventSource.PirateWeb, EventType.AddedMembership, * Convert.ToInt32(HttpContext.Current.User.Identity.Name), * masterOrg.Identity, person.GeographyId, person.Identity, 0, string.Empty);*/ masterOrgString += ", " + masterOrg.Name; } if (masterOrgString.Length > 0) { masterOrgString = " and [" + masterOrgString.Substring(2) + "]"; } Page.ClientScript.RegisterStartupScript(typeof(Page), "SuccessMessage", "alert ('The member [" + HttpUtility.HtmlEncode(person.Name.Replace("'", "''")) + "] was added to [" + HttpUtility.HtmlEncode(organization.Name.Replace("'", "''")) + "]" + masterOrgString.Replace("'", "''") + ".');", true); // Clear the text boxen, reset the drop fields this.TextName.Text = string.Empty; this.TextEmail.Text = string.Empty; this.TextPhone.Text = string.Empty; this.TextPostalCode.Text = string.Empty; this.TextStreet.Text = string.Empty; this.TextCity.Text = string.Empty; this.TextBirthDate.Text = string.Empty; this.TextPersonalNumber.Text = string.Empty; this.TextBank.Text = string.Empty; this.TextBankAccount.Text = string.Empty; this.DropGender.SelectedIndex = 0; this.TextName.Focus(); // Reset to default country Organization selectedOrg = Organization.FromIdentity(Convert.ToInt32(this.DropOrganizations.SelectedValue)); this.DropCountries.SelectedItem.Selected = false; this.DropCountries.Items.FindByValue(selectedOrg.DefaultCountry.Code).Selected = true; } }
protected void ButtonOK_Click(object sender, EventArgs e) { TextBoxJabberID.Text = TextBoxJabberID.Text.Trim(); string jid = "" + TextBoxJabberID.Text + "@piratechat.net"; Regex reValidate = new Regex(@"^([^""&/:<>@\\]|\w|[!#$%'\)\(\*\+,-.\}\{])+$", RegexOptions.Singleline); if (TextBoxJabberID.Text.Length < 1 || !reValidate.IsMatch(TextBoxJabberID.Text.Trim())) { LabelChars.Visible = true; return; } ExternalIdentity extID = null; try { extID = ExternalIdentity.FromUserIdAndType(jid, ExternalIdentityType.PPXMPPAccount); } catch { } if (extID != null) { if (extID.AttachedToPersonID != _currentUser.Identity) { LabelOccupied.Visible = true; return; } } Password1.Text = Password1.Text.Trim(); Password2.Text = Password2.Text.Trim(); if (Password1.Text != Password2.Text) { LabelMatch.Visible = true; return; } if (_currentUser.ValidatePassword(Password1.Text)) { LabelBadPw.Visible = true; return; } try { extID = ExternalIdentity.FromPersonIdAndType(_currentUser.Identity, ExternalIdentityType.PPXMPPAccount); } catch { } if (extID == null) { extID = ExternalIdentity.CreateExternalIdentity("xmpp.piratpartiet.se", jid, Password1.Text, _currentUser.Identity, ExternalIdentityType.PPXMPPAccount); LabelError.Text = " Identity created."; PWLog.Write(_currentUser, PWLogItem.ExtAccount, extID.Identity, PWLogAction.ExtAccountChanged, "Created XMPPAccount", "", "", "", jid); } else { PWLog.Write(_currentUser, PWLogItem.ExtAccount, extID.Identity, PWLogAction.ExtAccountChanged, "Updated XMPPAccount", "", "UserID", extID.UserID, jid); extID.SetExternalIdentity("xmpp.piratpartiet.se", jid, Password1.Text, _currentUser.Identity, ExternalIdentityType.PPXMPPAccount); LabelError.Text = " Identity updated."; } }
protected void Button1_Click(object sender, EventArgs e) { if (!Formatting.ValidateEmailFormat(TextBoxMail.Text)) { LabelReply.Text = "Fel format på e-Mail adress"; LabelReply.Font.Bold = true; LabelReply.ForeColor = Color.Red; LabelReply.Font.Size = FontUnit.Medium; return; } if (CheckBoxRenew.Checked == false) { LabelReply.Text = "Kryssa för att du vill vara medlem!"; LabelReply.Font.Bold = true; LabelReply.ForeColor = Color.Red; LabelReply.Font.Size = FontUnit.Medium; return; } if (TextBoxName.Text.Trim() == "") { LabelReply.Text = "Ange namn!"; LabelReply.Font.Bold = true; LabelReply.ForeColor = Color.Red; LabelReply.Font.Size = FontUnit.Medium; return; } People members = People.FromEmail(TextBoxMail.Text); Person person = null; DateTime newExpiry = DateTime.MinValue; bool sentMail = true; try { Memberships membershipsToRenew = new Memberships(); string foundMemberIds = ""; try { DateTime currentExpiry = DateTime.MinValue; if (members.Count > 0) { person = members[0]; DateTime latest = DateTime.MinValue; Memberships personMS = person.GetRecentMemberships(Membership.GracePeriod); if (personMS != null && personMS.Count > 0) { membershipsToRenew = personMS; latest = personMS[0].Expires; } foreach (Person p in members) { foundMemberIds += "," + p.Identity; personMS = p.GetRecentMemberships(Membership.GracePeriod); if (personMS != null && personMS.Count > 0 && personMS[0].Expires > latest) { membershipsToRenew = personMS; person = p; latest = personMS[0].Expires; } } } } finally { PWLog.Write(PWLogItem.None, 0, PWLogAction.MembershipRenewalRequest, "MembershipRenewalRequest recieved |" + TextBoxMail.Text + "|" + TextBoxName.Text, "Found " + members.Count + "Persons" + foundMemberIds); } if (membershipsToRenew.Count > 0) { //Don't need to extend these, it will be handled in the renewalpage //newExpiry = DateTime.Today.AddDays(6); //6 days to avoid renewal mail (just in case) //foreach (Membership ms in membershipsToRenew) //{ // if (ms.Expires < DateTime.Now) // { // PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MembershipRenewed, "Membership in " + ms.Organization.NameShort + " extended temporarily on delayed renewal", "Membership was renewed from IP " + Request.UserHostAddress + "."); // ms.Expires = newExpiry; // } //} SendReminderMail(person, membershipsToRenew); } else { //No memberships sentMail = SendMail( FunctionalMail.Address[MailAuthorType.MemberService].Name, FunctionalMail.Address[MailAuthorType.MemberService].Email, TextBoxName.Text, TextBoxMail.Text, "Vill du förnya?", @" Alldeles nyss försökte någon (troligtvis du) förnya ditt medlemskap i Piratpartiet och/eller Ung Pirat. Tyvärr kunde vi inte hitta din mailadress i vårt medlemsregister, så antingen var det fel adress, eller så har vi redan hunnit rensa bort dina medlemsuppgifter. Om du misstänker att det kan ha varit fel mailadress, att den adress vi har registrerad är en annan, pröva gärna med en annan på https://pirateweb.net/Pages/Public/SE/RequestRenewal.aspx Annars, om det har gått en tid sedan ditt medlemskap löpte ut, registrera dig på nytt på http://blipirat.nu/ Du är välkommen, du behövs! mvh Piratpartiet"); } } catch { sentMail = false; } if (sentMail) { Panel1.Visible = false; LabelReply.Text = "Vi har skickat ett mail med en förnyelselänk.<br><br>Kolla din mailbox."; } else { LabelReply.Text = "PROGRAMFEL: Lyckades inte skicka mail. Kontakta [email protected] istället och be att de hjälper dig att förnya ditt medlemskap."; } }
private void CreateMember() { bool youthOrgSelected = this.cbYouthOnly.Checked; bool partyOrgSelected = this.cbParty.Checked; bool localOrgSelected = this.cbPartyAndLocal.Checked && partyOrgSelected; int partyOrgID = Organization.PPFIid; int youthOrgID = Organization.UPFIid;//Not yet defined PaymentCode paymentCode = null; /* * // Payments disabled * * if (!youthOrgSelected) * { * paymentCode = PaymentCode.FromCode(this.TextPaymentCode.Text); * }*/ string name = this.TextName.Text; string password = ViewState["pw"] as string; string email = this.TextEmail.Text.Replace(",", "."); // for some reason 1 in 500 mistypes this string phone = this.TextPhone.Text; string street = this.TextStreet.Text; string postal = this.TextPostal.Text; string city = this.TextCity.Text; string countryCode = this.DropCountries.SelectedValue; int birthDay = Convert.ToInt32(this.TextBirthDay.Text); int birthMonth = Convert.ToInt32(this.DropBirthMonths.SelectedValue); int birthYear = Convert.ToInt32(this.TextBirthYear.Text); DateTime birthdate = new DateTime(birthYear, birthMonth, birthDay); PersonGender gender = (PersonGender)Enum.Parse(typeof(PersonGender), this.DropGenders.SelectedValue); // This will stop the Create to be called twice even if doubleclick SessionMemberDuplicateStop = DateTime.Now;; // We are ready to create the new person. People people = People.FromEmail(email); // already in db? Person person = null; foreach (Person p in people) { if (p.Birthdate == birthdate) { person = p; } } if (person != null) { person.TempPasswordHash = person.PasswordHash;//save it, but dont trash the existing one Authentication.RequestMembershipConfirmation(person, "https://pirateweb.net/Pages/Public/FI/People/ConfirmMembership.aspx?member={0}&ticket={1}"); } else { person = Person.Create(name, email, Formatting.GeneratePassword(9), phone, street, postal, city, countryCode, birthdate, gender); person.SetPassword(password); //set the given password person.TempPasswordHash = person.PasswordHash; //save it. person.SetPassword(Formatting.GeneratePassword(9)); //Generate a random one. Authentication.RequestMembershipConfirmation(person, "https://pirateweb.net/Pages/Public/FI/People/ConfirmMembership.aspx?member={0}&ticket={1}"); } // The creation resolves the appropriate geography, so we can determine the correct // organization to join the person to. // In some cases PostalCode does not indicate the geography uniquely if (DropDownKommun.SelectedIndex >= 0) { person.Geography = Geography.FromIdentity(int.Parse(DropDownKommun.SelectedValue)); } if (person.GeographyId == 0) { person.Geography = Geography.FromIdentity(Geography.FinlandId); } // Add memberships, as appropriate. Organization youthOrg = null; Organization localPartyOrg = null; Organization partyOrg = null; this.LabelMemberOfOrganizations.Text = string.Empty; if (youthOrgSelected) { try { youthOrg = Organizations.GetMostLocalOrganization(person.GeographyId, youthOrgID); } catch (ArgumentException ex) { //didnt find any, Does the org itself accept members? youthOrg = Organization.FromIdentity(youthOrgID); if (!youthOrg.AcceptsMembers) { throw ex; //rethrow } } this.LabelMemberOfOrganizations.Text += "<br><b>" + Server.HtmlEncode(youthOrg.Name) + "</b>, <br/>"; if (!person.MemberOf(youthOrg.Identity)) { Activizr.Logic.Pirates.Membership newMembership = person.AddMembership(youthOrg.Identity, DateTime.Now.AddYears(100)); newMembership.SetPaymentStatus(MembershipPaymentStatus.NewlyRegistered, DateTime.Now); } else { youthOrg = null; } } bool wasPartyMember = false; if (localOrgSelected) { try { // localPartyOrg = Organizations.GetMostLocalOrganization(person.GeographyId, partyOrgID); localPartyOrg = Organization.FromIdentity(Convert.ToInt32(DropDownListSubOrg.SelectedValue)); this.LabelMemberOfOrganizations.Text += "<br><b>" + Server.HtmlEncode(localPartyOrg.Name) + "</b>, <br/>"; if (!person.MemberOf(localPartyOrg.Identity)) { Activizr.Logic.Pirates.Membership newMembership = person.AddMembership(localPartyOrg.Identity, DateTime.Now.AddYears(100)); newMembership.SetPaymentStatus(MembershipPaymentStatus.NewlyRegistered, DateTime.Now); } else { localPartyOrg = null; } } catch { //Asked for local org but didnt give enoght data } } if (partyOrgSelected && (wasPartyMember == false)) { if (!person.MemberOf(partyOrgID)) { Activizr.Logic.Pirates.Membership newMembership = person.AddMembership(partyOrgID, DateTime.Now.AddYears(100)); newMembership.SetPaymentStatus(MembershipPaymentStatus.NewlyRegistered, DateTime.Now); partyOrg = Organization.FromIdentity(partyOrgID); this.LabelMemberOfOrganizations.Text += "<br><b>" + Server.HtmlEncode(partyOrg.Name) + "</b>, <br/>"; } else { partyOrg = Organization.FromIdentity(partyOrgID); this.LabelMemberOfOrganizations.Text += "<br><b>" + Server.HtmlEncode(partyOrg.Name) + "</b>, <br/>"; partyOrg = null; } } // Create events. if (localPartyOrg != null || youthOrg != null || partyOrg != null) { if (localPartyOrg != null) { Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, localPartyOrg.Identity, person.GeographyId, person.Identity, 0, localPartyOrg.Identity.ToString() + "," + Request.UserHostAddress + "," + this.LabelReferrer.Text); } if (youthOrg != null) { Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, youthOrg.Identity, person.GeographyId, person.Identity, 0, youthOrg.Identity.ToString() + "," + Request.UserHostAddress + "," + this.LabelReferrer.Text); } if (partyOrg != null) { Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.AddedMember, person.Identity, partyOrg.Identity, person.GeographyId, person.Identity, 0, partyOrg.Identity.ToString() + "," + Request.UserHostAddress + "," + this.LabelReferrer.Text); } PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "New member joined organization " + (youthOrg != null ? youthOrg.NameShort + " " : "") + (localPartyOrg != null ? localPartyOrg.NameShort + " " : "") + (partyOrg != null ? partyOrg.NameShort : ""), "The self-signup came from IP address " + Request.UserHostAddress + "."); } // Claim the payment. if (paymentCode != null) { paymentCode.Claim(person); } // If activity level was not passive (activist or officer), then register as activist. if (!this.RadioActivityPassive.Checked) { person.CreateActivist(false, false); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.NewActivist, person.Identity, partyOrgID, person.GeographyId, person.Identity, 0, string.Empty); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "Joined as activist.", string.Empty); } // If activity level was officer, register as officer volunteer. if (this.RadioActivityOfficer.Checked) { int[] chairman = Authorization.PersonsWithRoleInOrg(RoleType.OrganizationChairman, Organization.PPFIid, false); if (chairman.Length > 0) { Person defaultOwner = Person.FromIdentity(chairman[0]); Volunteer volunteer = Volunteer.Create(person, defaultOwner); // RF owns new volunteers //Autoassign will try to assign to ElectoralCircuit lead or //if not possible, to its parent org lead, or if not possible to defaultOwner volunteer.AutoAssign(person.Geography, Organization.PPFIid, defaultOwner, Geography.FinlandId); volunteer.AddRole(Organization.PPFIid, person.GeographyId, RoleType.LocalLead); volunteer.AddRole(Organization.PPFIid, person.GeographyId, RoleType.LocalDeputy); volunteer.AddRole(Organization.PPFIid, person.GeographyId, RoleType.LocalAdmin); string textParameter = person.Name.Replace("|", "") + "|" + person.Phone.Replace("|", "") + "|Yes|KL1 KL2 KLA"; Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.SignupPage, EventType.NewVolunteer, 0, Organization.PPFIid, person.GeographyId, 0, 0, textParameter); PWLog.Write(PWLogItem.Person, person.Identity, PWLogAction.MemberAdd, "Volunteered for local officership.", string.Empty); } } }