private static void InitGlobalAttributesCache() { DateTime today = RockDateTime.Now; GlobalAttributesCache globalAttributes = GlobalAttributesCache.Read(); globalAttributes.SetValue("GradeTransitionDate", string.Format("{0}/{1}", today.Month, today.Day), false); }
private void SendEmail(string recipient, string from, string subject, string body, RockContext rockContext) { var recipients = new List <string>(); recipients.Add(recipient); var mediumData = new Dictionary <string, string>(); mediumData.Add("From", from); mediumData.Add("Subject", subject); mediumData.Add("Body", body); var mediumEntity = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid(), rockContext); if (mediumEntity != null) { var medium = MediumContainer.GetComponent(mediumEntity.Name); if (medium != null && medium.IsActive) { var transport = medium.Transport; if (transport != null && transport.IsActive) { var appRoot = GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot"); transport.Send(mediumData, recipients, appRoot, string.Empty); } } } }
/// <summary> /// Checks for merge fields and then resolves them. /// </summary> /// <param name="content">The content.</param> /// <param name="mergeObjects">The merge objects.</param> /// <param name="currentPersonOverride">The current person override.</param> /// <param name="enabledLavaCommands">The enabled lava commands.</param> /// <returns>If lava present returns merged string, if no lava returns original string, if null returns empty string</returns> public static string ResolveMergeFields(this string content, IDictionary <string, object> mergeObjects, Person currentPersonOverride, string enabledLavaCommands) { try { if (!content.HasMergeFields()) { return(content ?? string.Empty); } // If there have not been any EnabledLavaCommands explicitely set, then use the global defaults. if (enabledLavaCommands == null) { enabledLavaCommands = GlobalAttributesCache.Read().GetValue("DefaultEnabledLavaCommands"); } Template template = GetTemplate(content); template.Registers.AddOrReplace("EnabledCommands", enabledLavaCommands); template.InstanceAssigns.AddOrReplace("CurrentPerson", currentPersonOverride); return(template.Render(Hash.FromDictionary(mergeObjects))); } catch (Exception ex) { return("Error resolving Lava merge fields: " + ex.Message); } }
private void SetSMTPParameters( ) { var globalAttributes = GlobalAttributesCache.Read(); this.Server = globalAttributes.GetValue("SMTPServer"); int port = 0; if (!Int32.TryParse(globalAttributes.GetValue("SMTPPort"), out port)) { port = 0; } this.Port = port; bool useSSL = false; if (!bool.TryParse(globalAttributes.GetValue("SMTPUseSSL"), out useSSL)) { useSSL = false; } this.UseSSL = useSSL; this.UserName = globalAttributes.GetValue("SMTPUserName"); this.Password = globalAttributes.GetValue("SMTPPassword"); }
/// <summary> /// Generate a URL for the file based on the rules of the StorageProvider /// </summary> /// <param name="file">The file.</param> /// <returns></returns> public virtual string GetUrl( BinaryFile file ) { if ( !string.IsNullOrWhiteSpace( file.Path ) ) { string url = file.Path.StartsWith( "~" ) ? System.Web.VirtualPathUtility.ToAbsolute( file.Path ) : file.Path; if ( url.StartsWith( "http", StringComparison.OrdinalIgnoreCase ) ) { return url; } Uri uri = null; try { if ( HttpContext.Current != null && HttpContext.Current.Request != null ) { uri = new Uri( HttpContext.Current.Request.Url.ToString() ); } } catch { } if ( uri == null ) { uri = new Uri( GlobalAttributesCache.Read().GetValue( "PublicApplicationRoot" ) ); } if ( uri != null ) { return uri.Scheme + "://" + uri.GetComponents( UriComponents.HostAndPort, UriFormat.UriEscaped ) + url; } } return string.Empty; ; }
/// <summary> /// Handles the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit(EventArgs e) { base.OnInit(e); this.DataValueField = "Id"; this.DataTextField = UseAbbreviation ? "Id" : "Value"; _rebindRequired = false; var definedType = DefinedTypeCache.Read(new Guid(SystemGuid.DefinedType.LOCATION_ADDRESS_STATE)); this.DataSource = definedType.DefinedValues.OrderBy(v => v.Order).Select(v => new { Id = v.Name, Value = v.Description }); this.DataBind(); if (!this.Page.IsPostBack) { string orgLocGuid = GlobalAttributesCache.Read().GetValue("OrganizationAddress"); if (!string.IsNullOrWhiteSpace(orgLocGuid)) { Guid locGuid = Guid.Empty; if (Guid.TryParse(orgLocGuid, out locGuid)) { var location = new Rock.Model.LocationService().Get(locGuid); if (location != null) { var li = this.Items.FindByValue(location.State); if (li != null) { li.Selected = true; } } } } } }
/// <summary> /// Sets the organization address defaults. /// </summary> private void SetOrganizationAddressDefaults() { var globalAttributesCache = GlobalAttributesCache.Read(); _orgState = globalAttributesCache.OrganizationState; _orgCountry = globalAttributesCache.OrganizationCountry; }
protected override void OnInit(EventArgs e) { RockContext rockContext = new RockContext(); base.OnInit(e); //Reject non user if (CurrentUser == null) { NavigateToHomePage(); return; } LoadSession(rockContext); GroupType FilterGroupType = new GroupTypeService(rockContext) .Get(GlobalAttributesCache.Read().GetValue("FilterGroupType").AsGuid()); //If this group type inherits Filter Group if (CurrentGroup != null && FilterGroupType != null && CurrentGroup.GroupType.InheritedGroupTypeId == FilterGroupType.Id) { CurrentGroup.GroupType.LoadAttributes(); CurrentGroupFilters = CurrentGroup.GroupType.GetAttributeValue("FilterAttribute") .Split(new char[','], StringSplitOptions.RemoveEmptyEntries) .ToList(); } else { CurrentGroupFilters = new List <string>(); } }
private string GetSafeSender(string email) { var safeDomains = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.COMMUNICATION_SAFE_SENDER_DOMAINS.AsGuid()).DefinedValues.Select(v => v.Value).ToList(); var emailParts = email.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries); if (emailParts.Length != 2 || !safeDomains.Contains(emailParts[1], StringComparer.OrdinalIgnoreCase)) { var safeEmail = GetAttributeValue("SafeSenderEmail"); var safeEmailParts = safeEmail.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries); if (!string.IsNullOrWhiteSpace(safeEmail) && safeEmailParts.Length == 2 && safeDomains.Contains(safeEmailParts[1], StringComparer.OrdinalIgnoreCase)) { return(safeEmail); } else { return(GlobalAttributesCache.Read().GetValue("OrganizationEmail")); } } if (!string.IsNullOrWhiteSpace(email)) { return(email); } return(GlobalAttributesCache.Read().GetValue("OrganizationEmail")); }
/// <summary> /// Sends the notification. /// </summary> /// <param name="message">The message to send.</param> private void SendNotification(string message) { try { // setup merge codes for email var mergeObjects = GlobalAttributesCache.GetMergeFields(null); mergeObjects.Add("ExceptionDetails", message); // get email addresses to send to var globalAttributesCache = GlobalAttributesCache.Read(); string emailAddressesList = globalAttributesCache.GetValue("EmailExceptionsList"); if (!string.IsNullOrWhiteSpace(emailAddressesList)) { string[] emailAddresses = emailAddressesList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var recipients = new List <RecipientData>(); foreach (string emailAddress in emailAddresses) { recipients.Add(new RecipientData(emailAddress, mergeObjects)); } if (recipients.Any()) { bool sendNotification = true; Email.Send(Rock.SystemGuid.SystemEmail.CONFIG_EXCEPTION_NOTIFICATION.AsGuid(), recipients); } } } catch { } }
private void Send(string recipients, string from, string subject, string body, Dictionary <string, object> mergeFields, RockContext rockContext, bool createCommunicationRecord, Dictionary <string, string> metaData) { var recipientList = recipients.SplitDelimitedValues().ToList(); var mediumData = new Dictionary <string, string>(); mediumData.Add("From", from.ResolveMergeFields(mergeFields)); mediumData.Add("Subject", subject.ResolveMergeFields(mergeFields)); mediumData.Add("Body", System.Text.RegularExpressions.Regex.Replace(body.ResolveMergeFields(mergeFields), @"\[\[\s*UnsubscribeOption\s*\]\]", string.Empty)); var mediumEntity = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid(), rockContext); if (mediumEntity != null) { var medium = MediumContainer.GetComponent(mediumEntity.Name); if (medium != null && medium.IsActive) { var transport = medium.Transport; if (transport != null && transport.IsActive) { var appRoot = GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot"); if (transport is Rock.Communication.Transport.SMTPComponent) { ((Rock.Communication.Transport.SMTPComponent)transport).Send(mediumData, recipientList, appRoot, string.Empty, createCommunicationRecord, metaData); } else { transport.Send(mediumData, recipientList, appRoot, string.Empty); } } } } }
/// <summary> /// Gets the releases list from the rock server. /// </summary> /// <returns></returns> private List <Release> GetReleasesList() { List <Release> releases = new List <Release>(); var releaseProgram = ReleaseProgram.PRODUCTION; var updateUrl = GlobalAttributesCache.Read().GetValue("UpdateServerUrl"); if (updateUrl.Contains(ReleaseProgram.ALPHA)) { releaseProgram = ReleaseProgram.ALPHA; } else if (updateUrl.Contains(ReleaseProgram.BETA)) { releaseProgram = ReleaseProgram.BETA; } var client = new RestClient("http://www.rockrms.com/api/RockUpdate/GetReleasesList"); var request = new RestRequest(Method.GET); request.RequestFormat = DataFormat.Json; request.AddParameter("rockInstanceId", Rock.Web.SystemSettings.GetRockInstanceId()); request.AddParameter("releaseProgram", releaseProgram); IRestResponse response = client.Execute(request); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Accepted) { foreach (var release in JsonConvert.DeserializeObject <List <Release> >(response.Content)) { releases.Add(release); } } return(releases); }
/// <summary> /// Initializes a new instance of the <see cref="DayOfWeekPicker"/> class. /// </summary> public GradePicker() : base() { Label = GlobalAttributesCache.Read().GetValue("core.GradeLabel"); PopulateItems(); }
/// <summary> /// Sets up the iframe. /// </summary> private void SetupIFrame() { var globalAttributesCache = GlobalAttributesCache.Read(); string imageFileTypeWhiteList = globalAttributesCache.GetValue("ContentImageFiletypeWhitelist"); string fileTypeBlackList = globalAttributesCache.GetValue("ContentFiletypeBlacklist"); var iframeUrl = ResolveRockUrl("~/htmleditorplugins/rockfilebrowser"); string rootFolder = GetAttributeValue("RootFolder"); string browseMode = GetAttributeValue("BrowseMode"); if (string.IsNullOrWhiteSpace(browseMode)) { browseMode = "doc"; } iframeUrl += "?rootFolder=" + HttpUtility.UrlEncode(Encryption.EncryptString(rootFolder)); iframeUrl += "&browseMode=" + browseMode; iframeUrl += "&fileTypeBlackList=" + HttpUtility.UrlEncode(fileTypeBlackList); if (browseMode == "image") { iframeUrl += "&imageFileTypeWhiteList=" + HttpUtility.UrlEncode(imageFileTypeWhiteList); } iframeUrl += "&theme=" + this.RockPage.Site.Theme; iframeFileBrowser.Src = iframeUrl; }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public virtual void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; var emailTemplateGuid = dataMap.GetString("SystemEmail").AsGuidOrNull(); var dataViewGuid = dataMap.GetString("DataView").AsGuidOrNull(); if (dataViewGuid != null && emailTemplateGuid != null) { var rockContext = new RockContext(); var dataView = new DataViewService(rockContext).Get((Guid)dataViewGuid); List <IEntity> resultSet = null; var errorMessages = new List <string>(); var dataTimeout = dataMap.GetString("DatabaseTimeout").AsIntegerOrNull() ?? 180; try { var qry = dataView.GetQuery(null, rockContext, dataTimeout, out errorMessages); if (qry != null) { resultSet = qry.AsNoTracking().ToList(); } } catch (Exception exception) { ExceptionLogService.LogException(exception, HttpContext.Current); while (exception != null) { if (exception is SqlException && (exception as SqlException).Number == -2) { // if there was a SQL Server Timeout, have the warning be a friendly message about that. errorMessages.Add("This dataview did not complete in a timely manner. You can try again or adjust the timeout setting of this block."); exception = exception.InnerException; } else { errorMessages.Add(exception.Message); exception = exception.InnerException; } return; } } var recipients = new List <RecipientData>(); if (resultSet.Any()) { foreach (Person person in resultSet) { var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("Person", person); recipients.Add(new RecipientData(person.Email, mergeFields)); } } var appRoot = GlobalAttributesCache.Read(rockContext).GetValue("ExternalApplicationRoot"); Email.Send((Guid)emailTemplateGuid, recipients, appRoot); context.Result = string.Format("{0} emails sent", recipients.Count()); } }
/// <summary> /// Job that updates the JobPulse setting with the current date/time. /// This will allow us to notify an admin if the jobs stop running. /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute(IJobExecutionContext context) { var globalAttributesCache = GlobalAttributesCache.Read(); globalAttributesCache.SetValue("JobPulse", RockDateTime.Now.ToString(), true); UpdateScheduledJobs(context); }
/// <summary> /// Job that updates the JobPulse setting with the current date/time. /// This will allow us to notify an admin if the jobs stop running. /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute(IJobExecutionContext context) { var globalAttributesCache = GlobalAttributesCache.Read(); // Update a JobPulse global attribute value so that 3rd Party plugins could query this value in case they need to know globalAttributesCache.SetValue("JobPulse", RockDateTime.Now.ToString(), true); UpdateScheduledJobs(context); }
/// <summary> /// Sends statistics to the SDN server but only if there are more than 100 person records /// or the sample data has not been loaded. /// /// The statistics are: /// * Rock Instance Id /// * Update Version /// * IP Address - The IP address of your Rock server. /// /// ...and we only send these if they checked the "Include Impact Statistics": /// * Organization Name and Address /// * Public Web Address /// * Number of Active Records /// /// As per http://www.rockrms.com/Rock/Impact /// </summary> /// <param name="version">the semantic version number</param> private void SendStatictics(string version) { try { var rockContext = new RockContext(); int numberOfActiveRecords = new PersonService(rockContext).Queryable(includeDeceased: false, includeBusinesses: false).Count(); if (numberOfActiveRecords > 100 || !Rock.Web.SystemSettings.GetValue(SystemSettingKeys.SAMPLEDATA_DATE).AsDateTime().HasValue) { string organizationName = string.Empty; ImpactLocation organizationLocation = null; string publicUrl = string.Empty; var rockInstanceId = Rock.Web.SystemSettings.GetRockInstanceId(); var ipAddress = Request.ServerVariables["LOCAL_ADDR"]; if (cbIncludeStats.Checked) { var globalAttributes = GlobalAttributesCache.Read(); organizationName = globalAttributes.GetValue("OrganizationName"); publicUrl = globalAttributes.GetValue("PublicApplicationRoot"); // Fetch the organization address var organizationAddressLocationGuid = globalAttributes.GetValue("OrganizationAddress").AsGuid(); if (!organizationAddressLocationGuid.Equals(Guid.Empty)) { var location = new Rock.Model.LocationService(rockContext).Get(organizationAddressLocationGuid); if (location != null) { organizationLocation = new ImpactLocation(location); } } } else { numberOfActiveRecords = 0; } var environmentData = Rock.Web.Utilities.RockUpdateHelper.GetEnvDataAsJson(Request, ResolveRockUrl("~/")); // now send them to SDN/Rock server SendToSpark(rockInstanceId, version, ipAddress, publicUrl, organizationName, organizationLocation, numberOfActiveRecords, environmentData); } } catch (Exception ex) { // Just catch any exceptions, log it, and keep moving... We don't want to mess up the experience // over a few statistics/metrics. try { LogException(ex); } catch { } } }
/// <summary> /// Sends the specified recipients. /// </summary> /// <param name="recipients">The recipients.</param> /// <param name="from">From.</param> /// <param name="subject">The subject.</param> /// <param name="body">The body.</param> /// <param name="appRoot">The application root.</param> /// <param name="themeRoot">The theme root.</param> public override void Send(List <string> recipients, string from, string subject, string body, string appRoot = null, string themeRoot = null) { try { var globalAttributes = GlobalAttributesCache.Read(); if (string.IsNullOrWhiteSpace(from)) { from = globalAttributes.GetValue("OrganizationEmail"); } if (!string.IsNullOrWhiteSpace(from)) { // Resolve any possible merge fields in the from address var globalConfigValues = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(null); from = from.ResolveMergeFields(globalConfigValues); MailMessage message = new MailMessage(); message.From = new MailAddress(from); CheckSafeSender(message, globalAttributes); message.IsBodyHtml = true; message.Priority = MailPriority.Normal; var smtpClient = GetSmtpClient(); message.To.Clear(); recipients.ForEach(r => message.To.Add(r)); if (!string.IsNullOrWhiteSpace(themeRoot)) { subject = subject.Replace("~~/", themeRoot); body = body.Replace("~~/", themeRoot); } if (!string.IsNullOrWhiteSpace(appRoot)) { subject = subject.Replace("~/", appRoot); body = body.Replace("~/", appRoot); body = body.Replace(@" src=""/", @" src=""" + appRoot); body = body.Replace(@" href=""/", @" href=""" + appRoot); } message.Subject = subject; message.Body = body; smtpClient.Send(message); } } catch (Exception ex) { ExceptionLogService.LogException(ex, null); } }
private void SetOrganization(Organization organization) { GlobalAttributesCache globalCache = GlobalAttributesCache.Read(); globalCache.SetValue("StoreOrganizationKey", organization.Key, true); pnlAuthenicate.Visible = false; pnlSelectOrganization.Visible = false; pnlComplete.Visible = true; lCompleteMessage.Text = string.Format("<div class='alert alert-success margin-t-md'><strong>Success!</strong> We were able to configure the store for use by {0}.</div>", organization.Name); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit(System.EventArgs e) { base.OnInit(e); var globalAttributes = GlobalAttributesCache.Read(); if (globalAttributes != null) { this.PrependText = "<i class='fa fa-envelope'></i>"; } }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit(System.EventArgs e) { base.OnInit(e); var globalAttributes = GlobalAttributesCache.Read(); if (globalAttributes != null) { string symbol = globalAttributes.GetValue("CurrencySymbol"); this.PrependText = string.IsNullOrWhiteSpace(symbol) ? "$" : symbol; } }
protected void bntMerge_Click(object sender, EventArgs e) { PDFWorkflowObject pdfWorkflowObject = new PDFWorkflowObject(); pdfWorkflowObject.LavaInput = ceLava.Text; pdfWorkflowObject.MergeObjects = new Dictionary <string, object>(); if (cbCurrentPerson.Checked) { pdfWorkflowObject.MergeObjects.Add("CurrentPerson", CurrentPerson); } if (cbGlobal.Checked) { pdfWorkflowObject.MergeObjects.Add("GlobalAttributes", GlobalAttributesCache.Read()); } Guid workflowTypeGuid = Guid.NewGuid(); if (Guid.TryParse(GetAttributeValue("WorkflowType"), out workflowTypeGuid)) { var workflowRockContext = new RockContext(); var workflowTypeService = new WorkflowTypeService(workflowRockContext); var workflowType = workflowTypeService.Get(workflowTypeGuid); if (workflowType != null) { var workflow = Workflow.Activate(workflowType, "PDFLavaWorkflow"); List <string> workflowErrors; var workflowService = new WorkflowService(workflowRockContext); var workflowActivity = GetAttributeValue("WorkflowActivity"); var activityType = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault(); if (activityType != null) { WorkflowActivity.Activate(activityType, workflow, workflowRockContext); if (workflowService.Process(workflow, pdfWorkflowObject, out workflowErrors)) { //success } } } } RockContext rockContext = new RockContext(); BinaryFileService binaryFileService = new BinaryFileService(rockContext); pdfWorkflowObject.RenderedPDF.FileName = "LavaGeneratedPDF.pdf"; binaryFileService.Add(pdfWorkflowObject.RenderedPDF); rockContext.SaveChanges(); Response.Redirect(pdfWorkflowObject.RenderedPDF.Path); }
/// <summary> /// Returns a user friendly description of the password rules. /// </summary> /// <returns>A user friendly description of the password rules.</returns> public static string FriendlyPasswordRules() { var globalAttributes = GlobalAttributesCache.Read(); string passwordRegex = globalAttributes.GetValue("PasswordRegexFriendlyDescription"); if (string.IsNullOrEmpty(passwordRegex)) { return(""); } else { return(passwordRegex); } }
public Location Get(string street, string city, string state, string postalCode) { string street2 = string.Empty; string country = GlobalAttributesCache.Read().OrganizationCountry; // Get a new location record for the address var location = ((LocationService)Service).Get(street, street2, city, state, postalCode, country); if (location == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return(location); }
/// <summary> /// Checks to see if the given password is valid according to the PasswordRegex (if defined). /// </summary> /// <param name="password">A password to verify.</param> /// <returns>A <see cref="System.Boolean"/> value that indicates if the password is valid. <c>true</c> if valid; otherwise <c>false</c>.</returns> public static bool IsPasswordValid(string password) { var globalAttributes = GlobalAttributesCache.Read(); string passwordRegex = globalAttributes.GetValue("PasswordRegularExpression"); if (string.IsNullOrEmpty(passwordRegex)) { return(true); } else { var regex = new Regex(passwordRegex); return(regex.IsMatch(password)); } }
/// <summary> /// Shows the edit. /// </summary> /// <param name="emailTemplateId">The email template id.</param> protected void ShowEdit(int emailTemplateId) { var globalAttributes = GlobalAttributesCache.Read(); string globalFromName = globalAttributes.GetValue("OrganizationName"); tbFromName.Help = string.Format("If a From Name value is not entered the 'Organization Name' Global Attribute value of '{0}' will be used when this template is sent.", globalFromName); string globalFrom = globalAttributes.GetValue("OrganizationEmail"); tbFrom.Help = string.Format("If a From Address value is not entered the 'Organization Email' Global Attribute value of '{0}' will be used when this template is sent.", globalFrom); tbTo.Help = "You can specify multiple email addresses by separating them with commas or semi-colons."; SystemEmailService emailTemplateService = new SystemEmailService(new RockContext()); SystemEmail emailTemplate = emailTemplateService.Get(emailTemplateId); if (emailTemplate != null) { lActionTitle.Text = ActionTitle.Edit(SystemEmail.FriendlyTypeName).FormatAsHtmlTitle(); hfEmailTemplateId.Value = emailTemplate.Id.ToString(); cpCategory.SetValue(emailTemplate.CategoryId); tbTitle.Text = emailTemplate.Title; tbFromName.Text = emailTemplate.FromName; tbFrom.Text = emailTemplate.From; tbTo.Text = emailTemplate.To; tbCc.Text = emailTemplate.Cc; tbBcc.Text = emailTemplate.Bcc; tbSubject.Text = emailTemplate.Subject; tbBody.Text = emailTemplate.Body; } else { lActionTitle.Text = ActionTitle.Add(SystemEmail.FriendlyTypeName).FormatAsHtmlTitle(); hfEmailTemplateId.Value = 0.ToString(); cpCategory.SetValue((int?)null); tbTitle.Text = string.Empty; tbFromName.Text = string.Empty; tbFrom.Text = string.Empty; tbTo.Text = string.Empty; tbCc.Text = string.Empty; tbBcc.Text = string.Empty; tbSubject.Text = string.Empty; tbBody.Text = string.Empty; } }
/// <summary> /// Validates the type of the file. /// </summary> /// <param name="context">The context.</param> /// <param name="uploadedFile">The uploaded file.</param> /// <exception cref="WebFaultException{System.String}">Filetype not allowed</exception> public virtual void ValidateFileType(HttpContext context, HttpPostedFile uploadedFile) { // validate file type (applies to all uploaded files) var globalAttributesCache = GlobalAttributesCache.Read(); IEnumerable <string> contentFileTypeBlackList = (globalAttributesCache.GetValue("ContentFiletypeBlacklist") ?? string.Empty).Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); // clean up list contentFileTypeBlackList = contentFileTypeBlackList.Select(a => a.ToLower().TrimStart(new char[] { '.', ' ' })); string fileExtension = Path.GetExtension(uploadedFile.FileName).ToLower().TrimStart(new char[] { '.' }); if (contentFileTypeBlackList.Contains(fileExtension)) { throw new Rock.Web.FileUploadException("Filetype not allowed", System.Net.HttpStatusCode.NotAcceptable); } }
/// <summary> /// Gets the javascript for year picker. /// </summary> /// <param name="ypGraduationYear">The yp graduation year.</param> /// <returns></returns> public string GetJavascriptForYearPicker(YearPicker ypGraduationYear) { DateTime gradeTransitionDate = GlobalAttributesCache.Read().GetValue("GradeTransitionDate").AsDateTime() ?? new DateTime(RockDateTime.Now.Year, 6, 1); // add a year if the next graduation mm/dd won't happen until next year int gradeOffsetRefactor = (RockDateTime.Now < gradeTransitionDate) ? 0 : 1; string gradeSelectionScriptFormat = @" $('#{0}').change(function(){{ var selectedGradeOffsetValue = $(this).val(); if ( selectedGradeOffsetValue == '') {{ $('#{1}').val(''); }} else {{ $('#{1}').val( {2} + ( {3} + parseInt( selectedGradeOffsetValue ) ) ); }} }}); $('#{1}').change(function(){{ var selectedYearValue = $(this).val(); if (selectedYearValue == '') {{ $('#{0}').val(''); }} else {{ var gradeOffset = ( parseInt( selectedYearValue ) - {4} ) - {3}; if (gradeOffset >= 0 ) {{ $('#{0}').val(gradeOffset.toString()); // if there is a gap in gradeOffsets (grade is combined), keep trying if we haven't hit an actual offset yet while (!$('#{0}').val() && gradeOffset <= {5}) {{ $('#{0}').val(gradeOffset++); }} }} else {{ $('#{0}').val(''); }} }} }});"; string script = string.Format( gradeSelectionScriptFormat, this.ClientID, // {0} ypGraduationYear.ClientID, // {1} gradeTransitionDate.Year, // {2} gradeOffsetRefactor, // {3} RockDateTime.Now.Year, // {4} this.MaxGradeOffset // {5} ); return(script); }
/// <summary> /// Resolves the merge fields. /// </summary> /// <param name="content">The content.</param> /// <param name="mergeObjects">The merge objects.</param> /// <param name="enabledLavaCommands">The enabled lava commands.</param> /// <param name="encodeStrings">if set to <c>true</c> [encode strings].</param> /// <param name="throwExceptionOnErrors">if set to <c>true</c> [throw exception on errors].</param> /// <returns></returns> public static string ResolveMergeFields(this string content, IDictionary <string, object> mergeObjects, string enabledLavaCommands, bool encodeStrings = false, bool throwExceptionOnErrors = false) { try { if (!content.HasMergeFields()) { return(content ?? string.Empty); } if (GlobalAttributesCache.Read().LavaSupportLevel == Lava.LavaSupportLevel.LegacyWithWarning && mergeObjects.ContainsKey("GlobalAttribute")) { if (hasLegacyGlobalAttributeLavaMergeFields.IsMatch(content)) { Rock.Model.ExceptionLogService.LogException(new Rock.Lava.LegacyLavaSyntaxDetectedException("GlobalAttribute", ""), System.Web.HttpContext.Current); } } Template template = Template.Parse(content); template.Registers.Add("EnabledCommands", enabledLavaCommands); if (encodeStrings) { // if encodeStrings = true, we want any string values to be XML Encoded ( RenderParameters renderParameters = new RenderParameters(); renderParameters.LocalVariables = Hash.FromDictionary(mergeObjects); renderParameters.ValueTypeTransformers = new Dictionary <Type, Func <object, object> >(); renderParameters.ValueTypeTransformers[typeof(string)] = EncodeStringTransformer; return(template.Render(renderParameters)); } else { return(template.Render(Hash.FromDictionary(mergeObjects))); } } catch (Exception ex) { if (throwExceptionOnErrors) { throw; } else { return("Error resolving Lava merge fields: " + ex.Message); } } }