protected void btnEmail_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(PUsername.Text.Trim())) { var patron = Patron.GetObjectByUsername(PUsername.Text.Trim()); // Show message no matter what, even if we can't do it, because of hacking concerns if (patron == null || string.IsNullOrEmpty(patron.EmailAddress)) { new SessionTools(Session).AlertPatron("Your account could not be located or is not associated with an email address. Please visit your local library branch to reset your password.", PatronMessageLevels.Warning, "exclamation-sign"); } else { string remoteAddress = Request.UserHostAddress; string passwordResetToken = patron.GeneratePasswordResetToken(); if (string.IsNullOrEmpty(passwordResetToken)) { new SessionTools(Session).AlertPatron("Unable to reset your password. Please visit your local library branch.", PatronMessageLevels.Warning, "exclamation-sign"); return; } string systemName = SRPSettings.GetSettingValue("SysName"); var values = new { SystemName = systemName, PasswordResetLink = string.Format("{0}{1}?token={2}", WebTools.GetBaseUrl(Request), "/PasswordRecovery.aspx", passwordResetToken), ContactName = SRPSettings.GetSettingValue("ContactName"), ContactEmail = SRPSettings.GetSettingValue("ContactEmail"), RemoteAddress = remoteAddress, UserEmail = patron.EmailAddress, Username = patron.Username, PasswordResetSubject = string.Format("{0} password reset request", systemName) }; StringBuilder body = new StringBuilder(); body.Append("<p>A password reset request was received by {SystemName} for "); body.Append("your account: {Username}.</p><p>Please "); body.Append("<a href=\"{PasswordResetLink}\">click here</a> in the next hour "); body.Append("to create a new password for your account.</p>"); body.Append("<p>If you did not initiate this request, take no action and your "); body.Append("password will not be changed.</p>"); body.Append("<p>If you have any comments or questions, please contact "); body.Append("{ContactName} at "); body.Append("<a href=\"mailto:{ContactEmail}\">{ContactEmail}</a>.</p>"); body.Append("<p style=\"font-size: smaller;\"><em>This password request was "); body.Append("submitted from: {RemoteAddress}.</em></p>"); new EmailService().SendEmail(patron.EmailAddress, "{SystemName} - {PasswordResetSubject}".FormatWith(values), body.ToString().FormatWith(values)); new SessionTools(Session).AlertPatron("Processing your password reset request, you should receive an email soon.", glyphicon: "ok"); } new SessionTools(Session).ClearPatron(); Response.Redirect("~"); } }
protected void btnLogin_Click(object sender, EventArgs e) { if (Page.IsValid) { object tokenObject = this.ViewState["token"]; if (tokenObject == null) { new SessionTools(Session).AlertPatron(GetResourceString("password-recovery-expired"), PatronMessageLevels.Warning, "exclamation-sign"); Response.Redirect("~/Recover.aspx"); return; } var user = Patron.UpdatePasswordByToken(tokenObject.ToString(), NPassword.Text); if (user == null) { new SessionTools(Session).AlertPatron(GetResourceString("password-recovery-expired"), PatronMessageLevels.Warning, "exclamation-sign"); Response.Redirect("~/Recovery.aspx"); return; } // user requested a password for an email address that is not in the database // if account doesn't exist, send an email saying so var values = new { SystemName = SRPSettings.GetSettingValue("SysName"), ContactName = SRPSettings.GetSettingValue("ContactName"), ContactEmail = SRPSettings.GetSettingValue("ContactEmail"), RemoteAddress = Request.UserHostAddress, UserEmail = user.EmailAddress, Username = user.Username, LoginLink = string.Format("{0}{1}", WebTools.GetBaseUrl(Request), "/Login.aspx"), PasswordResetSuccessSubject = "Your password has been reset!" }; this.Log().Info("Password reset process for {0} ({1}) complete from {2}", values.Username, values.UserEmail, values.RemoteAddress); // TODO email - move this template out to the database StringBuilder body = new StringBuilder(); body.Append("<p>The password change has been successful for the {SystemName} account: {Username}.</p>"); body.Append("<p>You may now <a href=\"{LoginLink}\">log in</a> using your new password.</p>"); body.Append("<p>If you have any comments or questions, please contact "); body.Append("{ContactName} at <a href=\"mailto:{ContactEmail}\">{ContactEmail}</a>.</p>"); body.Append("<p style=\"font-size: smaller;\"><em>This password request was "); body.Append("completed from: {RemoteAddress}.</em></p>"); new EmailService().SendEmail(user.EmailAddress, "{SystemName} - {PasswordResetSuccessSubject}".FormatWith(values), body.ToString().FormatWith(values)); var st = new SessionTools(Session); st.EstablishPatron(user); st.AlertPatron(GetResourceString("Your password has been reset!"), glyphicon: "ok"); Response.Redirect("~"); } }
protected void Page_Load(object sender, EventArgs e) { if (!String.IsNullOrEmpty(Request["PID"])) { Session["ProgramID"] = Request["PID"].ToString(); } if (!IsPostBack) { if (Session["ProgramID"] == null) { try { int PID = Programs.GetDefaultProgramID(); Session["ProgramID"] = PID.ToString(); } catch { Response.Redirect("~/Badges/"); } } } TranslateStrings(this); badgeBackLink.NavigateUrl = "~/Badges/"; TwitterShare.Visible = false; FacebookShare.Visible = false; try { int badgeId = 0; string displayBadge = Request.QueryString["BadgeId"]; if (!int.TryParse(displayBadge, out badgeId)) { throw new Exception("Invalid badge id provided."); } int patronId = 0; var patron = Session[SessionKey.Patron] as DAL.Patron; if (patron != null) { patronId = patron.PID; } var badgeDetailData = new Logic.Badge().GetForDisplay(Server, badgeId, patronId); if (badgeDetailData.Hidden == true && badgeDetailData.Earned == false) { throw new Exception("Secret badge must be earned to be revealed."); } badgeTitle.Text = badgeDetailData.DisplayName; this.Title = string.Format("Badge: {0}", badgeTitle.Text); this.MetaDescription = string.Format("All about the {0} badge - {1}", badgeTitle.Text, GetResourceString("system-name")); badgeImage.ImageUrl = badgeDetailData.ImageUrl; badgeImage.AlternateText = badgeDetailData.AlternateText; if (!string.IsNullOrEmpty(badgeDetailData.DateEarned)) { badgeEarnWhen.Text = string.Format("<p><strong>You earned this badge on {0}!</strong></p>", badgeDetailData.DateEarned); badgeEarnWhen.Visible = true; } else { badgeEarnWhen.Visible = false; } badgeDetails.Visible = true; if (badgeDetailData.HowToEarn.Length > 0) { badgeDesriptionLabel.Visible = true; badgeDesriptionLabel.Text = this.Server.HtmlDecode(badgeDetailData.Description); } else { badgeDesriptionLabel.Visible = false; } if (!badgeDetailData.HideDefaultDescription) { badgeEarnPanel.Visible = true; StringBuilder sb = new StringBuilder(); foreach (var line in badgeDetailData.HowToEarn) { sb.AppendFormat("<li>{0}</li>", line); } badgeEarnLabel.Text = sb.ToString(); } else { badgeEarnPanel.Visible = false; } /* metadata */ string systemName = GetResourceString("system-name"); var fbDescription = StringResources.getStringOrNull("facebook-description"); var hashtags = StringResources.getStringOrNull("socialmedia-hashtags"); string title = string.Format("{0} badge: {1}", systemName, badgeDetailData.DisplayName); string description = null; string twitDescrip = null; if (badgeDetailData.Earned) { description = string.Format("By participating in {0} I earned this badge: {1}!", systemName, badgeDetailData.DisplayName); twitDescrip = string.Format("I earned this {0} badge: {1}!", systemName, badgeDetailData.DisplayName); if (twitDescrip.Length > 118) { // if it's longer than this it won't fit with the url, shorten it twitDescrip = string.Format("I earned this badge: {0}!", badgeDetailData.DisplayName); } } else { description = string.Format("By participating in {0} you can earn this badge: {1}!", systemName, badgeDetailData.DisplayName); twitDescrip = string.Format("Check out this {0} badge: {1}!", systemName, badgeDetailData.DisplayName); if (twitDescrip.Length > 118) { // if it's longer than this it won't fit with the url, shorten it twitDescrip = string.Format("Check out this badge: {0}!", badgeDetailData.DisplayName); } } var wt = new WebTools(); var baseUrl = WebTools.GetBaseUrl(Request); var badgeDetailsUrl = string.Format("{0}/Badges/Details.aspx?BadgeId={1}", baseUrl, badgeDetailData.BadgeId); var badgeImagePath = string.Format("{0}{1}", baseUrl, VirtualPathUtility.ToAbsolute(badgeDetailData.ImageUrl)); wt.AddOgMetadata(Metadata, title, wt.BuildFacebookDescription(description, hashtags, fbDescription), badgeImagePath, badgeDetailsUrl, GetResourceString("facebook-appid")); wt.AddTwitterMetadata(Metadata, title, twitDescrip, badgeImagePath, twitterUsername: GetResourceString("twitter-username")); TwitterShare.NavigateUrl = wt.GetTwitterLink(twitDescrip, Server.UrlEncode(badgeDetailsUrl), hashtags); FacebookShare.NavigateUrl = wt.GetFacebookLink(Server.UrlEncode(badgeDetailsUrl)); if (!badgeDetailData.Hidden) { TwitterShare.Visible = true; FacebookShare.Visible = true; } // end social badgeDetails.Visible = true; } catch (Exception) { badgeDetails.Visible = false; var cph = Page.Master.FindControl("HeaderContent") as ContentPlaceHolder; if (cph != null) { cph.Controls.Add(new HtmlMeta { Name = "robots", Content = "noindex" }); } new SessionTools(Session).AlertPatron("Could not find details on that badge.", PatronMessageLevels.Warning, "exclamation-sign"); } }
protected List <string> ConfigureTheGRA() { var issues = new List <string>(); Configuration webConfig = null; try { webConfig = WebConfigurationManager.OpenWebConfiguration("~"); } catch (Exception ex) { issues.Add(string.Format("Could not read the Web.config file on the disk (this is probably due to permissions): {0}", ex.Message)); return(issues); } try { webConfig.Save(ConfigurationSaveMode.Minimal); } catch (Exception ex) { issues.Add(string.Format("Could not write to the Web.config file on the disk (this is probably due to permissions): {0}", ex.Message)); return(issues); } var ownerBuilder = new SqlConnectionStringBuilder(); ownerBuilder.DataSource = DatabaseServer.Text; ownerBuilder.InitialCatalog = DatabaseCatalog.Text; if (!DatabaseServer.Text.Contains("(localdb)")) { ownerBuilder.UserID = DatabaseOwnerUser.Text; ownerBuilder.Password = ViewState[DbOwnerKey].ToString(); } using (var sqlConnection = new SqlConnection(ownerBuilder.ConnectionString)) { // do database script run var path = CreateSchemaPath; this.Log().Info("Creating database schema"); var schemaIssues = ExecuteSqlFile(path, sqlConnection); if (schemaIssues.Count > 0) { return(schemaIssues); } if (ReadingProgram.SelectedIndex == 0) { // single program path = Insert1ProgramPath; } else { // multiple programs path = Insert4ProgramsPath; } var insertIssues = ExecuteSqlFile(path, sqlConnection); if (insertIssues.Count > 0) { return(insertIssues); } // update email address sqlConnection.Open(); try { // update the sysadmin user's email SqlCommand updateEmail = new SqlCommand("UPDATE [SRPUser] SET [EmailAddress] = @emailAddress WHERE [Username] = 'sysadmin';", sqlConnection); updateEmail.Parameters.AddWithValue("@emailAddress", MailAddress.Text); updateEmail.ExecuteNonQuery(); } catch (Exception ex) { string error = string.Format("Unable to update administrative email address: {0}", ex); this.Log().Error(error); } try { // update the sysadmin contact email and mail from address // TODO email - provide better setup for email SqlCommand updateEmail = new SqlCommand("UPDATE [SRPSettings] SET [Value] = @emailAddress WHERE [Name] IN ('ContactEmail', 'FromEmailAddress');", sqlConnection); updateEmail.Parameters.AddWithValue("@emailAddress", MailAddress.Text); updateEmail.ExecuteNonQuery(); } catch (Exception ex) { string error = string.Format("Unable to update administrative email address: {0}", ex); this.Log().Error(error); } sqlConnection.Close(); } // data inserted, update Web.config try { var userBuilder = new SqlConnectionStringBuilder(); userBuilder.DataSource = DatabaseServer.Text; userBuilder.InitialCatalog = DatabaseCatalog.Text; if (!DatabaseServer.Text.Contains("(localdb)")) { userBuilder.UserID = DatabaseUserUser.Text; userBuilder.Password = ViewState[DbUserKey].ToString(); } var csSection = (ConnectionStringsSection)webConfig.GetSection("connectionStrings"); csSection.ConnectionStrings[GlobalUtilities.SRPDBConnectionStringName].ConnectionString = userBuilder.ConnectionString; var mailSection = (MailSettingsSectionGroup)webConfig.GetSectionGroup("system.net/mailSettings"); var network = mailSection.Smtp.Network; if (!string.IsNullOrEmpty(MailServer.Text)) { network.Host = MailServer.Text; mailSection.Smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; } mailSection.Smtp.From = null; if (!string.IsNullOrEmpty(MailPort.Text)) { int port = 0; if (int.TryParse(MailPort.Text, out port)) { network.Port = port; } } if (!string.IsNullOrEmpty(MailLogin.Text)) { network.UserName = MailLogin.Text; } if (ViewState[MailPwKey] != null && !string.IsNullOrEmpty(ViewState[MailPwKey].ToString())) { network.Password = ViewState[MailPwKey].ToString(); } webConfig.Save(ConfigurationSaveMode.Minimal); } catch (Exception ex) { string error = string.Format("Couldn't update Web.config with new connection string: {0}", ex.Message); this.Log().Error(error); issues.Add(error); } if (issues.Count == 0) { this.Log().Info(() => "Great Reading Adventure setup complete!"); try { // TODO email - move this template out to the database var values = new { SystemName = "The Great Reading Adventure", ControlRoomLink = string.Format("{0}{1}", WebTools.GetBaseUrl(Request), "/ControlRoom/"), }; StringBuilder body = new StringBuilder(); body.Append("<p>Congratulations! You have successfully configured "); body.Append("{SystemName}!</p><p>You may now "); body.Append("<a href=\"{ControlRoomLink}\">log in</a> using the default "); body.Append("system administrator credentials.</p><p>For more information on "); body.Append("setting up and using the {SystemName} software, feel free to "); body.Append("visit the <a href=\"http://manual.greatreadingadventure.com/\">manual</a>"); body.Append("and <a href=\"http://forum.greatreadingadventure.com/\">forum</a>."); body.Append("</p>"); new EmailService().SendEmail(MailAddress.Text, "{SystemName} - Setup complete!" .FormatWith(values), body.ToString().FormatWith(values)); this.Log().Info(() => "Welcome email sent."); } catch (Exception ex) { this.Log().Error(() => "Welcome email sending failure: {Message}" .FormatWith(ex)); } return(null); } else { return(issues); } }
protected void LookupChallenge(int blid) { var bl = BookList.FetchObject(blid); if (bl == null) { challengeDetails.Visible = false; new SessionTools(Session).AlertPatron("Could not find details on that Challenge.", PatronMessageLevels.Warning, "exclamation-sign"); } else { int patronId = -1; var p = Session[SessionKey.Patron] as Patron; if (p != null) { patronId = p.PID; } // see if this is bound to a specific program if (bl.ProgID != 0) { // no user is logged in, don't show it if (p == null) { var prog = DAL.Programs.FetchObject(bl.ProgID); challengeDetails.Visible = false; new SessionTools(Session).AlertPatron( string.Format("You must be registered in the <strong>{0}</strong> program to view this Challenge.", prog.TabName), PatronMessageLevels.Warning, "exclamation-sign"); } // user is registered under another program if (p != null && bl.ProgID != p.ProgID) { var prog = DAL.Programs.FetchObject(bl.ProgID); challengeDetails.Visible = false; new SessionTools(Session).AlertPatron( string.Format("That Challenge is only available to people in the <strong>{0}</strong> program.", prog.TabName), PatronMessageLevels.Warning, "exclamation-sign"); } } if (challengeDetails.Visible) { Badge badge = null; challengeTitle.Text = bl.ListName; this.Title = string.Format("Challenge: {0}", challengeTitle.Text); lblDesc.Text = string.Format("<p>{0}</p>", Server.HtmlDecode(bl.Description)); string award = null; if (bl.AwardPoints > 0) { award = string.Format("Completing <strong>{0} task{1}</strong> will earn: <strong>{2} point{3}</strong>", bl.NumBooksToComplete, bl.NumBooksToComplete > 1 ? "s" : string.Empty, bl.AwardPoints, bl.AwardPoints > 1 ? "s" : string.Empty); } if (bl.AwardBadgeID > 0) { badge = DAL.Badge.FetchObject(bl.AwardBadgeID); if (badge != null) { if (badge.HiddenFromPublic != true) { if (string.IsNullOrWhiteSpace(award)) { award = string.Format("Completing {0} task{1} will earn: <strong>a badge</strong>.", bl.NumBooksToComplete, bl.NumBooksToComplete > 1 ? "s" : string.Empty); } else { award += " and <strong>a badge</strong>."; } BadgeImage.Text = string.Format("<img class=\"thumbnail disabled\" src=\"/images/badges/sm_{0}.png\" />", bl.AwardBadgeID); } else { badge = null; if (string.IsNullOrWhiteSpace(award)) { award = string.Format("Completing {0} task{1} will earn: <strong>a secret badge</strong>.", bl.NumBooksToComplete, bl.NumBooksToComplete > 1 ? "s" : string.Empty); } else { award += " and <strong>a secret badge</strong>."; } BadgeImage.Text = string.Empty; } } } else { BadgeImage.Text = string.Empty; award += "."; } BadgeImage.Visible = !string.IsNullOrEmpty(BadgeImage.Text); if (!string.IsNullOrWhiteSpace(award)) { lblPoints.Text = award; lblPoints.Visible = true; } var ds = BookListBooks.GetForDisplay(bl.BLID, patronId); //Eval("NumBooksCompleted"), Eval("NumBooksToComplete") if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { int completed = 0; foreach (DataRow row in ds.Tables[0].Rows) { if ((bool?)row["HasRead"] == true) { completed++; if (completed >= bl.NumBooksToComplete) { ChallengeCompleted = true; break; } } } } rptr.DataSource = ds; rptr.DataBind(); // begin social var wt = new WebTools(); string systemName = StringResources.getStringOrNull("system-name"); var fbDescription = StringResources.getStringOrNull("facebook-description"); var hashtags = StringResources.getStringOrNull("socialmedia-hashtags"); string title = string.Format("{0} challenge: {1}", systemName, bl.ListName); string description = string.Format("Check out this {0} challenge: {1}!", systemName, bl.ListName); string twitDescrip = description; if (twitDescrip.Length > 118) { // if it's longer than this it won't fit with the url, shorten it twitDescrip = string.Format("Check this out: {0}!", bl.ListName); } var baseUrl = WebTools.GetBaseUrl(Request); var challengeUrl = string.Format("{0}/Challenges/Details.aspx?ChallengeId={1}", baseUrl, bl.BLID); string imagePath = null; if (badge != null) { string potentialBadgePath = string.Format("~/Images/Badges/{0}.png", badge.BID); if (System.IO.File.Exists(Server.MapPath(potentialBadgePath))) { imagePath = string.Format("{0}{1}", baseUrl, VirtualPathUtility.ToAbsolute(potentialBadgePath)); } } if (string.IsNullOrEmpty(imagePath)) { imagePath = new GRA.Logic.Banner().FullMetadataBannerPath(baseUrl, Session, Server); } wt.AddOgMetadata(Metadata, title, wt.BuildFacebookDescription(description, hashtags, fbDescription), imagePath, challengeUrl, facebookApp: GetResourceString("facebook-appid")); wt.AddTwitterMetadata(Metadata, title, description, imagePath, twitterUsername: GetResourceString("twitter-username")); TwitterShare.NavigateUrl = wt.GetTwitterLink(description, Server.UrlEncode(challengeUrl), hashtags); TwitterShare.Visible = true; FacebookShare.NavigateUrl = wt.GetFacebookLink(Server.UrlEncode(challengeUrl)); FacebookShare.Visible = true; // end social this.ShowModal = true; } } }
protected void Page_Load(object sender, EventArgs e) { AvatarBackLink.NavigateUrl = "~/"; SystemName.Text = SystemNamePrint.Text = StringResources.getString("system-name"); SystemSlogan.Text = SystemSloganPrint.Text = StringResources.getString("slogan"); SystemSlogan.Visible = SystemSloganPrint.Visible = SystemSlogan.Text != "slogan"; string programId = null; AvatarBackLink.Text = StringResources.getString("avatar-return"); if (AvatarBackLink.Text == "avatar-return") { AvatarBackLink.Text = "Back"; } var patron = Session[SessionKey.Patron] as DAL.Patron; if (patron != null) { programId = patron.ProgID.ToString(); MyAvatarPrint.Text = Tools.DisplayHelper.FormatName(patron.FirstName, patron.LastName, patron.Username); } else { MyAvatarPrint.Text = "My Avatar"; } if (string.IsNullOrEmpty(programId)) { var sessionProgId = Session["ProgramId"]; if (sessionProgId != null) { programId = sessionProgId.ToString(); } } if (string.IsNullOrEmpty(programId)) { try { programId = DAL.Programs.GetDefaultProgramID().ToString(); } catch (Exception) { } } string bannerPath = new Logic.Banner().FullMetadataBannerPath( WebTools.GetBaseUrl(Request), programId, Server); if (!string.IsNullOrEmpty(bannerPath)) { BannerImagePrint.ImageUrl = bannerPath; } else { BannerImagePrint.Visible = false; } string avatarPath = null; string avatarMdPath = null; bool validAvatar = false; string avatarId = Request.QueryString["AvatarId"]; if (!string.IsNullOrEmpty(avatarId) && avatarId.Length <= 24) { char[] avatarIdArray = avatarId.ToCharArray(); avatarIdArray = Array.FindAll <char>(avatarIdArray, (c => (char.IsLetterOrDigit(c)))); avatarId = new string(avatarIdArray); avatarPath = string.Format("~/Images/AvatarCache/{0}.png", avatarId); avatarMdPath = string.Format("~/Images/AvatarCache/md_{0}.png", avatarId); if (File.Exists(Server.MapPath(avatarPath))) { validAvatar = true; AvatarImage.ImageUrl = AvatarImagePrint.ImageUrl = avatarPath; AvatarPanel.Visible = true; } } if (!validAvatar) { AvatarPanel.Visible = false; } else { // begin social var wt = new WebTools(); var fbDescription = StringResources.getStringOrNull("facebook-description"); var hashtags = StringResources.getStringOrNull("socialmedia-hashtags"); var title = string.Format("{0} avatar", SystemName.Text); var description = string.Format("Check out this awesome avatar in {0}!", SystemName.Text); var baseUrl = WebTools.GetBaseUrl(Request); var avatarDetailPath = string.Format("{0}/Avatar/View.aspx?AvatarId={1}", baseUrl, avatarId); var fullAvatarPath = string.Format("{0}{1}", baseUrl, VirtualPathUtility.ToAbsolute(avatarPath)); var fullAvatarMdPath = string.Format("{0}{1}", baseUrl, VirtualPathUtility.ToAbsolute(avatarMdPath)); if (patron != null) { title = string.Format("My {0} avatar", SystemName.Text); description = string.Format("Check out my awesome avatar in {0}!", SystemName.Text); } wt.AddOgMetadata(Metadata, title, wt.BuildFacebookDescription(description, hashtags, fbDescription), fullAvatarPath, avatarDetailPath, facebookApp: StringResources.getString("facebook-appid")); wt.AddTwitterMetadata(Metadata, title, description, fullAvatarMdPath, StringResources.getString("twitter-username")); TwitterShare.NavigateUrl = wt.GetTwitterLink(description, Server.UrlEncode(avatarDetailPath), hashtags); TwitterShare.Visible = true; FacebookShare.NavigateUrl = wt.GetFacebookLink(Server.UrlEncode(avatarDetailPath)); FacebookShare.Visible = true; // end social } AvatarPrintPanel.Visible = AvatarPanel.Visible; AvatarAlert.Visible = !AvatarPanel.Visible; }
protected void rptr_ItemDataBound(object source, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { var eventRow = e.Item.DataItem as System.Data.DataRowView; var branchName = eventRow["Branch"].ToString(); var branchAddress = eventRow["BranchAddress"]; var branchTelephone = eventRow["BranchTelephone"]; var branchLink = eventRow["BranchLink"]; var label = e.Item.FindControl("BranchName") as Literal; bool haveLink = branchLink != null && !string.IsNullOrWhiteSpace(branchLink.ToString()); bool haveAddress = branchAddress != null && !string.IsNullOrWhiteSpace(branchAddress.ToString()); DateTime eventDate = DateTime.MinValue; if (eventRow["EventDate"] != null) { eventDate = eventRow["EventDate"] as DateTime? ?? DateTime.MinValue; } if (haveLink) { label.Text = string.Format(WebTools.BranchLinkStub, branchLink.ToString(), branchName); } if (haveAddress) { label.Text += string.Format(WebTools.BranchMapStub, HttpUtility.UrlEncode(branchAddress.ToString())); } try { if (haveLink && haveAddress && eventDate != DateTime.MinValue) { string detailsLink = string.Format("{0}{1}", WebTools.GetBaseUrl(Request), ResolveUrl(string.Format("~/Events/Details.aspx?EventId={0}", eventRow["EID"]))); SchemaOrgLibrary mdLib = new SchemaOrgLibrary { Name = branchName, Address = branchAddress.ToString(), Url = branchLink.ToString() }; if (branchTelephone != null && !string.IsNullOrWhiteSpace(branchTelephone.ToString())) { mdLib.Telephone = branchTelephone.ToString(); } SchemaOrgEvent mdEvt = new SchemaOrgEvent { Name = eventRow["EventTitle"].ToString(), Url = detailsLink, Location = mdLib, StartDate = eventDate }; var md = e.Item.FindControl("Microdata") as Literal; if (md != null) { md.Text = new WebTools().BuildEventJsonld(mdEvt); } } } catch (Exception ex) { this.Log().Error("Problem creating microdata in event list for {0}: {1} - {2}", eventRow["EID"], ex.Message, ex.StackTrace); } } }
protected void btnEmail_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(PUsername.Text.Trim())) { var patron = Patron.GetObjectByUsername(PUsername.Text.Trim()); if (patron == null || string.IsNullOrEmpty(patron.EmailAddress)) { new SessionTools(Session).AlertPatron("Your account could not be located or is not associated with an email address. Please visit your local library branch to reset your password.", PatronMessageLevels.Warning, "exclamation-sign"); if (patron != null) { this.Log().Info("Unable to send password recovery email for patron id {0} becuase they don't have an email address configured", patron.PID); } return; } else { try { string remoteAddress = new WebTools().RemoteUserAddress(Request); string passwordResetToken = patron.GeneratePasswordResetToken(); if (string.IsNullOrEmpty(passwordResetToken)) { new SessionTools(Session).AlertPatron("Unable to reset your password. Please visit your local library branch.", PatronMessageLevels.Warning, "exclamation-sign"); this.Log().Fatal("Unable to generate password reset token - critical error in password recovery"); return; } string systemName = SRPSettings.GetSettingValue("SysName"); var values = new { SystemName = systemName, PasswordResetLink = string.Format("{0}{1}?token={2}", WebTools.GetBaseUrl(Request), "/PasswordRecovery.aspx", passwordResetToken), ContactName = SRPSettings.GetSettingValue("ContactName"), ContactEmail = SRPSettings.GetSettingValue("ContactEmail"), RemoteAddress = remoteAddress, UserEmail = patron.EmailAddress, Username = patron.Username, PasswordResetSubject = string.Format("{0} password reset request", systemName) }; StringBuilder body = new StringBuilder(); body.Append("<p>A password reset request was received by {SystemName} for "); body.Append("your account: {Username}.</p><p>Please "); body.Append("<a href=\"{PasswordResetLink}\">click here</a> "); body.Append("to create a new password for your account.</p>"); body.Append("<p>If you did not initiate this request, take no action and your "); body.Append("password will not be changed.</p>"); body.Append("<p>If you have any comments or questions, please contact "); body.Append("{ContactName} at "); body.Append("<a href=\"mailto:{ContactEmail}\">{ContactEmail}</a>.</p>"); body.Append("<p style=\"font-size: smaller;\"><em>This password request was "); body.Append("submitted from: {RemoteAddress}.</em></p>"); new EmailService().SendEmail(patron.EmailAddress, "{SystemName} - {PasswordResetSubject}".FormatWith(values), body.ToString().FormatWith(values)); this.Log().Info("Sent password request email for patron id {0} to {1}", patron.PID, patron.EmailAddress); new SessionTools(Session).AlertPatron("Processing your password reset request, you should receive an email soon.", glyphicon: "ok"); } catch (Exception ex) { this.Log().Fatal("Unable to send password recovery email for patron id {0} to {1}: {2} - {3}", patron.PID, patron.EmailAddress, ex.Message, ex.StackTrace); new SessionTools(Session).AlertPatron("A problem occurred resetting your password. Please visit your local library branch to reset your password.", PatronMessageLevels.Warning, "exclamation-sign"); } } new SessionTools(Session).ClearPatron(); Response.Redirect("~"); } }
protected void InstallBtn_Click(object sender, EventArgs e) { //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// string createSchemaFile = "~/ControlRoom/Modules/Install/CreateSchema.sql"; string initialDataFile = "~/ControlRoom/Modules/Install/InsertInitialData.sql"; //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// string conn = null; string rcon = null; bool localDbMode = DBServer.Text.ToUpper() == "(LOCALDB)"; Configuration webConfig = null; if (string.IsNullOrEmpty(Mailaddress.Text)) { return; } this.Log().Info("GRA setup started, using LocalDb is: {0}", localDbMode); // test writing to Web.config before we go further if (!localDbMode) { if (!this.IsValid) { return; } try { webConfig = WebConfigurationManager.OpenWebConfiguration("~"); } catch (Exception ex) { this.Log().Error("There was an error reading the Web.config: {0}", ex.Message); FailureText.Text = "There was an error when trying to read the Web.config file, see below:"; errorLabel.Text = ex.Message; return; } try { webConfig.Save(); } catch (Exception ex) { this.Log().Error("There was an error writing the Web.config file: {0}", ex.Message); FailureText.Text = "There was an error when trying to write to the Web.config file, see below:"; errorLabel.Text = ex.Message; return; } } if (localDbMode) { conn = GlobalUtilities.SRPDB; rcon = GlobalUtilities.SRPDB; // set reasonable defaults string dataSource = @"(localdb)\ProjectsV12"; string dbName = "SRP"; // try to parse out data source and database name try { var builder = new SqlConnectionStringBuilder(conn); if (!string.IsNullOrEmpty(builder.DataSource)) { dataSource = builder.DataSource; } if (!string.IsNullOrEmpty(builder.InitialCatalog)) { dbName = builder.InitialCatalog; } } catch (Exception) { // if we can't parse the connection string, use defaults } string localDbCs = string.Format("server={0}", dataSource); string existsQuery = string.Format("SELECT [database_id] FROM [sys].[databases] " + "WHERE [Name] = '{0}'", dbName); object result = null; try { result = SqlHelper.ExecuteScalar(localDbCs, CommandType.Text, existsQuery); } catch (Exception ex) { this.Log().Error("There was an error when trying to connect to LocalDb: {0}", ex.Message); FailureText.Text = "There was an error when trying to connect to LocalDb, see below:"; errorLabel.Text = ex.Message; return; } if (result == null) { string createDb = string.Format("CREATE DATABASE [{0}]", dbName); try { SqlHelper.ExecuteNonQuery(localDbCs, CommandType.Text, createDb); } catch (Exception ex) { this.Log().Error("There was an error creating the database: {0}", ex.Message); FailureText.Text = "There was an error creating the database, see below:"; errorLabel.Text = ex.Message; } } } else { if (!this.IsValid) { return; } conn = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}", DBServer.Text, DBName.Text, UserName.Text, Password.Text); rcon = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}", DBServer.Text, DBName.Text, RunUser.Text, RuntimePassword.Text); } var mailHost = Mailserver.Text; try { SqlHelper.ExecuteNonQuery(conn, CommandType.Text, "SELECT 1"); } catch (Exception ex) { this.Log().Error("There was an error when trying to connect with the SA account: {0}", ex.Message); FailureText.Text = "There was an error when trying to connect with the SA account, see below:"; errorLabel.Text = ex.Message; return; } try { SqlHelper.ExecuteNonQuery(rcon, CommandType.Text, "SELECT 1"); } catch (Exception ex) { this.Log().Error("There was an error when trying to connect with the runtime account: {0}", ex.Message); FailureText.Text = "There was an error when trying to connect with the runtime account, see below:"; errorLabel.Text = ex.Message; return; } //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// List <string> issues = new List <string>(); this.Log().Info("Executing the queries to create the database schema."); issues = ExecuteSqlFile(createSchemaFile, conn); if (issues.Count == 0) { this.Log().Info("Executing the queries to insert the initial data."); issues = ExecuteSqlFile(initialDataFile, conn); if (issues.Count != 0) { issues.Add(LogAndReturnError("Could not insert initial data. GRA will not work until the data will insert properly. Please resolve the issue, recreate the database, and run this process again.")); } } else { // schema create didn't work issues.Add(LogAndReturnError("Not inserting initial data due to schema issue. Please resolve the issue, recreate the database, and run this process again.")); } if (issues.Count == 0) { // update email address with what the user entered this.Log().Info("Updating the administrative email addresses to: {0}", Mailaddress); using (var connection = new SqlConnection(conn)) { try { connection.Open(); try { // update the sysadmin user's email SqlCommand updateEmail = new SqlCommand("UPDATE [SRPUser] SET [EmailAddress] = @emailAddress WHERE [Username] = 'sysadmin';", connection); updateEmail.Parameters.AddWithValue("@emailAddress", Mailaddress.Text); updateEmail.ExecuteNonQuery(); } catch (Exception ex) { issues.Add(LogAndReturnError(string.Format("Unable to update sysadmin email: {0}", ex.Message))); } try { // update the sysadmin contact email and mail from address // TODO email - provide better setup for email SqlCommand updateEmail = new SqlCommand("UPDATE [SRPSettings] SET [Value] = @emailAddress WHERE [Name] IN ('ContactEmail', 'FromEmailAddress');", connection); updateEmail.Parameters.AddWithValue("@emailAddress", Mailaddress.Text); updateEmail.ExecuteNonQuery(); } catch (Exception ex) { issues.Add(LogAndReturnError(string.Format("Unable to update settings emails: {0}", ex.Message))); } } catch (Exception ex) { issues.Add(LogAndReturnError(string.Format("Error connecting to update email address: {0}", ex.Message))); } finally { connection.Close(); } } } if (issues.Count == 0 && !localDbMode) { // modify the Web.config this.Log().Info(() => "Updating the Web.config file with the provided settings"); webConfig = WebConfigurationManager.OpenWebConfiguration("~"); var csSection = (ConnectionStringsSection)webConfig.GetSection("connectionStrings"); csSection.ConnectionStrings[GlobalUtilities.SRPDBConnectionStringName].ConnectionString = rcon; if (mailHost != "(localhost)") { var mailSection = (MailSettingsSectionGroup)webConfig.GetSectionGroup("system.net/mailSettings"); mailSection.Smtp.Network.Host = mailHost; } webConfig.Save(); } if (issues.Count == 0) { // Delete the Install File //System.IO.File.Delete(Server.MapPath(InstallFile)); this.Log().Info(() => "Great Reading Adventure setup complete!"); try { // TODO email - move this template out to the database var values = new { SystemName = "The Great Reading Adventure", ControlRoomLink = string.Format("{0}{1}", WebTools.GetBaseUrl(Request), "/ControlRoom/"), }; StringBuilder body = new StringBuilder(); body.Append("<p>Congratulations! You have successfully configured "); body.Append("{SystemName}!</p><p>You may now "); body.Append("<a href=\"{ControlRoomLink}\">log in</a> using the default "); body.Append("system administrator credentials.</p><p>For more information on "); body.Append("setting up and using the {SystemName} software, feel free to "); body.Append("visit the <a href=\"http://manual.greatreadingadventure.com/\">manual</a>"); body.Append("and <a href=\"http://forum.greatreadingadventure.com/\">forum</a>."); body.Append("</p>"); new EmailService().SendEmail(Mailaddress.Text, "{SystemName} - Setup complete!" .FormatWith(values), body.ToString().FormatWith(values)); this.Log().Info(() => "Welcome email sent."); } catch (Exception ex) { this.Log().Error(() => "Welcome email sending failure: {Message}" .FormatWith(ex)); } Response.Redirect("~/ControlRoom/"); } else { FailureText.Text = "There have been errors, see details below."; StringBuilder errorText = new StringBuilder(); foreach (var issue in issues) { errorText.Append(issue); errorText.AppendLine("<br>"); } errorLabel.Text = errorText.ToString(); } }
protected void Page_Load(object sender, EventArgs e) { if (!String.IsNullOrEmpty(Request["PID"])) { Session["ProgramID"] = Request["PID"].ToString(); } if (!IsPostBack) { if (Session["ProgramID"] == null) { try { int PID = Programs.GetDefaultProgramID(); Session["ProgramID"] = PID.ToString(); } catch { Response.Redirect("~/Default.aspx"); } } } TranslateStrings(this); eventBackLink.NavigateUrl = "~/Events/"; DAL.Event evnt = null; int eventId = 0; string displayEvent = Request.QueryString["EventId"]; if (!string.IsNullOrEmpty(displayEvent) && int.TryParse(displayEvent.ToString(), out eventId)) { evnt = DAL.Event.GetEvent(eventId); if (evnt != null && evnt.HiddenFromPublic) { evnt = null; } if (evnt != null) { SchemaOrgLibrary mdLib = new SchemaOrgLibrary(); SchemaOrgEvent mvEvt = new SchemaOrgEvent { Name = evnt.EventTitle, StartDate = evnt.EventDate }; eventTitle.Text = evnt.EventTitle; this.Title = string.Format("Event Details: {0}", eventTitle.Text); eventWhen.Text = DAL.Event.DisplayEventDateTime(evnt); eventWhere.Visible = false; eventWhereLink.Visible = false; atLabel.Visible = false; if (evnt.BranchID > 0) { var codeObject = DAL.Codes.FetchObject(evnt.BranchID); if (codeObject != null) { eventWhere.Text = mdLib.Name = codeObject.Description; eventWhereLink.Text = string.Format("{0} <span class=\"glyphicon glyphicon-new-window hidden-print\"></span>", codeObject.Description); eventWhere.Visible = true; atLabel.Visible = true; eventWhereLink.Visible = false; } var crosswalk = DAL.LibraryCrosswalk.FetchObjectByLibraryID(evnt.BranchID); if (crosswalk != null) { if (!string.IsNullOrEmpty(eventWhere.Text) && !string.IsNullOrEmpty(crosswalk.BranchAddress)) { eventWhereMapLink.Visible = true; eventWhereMapLink.NavigateUrl = string.Format(WebTools.BranchMapLinkStub, crosswalk.BranchAddress); } if (!string.IsNullOrEmpty(eventWhere.Text) && !string.IsNullOrEmpty(crosswalk.BranchLink)) { eventWhereLink.NavigateUrl = crosswalk.BranchLink; eventWhere.Visible = false; eventWhereLink.Visible = true; atLabel.Visible = true; } mdLib.Address = crosswalk.BranchAddress; mdLib.Telephone = crosswalk.BranchTelephone; mdLib.Url = crosswalk.BranchLink; } } if (string.IsNullOrEmpty(mdLib.Name)) { this.MetaDescription = string.Format("Details about the event: {0} - {1}", mdLib.Name, GetResourceString("system-name")); } else { this.MetaDescription = string.Format("Details about the event: {0} at {1} - {2}", eventTitle.Text, eventWhere.Text, GetResourceString("system-name")); } if (!string.IsNullOrWhiteSpace(evnt.ExternalLinkToEvent)) { eventLinkPanel.Visible = true; ExternalLink.NavigateUrl = evnt.ExternalLinkToEvent; ExternalLink.Text = string.Format(eventTitle.Text); } else { eventLinkPanel.Visible = false; } eventDescription.Text = Server.HtmlDecode(evnt.HTML); var cf = DAL.CustomEventFields.FetchObject(); if (!string.IsNullOrWhiteSpace(evnt.Custom1) && !string.IsNullOrWhiteSpace(cf.Label1)) { eventCustom1Panel.Visible = true; eventCustomLabel1.Text = cf.Label1; eventCustomValue1.Text = evnt.Custom1; } else { eventCustom1Panel.Visible = false; } if (!string.IsNullOrWhiteSpace(evnt.Custom2) && !string.IsNullOrWhiteSpace(cf.Label2)) { eventCustom2Panel.Visible = true; eventCustomLabel2.Text = cf.Label2; eventCustomValue2.Text = evnt.Custom2; } else { eventCustom2Panel.Visible = false; } if (!string.IsNullOrWhiteSpace(evnt.Custom3) && !string.IsNullOrWhiteSpace(cf.Label3)) { eventCustom3Panel.Visible = true; eventCustomLabel3.Text = cf.Label3; eventCustomValue3.Text = evnt.Custom3; } else { eventCustom3Panel.Visible = false; } eventDetails.Visible = true; mvEvt.Location = mdLib; try { Microdata.Text = new WebTools().BuildEventJsonld(mvEvt); } catch (Exception ex) { this.Log().Error("Problem creating microdata in event detail for {0}: {1} - {2}", evnt.EID, ex.Message, ex.StackTrace); } // begin social var wt = new WebTools(); var systemName = StringResources.getStringOrNull("system-name"); var fbDescription = StringResources.getStringOrNull("facebook-description"); var hashtags = StringResources.getStringOrNull("socialmedia-hashtags"); var title = string.Format("{0} event: {1}", systemName, evnt.EventTitle); string description = string.Format("I'm thinking about attending this {0} event: {1}!", systemName, evnt.EventTitle); string twitDescrip = string.Format("Check out this {0} event: {1}!", systemName, evnt.EventTitle); if (twitDescrip.Length > 118) { // if it's longer than this it won't fit with the url, shorten it twitDescrip = string.Format("Check this out: {0}!", evnt.EventTitle); } var baseUrl = WebTools.GetBaseUrl(Request); var eventDetailsUrl = string.Format("{0}/Events/Details.aspx?EventId={1}", baseUrl, evnt.EID); string bannerPath = new GRA.Logic.Banner().FullMetadataBannerPath(baseUrl, Session, Server); wt.AddOgMetadata(Metadata, title, wt.BuildFacebookDescription(description, hashtags, fbDescription), bannerPath, eventDetailsUrl, facebookApp: GetResourceString("facebook-appid")); wt.AddTwitterMetadata(Metadata, title, description, bannerPath, twitterUsername: GetResourceString("twitter-username")); TwitterShare.NavigateUrl = wt.GetTwitterLink(twitDescrip, Server.UrlEncode(eventDetailsUrl), hashtags); TwitterShare.Visible = true; FacebookShare.NavigateUrl = wt.GetFacebookLink(Server.UrlEncode(eventDetailsUrl)); FacebookShare.Visible = true; //end social } } if (evnt == null) { eventDetails.Visible = false; var cph = Page.Master.FindControl("HeaderContent") as ContentPlaceHolder; if (cph != null) { cph.Controls.Add(new HtmlMeta { Name = "robots", Content = "noindex" }); } Session[SessionKey.PatronMessage] = "Could not find details on that event."; Session[SessionKey.PatronMessageLevel] = PatronMessageLevels.Warning; Session[SessionKey.PatronMessageGlyphicon] = "exclamation-sign"; } }
protected void Page_Load(object sender, EventArgs e) { if (((BaseSRPPage)Page).IsLoggedIn) { Server.Transfer("~/Dashboard.aspx"); } if (!String.IsNullOrEmpty(Request["PID"])) { Session["ProgramID"] = Request["PID"].ToString(); } if (!IsPostBack) { if (Session["ProgramID"] == null) { try { int PID = Programs.GetDefaultProgramID(); Session["ProgramID"] = PID.ToString(); } catch { Response.Redirect("~/ControlRoom/Configure.aspx"); } // pgmID.Text = Session["ProgramID"].ToString(); } else { //pgmID.Text = Session["ProgramID"].ToString(); } var systemName = GetResourceString("system-name"); var description = GetResourceString("frontpage-description"); var wt = new WebTools(); var baseUrl = WebTools.GetBaseUrl(Request); var bannerPath = new GRA.Logic.Banner().FullMetadataBannerPath(baseUrl, Session, Server); // open graph & facebook wt.AddOgMetadata(Metadata, systemName, description, bannerPath, baseUrl, facebookApp: GetResourceString("facebook-appid")); // dublin core Metadata.Controls.Add(new HtmlMeta { Name = "DC.Title", Content = systemName }); Metadata.Controls.Add(new HtmlMeta { Name = "DC.Description", Content = description }); Metadata.Controls.Add(new HtmlMeta { Name = "DC.Source", Content = baseUrl }); Metadata.Controls.Add(new HtmlMeta { Name = "DC.Type", Content = "InteractiveResource" }); //twitter wt.AddTwitterMetadata(Metadata, systemName, GetResourceString("twitter-description"), bannerPath, "summary_large_image", GetResourceString("twitter-username")); } TranslateStrings(this); }