private void GetTemplateData(int templateId, bool loadControl = true) { var template = new CommunicationTemplateService(new RockContext()).Get(templateId); if (template != null) { var mediumData = template.MediumData; if (!mediumData.ContainsKey("Subject")) { mediumData.Add("Subject", template.Subject); } foreach (var dataItem in mediumData) { if (!string.IsNullOrWhiteSpace(dataItem.Value)) { if (MediumData.ContainsKey(dataItem.Key)) { MediumData[dataItem.Key] = dataItem.Value; } else { MediumData.Add(dataItem.Key, dataItem.Value); } } } if (loadControl) { LoadMediumControl(true); } } }
/// <summary> /// Handles the Delete event of the gCommunication control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param> protected void gCommunication_Delete( object sender, Rock.Web.UI.Controls.RowEventArgs e ) { var rockContext = new RockContext(); var service = new CommunicationTemplateService( rockContext ); var template = service.Get( e.RowKeyId ); if ( template != null ) { if ( !template.IsAuthorized( Authorization.EDIT, this.CurrentPerson ) ) { maGridWarning.Show( "You are not authorized to delete this template", ModalAlertType.Information ); return; } string errorMessage; if ( !service.CanDelete( template, out errorMessage ) ) { maGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } service.Delete( template ); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Handles the Copy event of the gCommunicationTemplates control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gCommunicationTemplates_Copy(object sender, RowEventArgs e) { var rockContext = new RockContext(); var service = new CommunicationTemplateService(rockContext); var template = service.Get(e.RowKeyId); if (template != null) { if (!template.IsAuthorized(Authorization.EDIT, this.CurrentPerson)) { maGridWarning.Show("You are not authorized to copy this template", ModalAlertType.Information); return; } var templateCopy = template.Clone(false); templateCopy.Id = 0; int copyNumber = 0; var copyName = "Copy of " + template.Name; while (service.Queryable().Where(a => a.Name == copyName).Any()) { copyNumber++; copyName = string.Format("Copy({0}) of {1}", copyNumber, template.Name); } template.Name = copyName.Truncate(100); templateCopy.Guid = Guid.NewGuid(); service.Add(templateCopy); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Handles the Delete event of the gCommunicationTemplates control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param> protected void gCommunicationTemplates_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); var service = new CommunicationTemplateService(rockContext); var template = service.Get(e.RowKeyId); if (template != null) { if (!template.IsAuthorized(Authorization.EDIT, CurrentPerson)) { maGridWarning.Show("You are not authorized to delete this template", ModalAlertType.Information); return; } string errorMessage; if (!service.CanDelete(template, out errorMessage)) { maGridWarning.Show(errorMessage, ModalAlertType.Information); return; } service.Delete(template); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Handles the Copy event of the gCommunicationTemplates control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gCommunicationTemplates_Copy(object sender, RowEventArgs e) { var rockContext = new RockContext(); var service = new CommunicationTemplateService(rockContext); var template = service.Get(e.RowKeyId); if (template != null) { var templateCopy = template.Clone(false); templateCopy.Id = 0; int copyNumber = 0; var copyName = "Copy of " + template.Name; while (service.Queryable().Any(a => a.Name == copyName)) { copyNumber++; copyName = string.Format("Copy({0}) of {1}", copyNumber, template.Name); } templateCopy.Name = copyName.Truncate(100); templateCopy.IsSystem = false; templateCopy.Guid = Guid.NewGuid(); service.Add(templateCopy); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Binds the template picker. /// </summary> /// <returns><c>true</c> if any templates were displayed.</returns> private bool BindTemplatePicker() { var rockContext = new RockContext(); var templateQuery = new CommunicationTemplateService(rockContext) .Queryable() .AsNoTracking() .Where(a => a.IsActive); int?categoryId = cpCommunicationTemplate.SelectedValue.AsIntegerOrNull(); if (categoryId.HasValue && categoryId > 0) { templateQuery = templateQuery.Where(a => a.CategoryId == categoryId); } templateQuery = templateQuery.OrderBy(a => a.Name); // get list of push templates that the current user is authorized to View IEnumerable <CommunicationTemplate> templateList = templateQuery.AsNoTracking() .ToList() .Where(a => a.IsAuthorized(Rock.Security.Authorization.VIEW, this.CurrentPerson)) .Where(a => a.PushMessage.IsNotNullOrWhiteSpace()) .ToList(); rptSelectTemplate.DataSource = templateList; rptSelectTemplate.DataBind(); return(templateList.Any()); }
/// <summary> /// Gets the edit value as the IEntity.Id /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public int?GetEditValueAsEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues) { var guid = GetEditValue(control, configurationValues).AsGuid(); var item = new CommunicationTemplateService(new RockContext()).Get(guid); return(item != null ? item.Id : ( int? )null); }
/// <summary> /// Sets the edit value from IEntity.Id value /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="id">The identifier.</param> public void SetEditValueFromEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues, int?id) { var item = new CommunicationTemplateService(new RockContext()).Get(id ?? 0); var guidValue = item != null?item.Guid.ToString() : string.Empty; SetEditValue(control, configurationValues, guidValue); }
public void CheckCommunicationTemplate() { #pragma warning disable 0618 RockContext rockContext = new RockContext(); CommunicationTemplateService communicationTemplateService = new CommunicationTemplateService(rockContext); foreach (CommunicationTemplate communicationTemplate in communicationTemplateService.Queryable().ToList()) { // don't change if modified if (communicationTemplate.ModifiedDateTime != null) { continue; } bool isUpdated = false; communicationTemplate.MediumDataJson = ReplaceUnformatted(communicationTemplate.MediumDataJson, ref isUpdated); communicationTemplate.MediumDataJson = ReplaceUrl(communicationTemplate.MediumDataJson, ref isUpdated); communicationTemplate.MediumDataJson = ReplaceGlobal(communicationTemplate.MediumDataJson, ref isUpdated); communicationTemplate.MediumDataJson = ReplaceDotNotation(communicationTemplate.MediumDataJson, ref isUpdated); communicationTemplate.Subject = ReplaceUnformatted(communicationTemplate.Subject, ref isUpdated); communicationTemplate.Subject = ReplaceUrl(communicationTemplate.Subject, ref isUpdated); communicationTemplate.Subject = ReplaceGlobal(communicationTemplate.Subject, ref isUpdated); communicationTemplate.Subject = ReplaceDotNotation(communicationTemplate.Subject, ref isUpdated); if (isUpdated) { string sql = $"UPDATE [CommunicationTemplate] SET [MediumDataJson] = '{communicationTemplate.MediumDataJson.Replace( "'", "''" )}', [Subject] = '{communicationTemplate.Subject.Replace( "'", "''" )}' WHERE [Guid] = '{communicationTemplate.Guid}';"; _sqlUpdateScripts.Add(sql); } } #pragma warning restore 0618 }
/// <summary> /// Creates the control(s) necessary for prompting user for a new value /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id"></param> /// <returns> /// The control /// </returns> public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id) { var editControl = new RockDropDownList { ID = id }; editControl.Items.Add(new ListItem()); var templates = new CommunicationTemplateService(new RockContext()).Queryable().OrderBy(t => t.Name).Select(a => new { a.Guid, a.Name }); if (templates.Any()) { foreach (var template in templates) { editControl.Items.Add(new ListItem(template.Name, template.Guid.ToString())); } return(editControl); } return(null); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if (Page.IsValid) { var rockContext = new RockContext(); var service = new CommunicationTemplateService(rockContext); Rock.Model.CommunicationTemplate template = null; if (CommunicationTemplateId.HasValue) { template = service.Get(CommunicationTemplateId.Value); } bool newTemplate = false; if (template == null) { newTemplate = true; template = new Rock.Model.CommunicationTemplate(); service.Add(template); } template.Name = tbName.Text; template.Description = tbDescription.Text; template.MediumEntityTypeId = MediumEntityTypeId; template.MediumData.Clear(); GetMediumData(); foreach (var keyVal in MediumData) { if (!string.IsNullOrEmpty(keyVal.Value)) { template.MediumData.Add(keyVal.Key, keyVal.Value); } } if (template.MediumData.ContainsKey("Subject")) { template.Subject = template.MediumData["Subject"]; template.MediumData.Remove("Subject"); } else { template.Subject = string.Empty; } if (template != null) { rockContext.SaveChanges(); NavigateToParentPage(); } if (newTemplate && !_canEdit) { template.MakePrivate(Authorization.VIEW, CurrentPerson); template.MakePrivate(Authorization.EDIT, CurrentPerson); } } }
private void BindGrid() { var communications = new CommunicationTemplateService(new RockContext()) .Queryable("MediumEntityType,CreatedByPersonAlias.Person"); Guid entityTypeGuid = Guid.Empty; if (Guid.TryParse(rFilter.GetUserPreference("Medium"), out entityTypeGuid)) { communications = communications .Where(c => c.MediumEntityType != null && c.MediumEntityType.Guid.Equals(entityTypeGuid)); } if (_canEdit) { int personId = 0; if (int.TryParse(rFilter.GetUserPreference("Created By"), out personId) && personId != 0) { communications = communications .Where(c => c.CreatedByPersonAlias != null && c.CreatedByPersonAlias.PersonId == personId); } } var sortProperty = gCommunication.SortProperty; if (sortProperty != null) { communications = communications.Sort(sortProperty); } else { communications = communications.OrderBy(c => c.Name); } var viewableCommunications = new List <CommunicationTemplate>(); if (_canEdit) { viewableCommunications = communications.ToList(); } else { foreach (var comm in communications) { if (comm.IsAuthorized(Authorization.EDIT, CurrentPerson)) { viewableCommunications.Add(comm); } } } gCommunication.DataSource = viewableCommunications; gCommunication.DataBind(); }
/// <summary> /// Creates the control(s) neccessary for prompting user for a new value /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id"></param> /// <returns> /// The control /// </returns> public override Control EditControl( Dictionary<string, ConfigurationValue> configurationValues, string id ) { var editControl = new RockDropDownList { ID = id }; var templates = new CommunicationTemplateService( new RockContext() ).Queryable().OrderBy( t => t.Name ); if ( templates.Any() ) { foreach ( var template in templates ) { editControl.Items.Add( new ListItem( template.Name, template.Guid.ToString() ) ); } return editControl; } return null; }
/// <summary> /// Shows the detail. /// </summary> /// <param name="itemKey">The item key.</param> /// <param name="itemKeyValue">The item key value.</param> private void ShowDetail(string itemKey, int itemKeyValue) { if (!itemKey.Equals("TemplateId")) { return; } Rock.Model.CommunicationTemplate template = null; if (!itemKeyValue.Equals(0)) { template = new CommunicationTemplateService(new RockContext()) .Queryable() .Where(c => c.Id == itemKeyValue) .FirstOrDefault(); if (template != null) { lTitle.Text = template.Name.FormatAsHtmlTitle(); } } else { template = new Rock.Model.CommunicationTemplate(); RockPage.PageTitle = "New Communication Template"; lTitle.Text = "New Communication Template".FormatAsHtmlTitle(); } if (template == null) { return; } CommunicationTemplateId = template.Id; tbName.Text = template.Name; tbDescription.Text = template.Description; ChannelEntityTypeId = template.ChannelEntityTypeId; BindChannels(); ChannelData = template.ChannelData; ChannelData.Add("Subject", template.Subject); ChannelControl control = LoadChannelControl(true); }
/// <summary> /// Gets the template data. /// </summary> /// <exception cref="System.Exception">Missing communication template configuration.</exception> private bool GetTemplateData() { if (string.IsNullOrWhiteSpace(GetAttributeValue("PhotoRequestTemplate"))) { nbError.Title = "Configuration Error"; nbError.Text = "Missing communication template configuration."; nbError.Visible = true; return(false); } var template = new CommunicationTemplateService(new RockContext()).Get(GetAttributeValue("PhotoRequestTemplate").AsGuid()); if (template == null) { nbError.Title = "Configuration Error"; nbError.Text = "The communication template appears to be missing."; nbError.Visible = true; return(false); } var mediumData = template.MediumData; if (!mediumData.ContainsKey("Subject")) { mediumData.Add("Subject", template.Subject); } foreach (var dataItem in mediumData) { if (!string.IsNullOrWhiteSpace(dataItem.Value)) { if (MediumData.ContainsKey(dataItem.Key)) { MediumData[dataItem.Key] = dataItem.Value; } else { MediumData.Add(dataItem.Key, dataItem.Value); } } } return(true); }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed) { string formattedValue = value; System.Guid?guid = value.AsGuidOrNull(); if (guid.HasValue) { using (var rockContext = new RockContext()) { var communicationTemplateName = new CommunicationTemplateService(rockContext).GetSelect(guid.Value, a => a.Name); if (communicationTemplateName != null) { formattedValue = communicationTemplateName; } } } return(base.FormatValue(parentControl, formattedValue, configurationValues, condensed)); }
/// <summary> /// Populate the drop down list as should be for block configuration. /// </summary> private void PopulateDropDown() { var rockContext = new RockContext(); ddlEmail.Items.Clear(); ddlEmail.Items.Add(new ListItem()); if (GetAttributeValue("CommunicationType") == "System") { ltTitle.Text = "Test System Email"; ddlEmail.Label = "System Email"; var emails = new SystemEmailService(rockContext) .Queryable() .OrderBy(c => c.Category.Name) .ThenBy(c => c.Title); foreach (var email in emails) { ddlEmail.Items.Add(new ListItem(string.Format("{0} > {1}", email.Category.Name, email.Title), email.Guid.ToString())); } } else { ltTitle.Text = "Test Communication Template"; ddlEmail.Label = "Communication Template"; var entityTypeId = EntityTypeCache.Read("Rock.Communication.Medium.Email").Id; var emails = new CommunicationTemplateService(rockContext) .Queryable() .Where(c => c.MediumEntityTypeId == entityTypeId) .OrderBy(c => c.Name); foreach (var email in emails) { ddlEmail.Items.Add(new ListItem(email.Name, email.Guid.ToString())); } } }
/// <summary> /// Returns breadcrumbs specific to the block that should be added to navigation /// based on the current page reference. This function is called during the page's /// oninit to load any initial breadcrumbs. /// </summary> /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param> /// <returns> /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>. /// </returns> public override List <Rock.Web.UI.BreadCrumb> GetBreadCrumbs(Rock.Web.PageReference pageReference) { var breadCrumbs = new List <BreadCrumb>(); string pageTitle = "New Template"; int?templateId = PageParameter("TemplateId").AsInteger(false); if (templateId.HasValue) { var template = new CommunicationTemplateService(new RockContext()).Get(templateId.Value); if (template != null) { pageTitle = template.Name; } } breadCrumbs.Add(new BreadCrumb(pageTitle, pageReference)); RockPage.Title = pageTitle; return(breadCrumbs); }
/// <summary> /// Initializes the fields from communication template. /// </summary> /// <param name="communicationTemplateId">The communication template identifier.</param> private void InitializeFieldsFromCommunicationTemplate(int communicationTemplateId) { hfSelectedCommunicationTemplateId.Value = communicationTemplateId.ToString(); var communicationTemplate = new CommunicationTemplateService(new RockContext()).Get(hfSelectedCommunicationTemplateId.Value.AsInteger()); var pushCommunication = new CommunicationDetails { PushData = communicationTemplate.PushData, PushImageBinaryFileId = communicationTemplate.PushImageBinaryFileId, PushMessage = communicationTemplate.PushMessage, PushTitle = communicationTemplate.PushTitle, PushOpenMessage = communicationTemplate.PushOpenMessage, PushOpenAction = communicationTemplate.PushOpenAction }; var pushNotificationControl = phPushControl.Controls[0] as PushNotification; if (pushNotificationControl != null) { pushNotificationControl.SetFromCommunication(pushCommunication); } }
/// <summary> /// Gets the template data. /// </summary> /// <exception cref="System.Exception">Missing communication template configuration.</exception> private Dictionary <string, string> GetTemplateData() { if (string.IsNullOrWhiteSpace(ddlEmail.SelectedValue)) { return(null); } var template = new CommunicationTemplateService(new RockContext()).Get(ddlEmail.SelectedValue.AsGuid()); if (template == null) { return(null); } var mediumData = template.MediumData; var MediumData = new Dictionary <string, string>(); if (!mediumData.ContainsKey("Subject")) { mediumData.Add("Subject", template.Subject); } foreach (var dataItem in mediumData) { if (!string.IsNullOrWhiteSpace(dataItem.Value)) { if (MediumData.ContainsKey(dataItem.Key)) { MediumData[dataItem.Key] = dataItem.Value; } else { MediumData.Add(dataItem.Key, dataItem.Value); } } } return(MediumData); }
/// <summary> /// Gets the template data. /// </summary> /// <exception cref="System.Exception">Missing communication template configuration.</exception> private void GetTemplateData() { if (string.IsNullOrWhiteSpace(GetAttributeValue("PhotoRequestTemplate"))) { throw new Exception("Missing communication template configuration."); } var template = new CommunicationTemplateService(new RockContext()).Get(GetAttributeValue("PhotoRequestTemplate").AsGuid()); if (template != null) { var mediumData = template.MediumData; if (!mediumData.ContainsKey("Subject")) { mediumData.Add("Subject", template.Subject); } foreach (var dataItem in mediumData) { if (!string.IsNullOrWhiteSpace(dataItem.Value)) { if (MediumData.ContainsKey(dataItem.Key)) { MediumData[dataItem.Key] = dataItem.Value; } else { MediumData.Add(dataItem.Key, dataItem.Value); } } } } else { throw new Exception("The communication template appears to be missing."); } }
/// <summary> /// Gets the template data. /// </summary> /// <exception cref="System.Exception">Missing communication template configuration.</exception> private bool GetTemplateData() { if (string.IsNullOrWhiteSpace(GetAttributeValue("PhotoRequestTemplate"))) { nbError.Title = "Configuration Error"; nbError.Text = "Missing communication template configuration."; nbError.Visible = true; return(false); } var template = new CommunicationTemplateService(new RockContext()).Get(GetAttributeValue("PhotoRequestTemplate").AsGuid()); if (template == null) { nbError.Title = "Configuration Error"; nbError.Text = "The communication template appears to be missing."; nbError.Visible = true; return(false); } CommunicationDetails.Copy(template, CommunicationData); return(true); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="templateId">The template identifier.</param> private void ShowDetail(int templateId) { Rock.Model.CommunicationTemplate template = null; if (!templateId.Equals(0)) { template = new CommunicationTemplateService(new RockContext()) .Queryable() .Where(c => c.Id == templateId) .FirstOrDefault(); if (template != null) { lTitle.Text = template.Name.FormatAsHtmlTitle(); } } if (template == null) { template = new Rock.Model.CommunicationTemplate(); RockPage.PageTitle = "New Communication Template"; lTitle.Text = "New Communication Template".FormatAsHtmlTitle(); } CommunicationTemplateId = template.Id; tbName.Text = template.Name; tbDescription.Text = template.Description; MediumEntityTypeId = template.MediumEntityTypeId; BindMediums(); MediumData = template.MediumData; MediumData.Add("Subject", template.Subject); MediumControl control = LoadMediumControl(true); }
private void BindGrid() { var communications = new CommunicationTemplateService( new RockContext() ) .Queryable( "ChannelEntityType,CreatedByPersonAlias.Person" ); Guid entityTypeGuid = Guid.Empty; if ( Guid.TryParse( rFilter.GetUserPreference( "Channel" ), out entityTypeGuid ) ) { communications = communications .Where( c => c.ChannelEntityType != null && c.ChannelEntityType.Guid.Equals( entityTypeGuid ) ); } if ( _canEdit ) { int personId = 0; if ( int.TryParse( rFilter.GetUserPreference( "Created By" ), out personId ) && personId != 0 ) { communications = communications .Where( c => c.CreatedByPersonAlias != null && c.CreatedByPersonAlias.PersonId == personId ); } } var sortProperty = gCommunication.SortProperty; if ( sortProperty != null ) { communications = communications.Sort( sortProperty ); } else { communications = communications.OrderBy( c => c.Name ); } var viewableCommunications = new List<CommunicationTemplate>(); if ( _canEdit ) { viewableCommunications = communications.ToList(); } else { foreach ( var comm in communications ) { if ( comm.IsAuthorized( Authorization.EDIT, CurrentPerson ) ) { viewableCommunications.Add( comm ); } } } gCommunication.DataSource = viewableCommunications; gCommunication.DataBind(); }
private void GetTemplateData(int templateId, bool loadControl = true) { var template = new CommunicationTemplateService( new RockContext() ).Get( templateId ); if ( template != null ) { var channelData = template.ChannelData; if ( !channelData.ContainsKey( "Subject" ) ) { channelData.Add( "Subject", template.Subject ); } foreach ( var dataItem in channelData ) { if ( !string.IsNullOrWhiteSpace( dataItem.Value ) ) { if ( ChannelData.ContainsKey( dataItem.Key ) ) { ChannelData[dataItem.Key] = dataItem.Value; } else { ChannelData.Add( dataItem.Key, dataItem.Value ); } } } if ( loadControl ) { LoadChannelControl( true ); } } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="communication">The communication.</param> private void ShowDetail(Rock.Model.Communication communication) { Recipients.Clear(); if (communication != null) { this.AdditionalMergeFields = communication.AdditionalMergeFields.ToList(); lTitle.Text = ( communication.Subject ?? "New Communication" ).FormatAsHtmlTitle(); foreach(var recipient in new CommunicationRecipientService(new RockContext()) .Queryable("Person.PhoneNumbers") .Where( r => r.CommunicationId == communication.Id)) { Recipients.Add( new Recipient( recipient.Person, recipient.Status, recipient.StatusNote, recipient.OpenedClient, recipient.OpenedDateTime)); } } else { communication = new Rock.Model.Communication() { Status = CommunicationStatus.Transient }; lTitle.Text = "New Communication".FormatAsHtmlTitle(); int? personId = PageParameter( "Person" ).AsInteger( false ); if ( personId.HasValue ) { communication.IsBulkCommunication = false; var person = new PersonService( new RockContext() ).Get( personId.Value ); if ( person != null ) { Recipients.Add( new Recipient( person, CommunicationRecipientStatus.Pending, string.Empty, string.Empty, null ) ); } } } CommunicationId = communication.Id; ChannelEntityTypeId = communication.ChannelEntityTypeId; BindChannels(); ChannelData = communication.ChannelData; ChannelData.Add( "Subject", communication.Subject ); if (communication.Status == CommunicationStatus.Transient && !string.IsNullOrWhiteSpace(GetAttributeValue("DefaultTemplate"))) { var template = new CommunicationTemplateService( new RockContext() ).Get( GetAttributeValue( "DefaultTemplate" ).AsGuid() ); if (template != null && template.ChannelEntityTypeId == ChannelEntityTypeId) { foreach(ListItem item in ddlTemplate.Items) { if (item.Value == template.Id.ToString()) { item.Selected = true; GetTemplateData( template.Id, false ); } else { item.Selected = false; } } } } cbBulk.Checked = communication.IsBulkCommunication; ChannelControl control = LoadChannelControl( true ); if ( control != null && CurrentPerson != null ) { control.InitializeFromSender( CurrentPerson ); } dtpFutureSend.SelectedDateTime = communication.FutureSendDateTime; ShowStatus( communication ); ShowActions( communication ); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="templateId">The template identifier.</param> private void ShowDetail(int templateId) { CommunicationTemplate communicationTemplate = null; var newTemplate = false; if (!templateId.Equals(0)) { communicationTemplate = new CommunicationTemplateService(new RockContext()).Get(templateId); if (communicationTemplate != null) { lTitle.Text = communicationTemplate.Name.FormatAsHtmlTitle(); pdAuditDetails.SetEntity(communicationTemplate, ResolveRockUrl("~")); } } if (communicationTemplate == null) { RockPage.PageTitle = "New Communication Template"; lTitle.Text = "New Communication Template".FormatAsHtmlTitle(); communicationTemplate = new CommunicationTemplate(); newTemplate = true; } LoadDropDowns(); mfpSMSMessage.MergeFields.Clear(); mfpSMSMessage.MergeFields.Add("GlobalAttribute"); mfpSMSMessage.MergeFields.Add("Rock.Model.Person"); hfCommunicationTemplateId.Value = templateId.ToString(); tbName.Text = communicationTemplate.Name; cbIsActive.Checked = communicationTemplate.IsActive; tbDescription.Text = communicationTemplate.Description; cpCategory.SetValue(communicationTemplate.CategoryId); imgTemplatePreview.BinaryFileId = communicationTemplate.ImageFileId; imgTemplateLogo.BinaryFileId = communicationTemplate.LogoBinaryFileId; // Email Fields tbFromName.Text = communicationTemplate.FromName; tbFromAddress.Text = communicationTemplate.FromEmail; tbReplyToAddress.Text = communicationTemplate.ReplyToEmail; tbCCList.Text = communicationTemplate.CCEmails; tbBCCList.Text = communicationTemplate.BCCEmails; cbCssInliningEnabled.Checked = communicationTemplate.CssInliningEnabled; kvlMergeFields.Value = communicationTemplate.LavaFields.Select(a => string.Format("{0}^{1}", a.Key, a.Value)).ToList().AsDelimited("|"); hfShowAdditionalFields.Value = (!string.IsNullOrEmpty(communicationTemplate.ReplyToEmail) || !string.IsNullOrEmpty(communicationTemplate.CCEmails) || !string.IsNullOrEmpty(communicationTemplate.BCCEmails)).ToTrueFalse().ToLower(); tbEmailSubject.Text = communicationTemplate.Subject; nbTemplateHelp.InnerHtml = @" <p>An email template needs to be an html doc with some special divs to support the communication wizard.</p> <br/> <p>The template needs to have at least one div with a 'dropzone' class in the BODY</p> <br/> <pre> <div class=""dropzone""> </div> </pre> <br/> <p>A template also needs to have at least one div with a 'structure-dropzone' class in the BODY to support adding zones</p> <br/> <pre> <div class=""structure-dropzone""> <div class=""dropzone""> </div> </div> </pre> <br/> <p>To have some starter text, include a 'component component-text' div within the 'dropzone' div</p> <br/> <pre> <div class=""structure-dropzone""> <div class=""dropzone""> <div class=""component component-text"" data-content=""<h1>Hello There!</h1>"" data-state=""component""> <h1>Hello There!</h1> </div> </div> </div> </pre> <br/> <p>To enable the PREHEADER text, a div with an id of 'preheader-text' needs to be the first div in the BODY</p> <br/> <pre> <!-- HIDDEN PREHEADER TEXT --> <div id=""preheader-text"" style=""display: none; font-size: 1px; color: #fefefe; line-height: 1px; font-family: Helvetica, Arial, sans-serif; max-height: 0px; max-width: 0px; opacity: 0; overflow: hidden;""> Entice the open with some amazing preheader text. Use a little mystery and get those subscribers to read through... </div> </pre> <p>To include a logo, an img div with an id of 'template-logo' can be placed anywhere in the template, which will then show the 'Logo' image uploader under the template editor which will be used to set the src of the template-logo</p> <br/> <pre> <!-- LOGO --> <img id='template-logo' src='/Content/EmailTemplates/placeholder-logo.png' width='200' height='50' data-instructions='Provide a PNG with a transparent background or JPG with the background color of #ee7725.' /> </pre> <br/> "; ceEmailTemplate.Text = communicationTemplate.Message; hfAttachedBinaryFileIds.Value = communicationTemplate.Attachments.Select(a => a.BinaryFileId).ToList().AsDelimited(","); UpdateAttachedFiles(false); // SMS Fields ddlSMSFrom.SetValue(communicationTemplate.SMSFromDefinedValueId); tbSMSTextMessage.Text = communicationTemplate.SMSMessage; // render UI based on Authorized and IsSystem var readOnly = false; var restrictedEdit = false; if (!newTemplate && !communicationTemplate.IsAuthorized(Authorization.EDIT, CurrentPerson)) { restrictedEdit = true; readOnly = true; nbEditModeMessage.Text = EditModeMessage.NotAuthorizedToEdit(CommunicationTemplate.FriendlyTypeName); nbEditModeMessage.Visible = true; } if (communicationTemplate.IsSystem) { restrictedEdit = true; nbEditModeMessage.Text = EditModeMessage.System(CommunicationTemplate.FriendlyTypeName); nbEditModeMessage.Visible = true; } tbName.ReadOnly = restrictedEdit; cbIsActive.Enabled = !restrictedEdit; tbFromName.ReadOnly = restrictedEdit; tbName.ReadOnly = restrictedEdit; tbFromAddress.ReadOnly = restrictedEdit; tbReplyToAddress.ReadOnly = restrictedEdit; tbCCList.ReadOnly = restrictedEdit; tbBCCList.ReadOnly = restrictedEdit; tbEmailSubject.ReadOnly = restrictedEdit; fupAttachments.Visible = !restrictedEdit; // Allow these to be Editable if they are IsSystem, but not if they don't have EDIT Auth tbDescription.ReadOnly = readOnly; imgTemplatePreview.Enabled = !readOnly; ceEmailTemplate.ReadOnly = readOnly; mfpSMSMessage.Visible = !restrictedEdit; ddlSMSFrom.Enabled = !restrictedEdit; tbSMSTextMessage.ReadOnly = restrictedEdit; ceEmailTemplate.ReadOnly = restrictedEdit; btnSave.Enabled = !readOnly; tglPreviewAdvanced.Checked = true; tglPreviewAdvanced_CheckedChanged(null, null); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } var rockContext = new RockContext(); var communicationTemplateService = new CommunicationTemplateService(rockContext); var communicationTemplateAttachmentService = new CommunicationTemplateAttachmentService(rockContext); var binaryFileService = new BinaryFileService(rockContext); CommunicationTemplate communicationTemplate = null; var communicationTemplateId = hfCommunicationTemplateId.Value.AsIntegerOrNull(); if (communicationTemplateId.HasValue) { communicationTemplate = communicationTemplateService.Get(communicationTemplateId.Value); } var newTemplate = false; if (communicationTemplate == null) { newTemplate = true; communicationTemplate = new CommunicationTemplate(); communicationTemplateService.Add(communicationTemplate); } communicationTemplate.Name = tbName.Text; communicationTemplate.IsActive = cbIsActive.Checked; communicationTemplate.Description = tbDescription.Text; if (communicationTemplate.ImageFileId != imgTemplatePreview.BinaryFileId) { var oldImageTemplatePreview = binaryFileService.Get(communicationTemplate.ImageFileId ?? 0); if (oldImageTemplatePreview != null) { // the old image template preview won't be needed anymore, so make it IsTemporary and have it get cleaned up later oldImageTemplatePreview.IsTemporary = true; } } communicationTemplate.ImageFileId = imgTemplatePreview.BinaryFileId; // Ensure that the ImagePreview is not set as IsTemporary=True if (communicationTemplate.ImageFileId.HasValue) { var imageTemplatePreview = binaryFileService.Get(communicationTemplate.ImageFileId.Value); if (imageTemplatePreview != null && imageTemplatePreview.IsTemporary) { imageTemplatePreview.IsTemporary = false; } } // Note: If the Logo has changed, we can't get rid of it since existing communications might use it communicationTemplate.LogoBinaryFileId = imgTemplateLogo.BinaryFileId; // Ensure that the ImagePreview is not set as IsTemporary=True if (communicationTemplate.LogoBinaryFileId.HasValue) { var newImageTemplateLogo = binaryFileService.Get(communicationTemplate.LogoBinaryFileId.Value); if (newImageTemplateLogo != null && newImageTemplateLogo.IsTemporary) { newImageTemplateLogo.IsTemporary = false; } } communicationTemplate.FromName = tbFromName.Text; communicationTemplate.FromEmail = tbFromAddress.Text; communicationTemplate.ReplyToEmail = tbReplyToAddress.Text; communicationTemplate.CCEmails = tbCCList.Text; communicationTemplate.BCCEmails = tbBCCList.Text; communicationTemplate.LavaFields = kvlMergeFields.Value.AsDictionaryOrNull(); communicationTemplate.CssInliningEnabled = cbCssInliningEnabled.Checked; var binaryFileIds = hfAttachedBinaryFileIds.Value.SplitDelimitedValues().AsIntegerList(); // delete any attachments that are no longer included foreach (var attachment in communicationTemplate.Attachments .Where(a => !binaryFileIds.Contains(a.BinaryFileId)).ToList()) { communicationTemplate.Attachments.Remove(attachment); communicationTemplateAttachmentService.Delete(attachment); } // add any new attachments that were added foreach (var attachmentBinaryFileId in binaryFileIds.Where(a => communicationTemplate.Attachments.All(x => x.BinaryFileId != a))) { communicationTemplate.Attachments.Add(new CommunicationTemplateAttachment { BinaryFileId = attachmentBinaryFileId }); } communicationTemplate.Subject = tbEmailSubject.Text; communicationTemplate.Message = ceEmailTemplate.Text; communicationTemplate.SMSFromDefinedValueId = ddlSMSFrom.SelectedValue.AsIntegerOrNull(); communicationTemplate.SMSMessage = tbSMSTextMessage.Text; communicationTemplate.CategoryId = cpCategory.SelectedValueAsInt(); rockContext.SaveChanges(); var personalView = GetAttributeValue("PersonalTemplatesView").AsBoolean(); if (newTemplate) { communicationTemplate = communicationTemplateService.Get(communicationTemplate.Id); if (communicationTemplate != null) { if (personalView) { // If editing personal templates, make the new template is private/personal to current user communicationTemplate.MakePrivate(Authorization.VIEW, CurrentPerson); communicationTemplate.MakePrivate(Authorization.EDIT, CurrentPerson); communicationTemplate.MakePrivate(Authorization.ADMINISTRATE, CurrentPerson); } else { // Otherwise, make sure user can view and edit the new template. if (!communicationTemplate.IsAuthorized(Authorization.VIEW, CurrentPerson)) { communicationTemplate.AllowPerson(Authorization.VIEW, CurrentPerson); } // Make sure user can edit the new template. if (!communicationTemplate.IsAuthorized(Authorization.EDIT, CurrentPerson)) { communicationTemplate.AllowPerson(Authorization.EDIT, CurrentPerson); } } // Always make sure RSR-Admin and Communication Admin can see var groupService = new GroupService(rockContext); var communicationAdministrators = groupService.Get(Rock.SystemGuid.Group.GROUP_COMMUNICATION_ADMINISTRATORS.AsGuid()); if (communicationAdministrators != null) { communicationTemplate.AllowSecurityRole(Authorization.VIEW, communicationAdministrators, rockContext); communicationTemplate.AllowSecurityRole(Authorization.EDIT, communicationAdministrators, rockContext); communicationTemplate.AllowSecurityRole(Authorization.ADMINISTRATE, communicationAdministrators, rockContext); } var rockAdministrators = groupService.Get(Rock.SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid()); if (rockAdministrators != null) { communicationTemplate.AllowSecurityRole(Authorization.VIEW, rockAdministrators, rockContext); communicationTemplate.AllowSecurityRole(Authorization.EDIT, rockAdministrators, rockContext); communicationTemplate.AllowSecurityRole(Authorization.ADMINISTRATE, rockAdministrators, rockContext); } } } NavigateToParentPage(); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); var communications = new CommunicationService(rockContext) .Queryable().AsNoTracking() .Where(c => c.Status != CommunicationStatus.Transient); string subject = tbSubject.Text; if (!string.IsNullOrWhiteSpace(subject)) { communications = communications.Where(c => (string.IsNullOrEmpty(c.Subject) && c.Name.Contains(subject)) || c.Subject.Contains(subject)); } var communicationType = ddlType.SelectedValueAsEnumOrNull <CommunicationType>(); if (communicationType != null) { communications = communications.Where(c => c.CommunicationType == communicationType); } string status = ddlStatus.SelectedValue; if (!string.IsNullOrWhiteSpace(status)) { var communicationStatus = ( CommunicationStatus )System.Enum.Parse(typeof(CommunicationStatus), status); communications = communications.Where(c => c.Status == communicationStatus); } if (canApprove) { if (ppSender.PersonId.HasValue) { communications = communications .Where(c => c.SenderPersonAlias != null && c.SenderPersonAlias.PersonId == ppSender.PersonId.Value); } } else { // If can't approve, only show current person's communications communications = communications .Where(c => c.SenderPersonAlias != null && c.SenderPersonAlias.PersonId == CurrentPersonId); } if (drpCreatedDates.LowerValue.HasValue) { communications = communications.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= drpCreatedDates.LowerValue.Value); } if (drpCreatedDates.UpperValue.HasValue) { DateTime upperDate = drpCreatedDates.UpperValue.Value.Date.AddDays(1); communications = communications.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < upperDate); } if (drpSentDates.LowerValue.HasValue) { communications = communications.Where(a => (a.SendDateTime ?? a.FutureSendDateTime) >= drpSentDates.LowerValue.Value); } if (drpSentDates.UpperValue.HasValue) { DateTime upperDate = drpSentDates.UpperValue.Value.Date.AddDays(1); communications = communications.Where(a => (a.SendDateTime ?? a.FutureSendDateTime) < upperDate); } string content = tbContent.Text; if (!string.IsNullOrWhiteSpace(content)) { communications = communications.Where(c => c.Message.Contains(content) || c.SMSMessage.Contains(content) || c.PushMessage.Contains(content)); } var recipients = new CommunicationRecipientService(rockContext).Queryable(); // We want to limit to only communications that they are authorized to view, but if there are a large number of communications, that could be very slow. // So, since communication security is based on CommunicationTemplate, take a shortcut and just limit based on authorized communication templates var authorizedCommunicationTemplateIds = new CommunicationTemplateService(rockContext).Queryable() .Where(a => communications.Where(x => x.CommunicationTemplateId.HasValue).Select(x => x.CommunicationTemplateId.Value).Distinct().Contains(a.Id)) .ToList().Where(a => a.IsAuthorized(Rock.Security.Authorization.VIEW, this.CurrentPerson)).Select(a => a.Id).ToList(); var queryable = communications.Where(a => a.CommunicationTemplateId == null || authorizedCommunicationTemplateIds.Contains(a.CommunicationTemplateId.Value)) .Select(c => new CommunicationItem { Id = c.Id, CommunicationType = c.CommunicationType, Subject = string.IsNullOrEmpty(c.Subject) ? (string.IsNullOrEmpty(c.PushTitle) ? c.Name : c.PushTitle) : c.Subject, CreatedDateTime = c.CreatedDateTime, SendDateTime = c.SendDateTime ?? c.FutureSendDateTime, SendDateTimePrefix = c.SendDateTime == null && c.FutureSendDateTime != null ? "<span class='label label-info'>Future</span> " : "", Sender = c.SenderPersonAlias != null ? c.SenderPersonAlias.Person : null, ReviewedDateTime = c.ReviewedDateTime, Reviewer = c.ReviewerPersonAlias != null ? c.ReviewerPersonAlias.Person : null, Status = c.Status, Recipients = recipients.Where(r => r.CommunicationId == c.Id).Count(), PendingRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Pending).Count(), CancelledRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Cancelled).Count(), FailedRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Failed).Count(), DeliveredRecipients = recipients.Where(r => r.CommunicationId == c.Id && (r.Status == CommunicationRecipientStatus.Delivered || r.Status == CommunicationRecipientStatus.Opened)).Count(), OpenedRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Opened).Count() }); var sortProperty = gCommunication.SortProperty; if (sortProperty != null) { queryable = queryable.Sort(sortProperty); } else { queryable = queryable.OrderByDescending(c => c.SendDateTime); } gCommunication.EntityTypeId = EntityTypeCache.Get <Rock.Model.Communication>().Id; nbBindError.Text = string.Empty; try { gCommunication.SetLinqDataSource(queryable); gCommunication.DataBind(); } catch (Exception e) { ExceptionLogService.LogException(e); Exception sqlException = e; while (sqlException != null && !(sqlException is System.Data.SqlClient.SqlException)) { sqlException = sqlException.InnerException; } nbBindError.Text = string.Format("<p>An error occurred trying to retrieve the communication history. Please try adjusting your filter settings and try again.</p><p>Error: {0}</p>", sqlException != null ? sqlException.Message : e.Message); gCommunication.DataSource = new List <object>(); gCommunication.DataBind(); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); var communicationTemplateQry = new CommunicationTemplateService(rockContext).Queryable("CreatedByPersonAlias.Person"); var privateCol = gCommunicationTemplates.ColumnsOfType <RockBoundField>().FirstOrDefault(c => c.DataField == "SenderPersonAlias.Person.FullName"); if (privateCol != null) { privateCol.Visible = GetAttributeValue("EnablePersonalTemplates").AsBoolean(); } if (_canFilterCreatedBy) { var personId = rFilter.GetUserPreference("Created By").AsIntegerOrNull(); if (personId.HasValue && personId != 0) { communicationTemplateQry = communicationTemplateQry .Where(c => c.CreatedByPersonAlias != null && c.CreatedByPersonAlias.PersonId == personId.Value); } } var categoryId = rFilter.GetUserPreference("Category").AsIntegerOrNull(); if (categoryId.HasValue && categoryId > 0) { communicationTemplateQry = communicationTemplateQry.Where(a => a.CategoryId.HasValue && a.CategoryId.Value == categoryId.Value); } var activeFilter = rFilter.GetUserPreference("Active"); switch (activeFilter) { case "Active": communicationTemplateQry = communicationTemplateQry.Where(a => a.IsActive); break; case "Inactive": communicationTemplateQry = communicationTemplateQry.Where(a => !a.IsActive); break; } var sortProperty = gCommunicationTemplates.SortProperty; communicationTemplateQry = sortProperty != null?communicationTemplateQry.Sort(sortProperty) : communicationTemplateQry.OrderBy(c => c.Name); _templatesWithCommunications = new HashSet <int>(new CommunicationService(rockContext).Queryable().Where(a => a.CommunicationTemplateId.HasValue).Select(a => a.CommunicationTemplateId.Value).Distinct().ToList()); var personalView = GetAttributeValue("PersonalTemplatesView").AsBoolean(); var viewableCommunications = new List <CommunicationTemplate>(); foreach (var comm in communicationTemplateQry.ToList()) { var isViewable = comm.IsAuthorized(personalView ? Authorization.EDIT : Authorization.VIEW, CurrentPerson); if (isViewable) { viewableCommunications.Add(comm); } } var supports = rFilter.GetUserPreference("Supports"); switch (supports) { case "Email Wizard": viewableCommunications = viewableCommunications.Where(a => a.SupportsEmailWizard()).ToList(); break; case "Simple Email Template": viewableCommunications = viewableCommunications.Where(a => !a.SupportsEmailWizard()).ToList(); break; } gCommunicationTemplates.DataSource = viewableCommunications; gCommunicationTemplates.DataBind(); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); var communications = new CommunicationService(rockContext) .Queryable().AsNoTracking() .Where(c => c.Status != CommunicationStatus.Transient); string subject = tbSubject.Text; if (!string.IsNullOrWhiteSpace(subject)) { communications = communications.Where(c => c.Subject.Contains(subject)); } var communicationType = ddlType.SelectedValueAsEnumOrNull <CommunicationType>(); if (communicationType != null) { communications = communications.Where(c => c.CommunicationType == communicationType); } string status = ddlStatus.SelectedValue; if (!string.IsNullOrWhiteSpace(status)) { var communicationStatus = (CommunicationStatus)System.Enum.Parse(typeof(CommunicationStatus), status); communications = communications.Where(c => c.Status == communicationStatus); } if (canApprove) { if (ppSender.PersonId.HasValue) { communications = communications .Where(c => c.SenderPersonAlias != null && c.SenderPersonAlias.PersonId == ppSender.PersonId.Value); } } else { // If can't approve, only show current person's communications communications = communications .Where(c => c.SenderPersonAlias != null && c.SenderPersonAlias.PersonId == CurrentPersonId); } if (drpDates.LowerValue.HasValue) { communications = communications.Where(a => a.CreatedDateTime >= drpDates.LowerValue.Value); } if (drpDates.UpperValue.HasValue) { DateTime upperDate = drpDates.UpperValue.Value.Date.AddDays(1); communications = communications.Where(a => a.CreatedDateTime < upperDate); } string content = tbContent.Text; if (!string.IsNullOrWhiteSpace(content)) { communications = communications.Where(c => c.Message.Contains(content) || c.SMSMessage.Contains(content) || c.PushMessage.Contains(content)); } var recipients = new CommunicationRecipientService(rockContext).Queryable(); // We want to limit to only communications that they are authorized to view, but if there are a large number of communications, that could be very slow. // So, since communication security is based on CommunicationTemplate, take a shortcut and just limit based on authorized communication templates var authorizedCommunicationTemplateIds = new CommunicationTemplateService(rockContext).Queryable() .Where(a => communications.Where(x => x.CommunicationTemplateId.HasValue).Select(x => x.CommunicationTemplateId.Value).Distinct().Contains(a.Id)) .ToList().Where(a => a.IsAuthorized(Rock.Security.Authorization.VIEW, this.CurrentPerson)).Select(a => a.Id).ToList(); var queryable = communications.Where(a => a.CommunicationTemplateId == null || authorizedCommunicationTemplateIds.Contains(a.CommunicationTemplateId.Value)) .Select(c => new CommunicationItem { Id = c.Id, CommunicationType = c.CommunicationType, Subject = c.Subject, CreatedDateTime = c.CreatedDateTime, Sender = c.SenderPersonAlias != null ? c.SenderPersonAlias.Person : null, ReviewedDateTime = c.ReviewedDateTime, Reviewer = c.ReviewerPersonAlias != null ? c.ReviewerPersonAlias.Person : null, Status = c.Status, Recipients = recipients.Where(r => r.CommunicationId == c.Id).Count(), PendingRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Pending).Count(), CancelledRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Cancelled).Count(), FailedRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Failed).Count(), DeliveredRecipients = recipients.Where(r => r.CommunicationId == c.Id && (r.Status == CommunicationRecipientStatus.Delivered || r.Status == CommunicationRecipientStatus.Opened)).Count(), OpenedRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Opened).Count() }); var sortProperty = gCommunication.SortProperty; if (sortProperty != null) { queryable = queryable.Sort(sortProperty); } else { queryable = queryable.OrderByDescending(c => c.CreatedDateTime); } gCommunication.EntityTypeId = EntityTypeCache.Read <Rock.Model.Communication>().Id; gCommunication.SetLinqDataSource(queryable); gCommunication.DataBind(); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="templateId">The template identifier.</param> private void ShowDetail(int templateId) { CommunicationTemplate communicationTemplate = null; var newTemplate = false; var pushCommunication = new CommunicationDetails(); if (!templateId.Equals(0)) { communicationTemplate = new CommunicationTemplateService(new RockContext()).Get(templateId); if (communicationTemplate != null) { lTitle.Text = communicationTemplate.Name.FormatAsHtmlTitle(); pdAuditDetails.SetEntity(communicationTemplate, ResolveRockUrl("~")); } pushCommunication = new CommunicationDetails { PushData = communicationTemplate.PushData, PushImageBinaryFileId = communicationTemplate.PushImageBinaryFileId, PushMessage = communicationTemplate.PushMessage, PushTitle = communicationTemplate.PushTitle, PushOpenMessage = communicationTemplate.PushOpenMessage, PushOpenAction = communicationTemplate.PushOpenAction }; } if (communicationTemplate == null) { RockPage.PageTitle = "New Communication Template"; lTitle.Text = "New Communication Template".FormatAsHtmlTitle(); communicationTemplate = new CommunicationTemplate(); newTemplate = true; } LoadDropDowns(); mfpSMSMessage.MergeFields.Clear(); mfpSMSMessage.MergeFields.Add("GlobalAttribute"); mfpSMSMessage.MergeFields.Add("Rock.Model.Person"); hfCommunicationTemplateId.Value = templateId.ToString(); tbName.Text = communicationTemplate.Name; cbIsActive.Checked = communicationTemplate.IsActive; tbDescription.Text = communicationTemplate.Description; cpCategory.SetValue(communicationTemplate.CategoryId); imgTemplatePreview.BinaryFileId = communicationTemplate.ImageFileId; imgTemplateLogo.BinaryFileId = communicationTemplate.LogoBinaryFileId; // Email Fields tbFromName.Text = communicationTemplate.FromName; tbFromAddress.Text = communicationTemplate.FromEmail; tbReplyToAddress.Text = communicationTemplate.ReplyToEmail; tbCCList.Text = communicationTemplate.CCEmails; tbBCCList.Text = communicationTemplate.BCCEmails; cbCssInliningEnabled.Checked = communicationTemplate.CssInliningEnabled; kvlMergeFields.Value = communicationTemplate.LavaFields.Select(a => string.Format("{0}^{1}", a.Key, a.Value)).ToList().AsDelimited("|"); hfShowAdditionalFields.Value = (!string.IsNullOrEmpty(communicationTemplate.ReplyToEmail) || !string.IsNullOrEmpty(communicationTemplate.CCEmails) || !string.IsNullOrEmpty(communicationTemplate.BCCEmails)).ToTrueFalse().ToLower(); tbEmailSubject.Text = communicationTemplate.Subject; nbTemplateHelp.InnerHtml = CommunicationTemplateHelper.GetTemplateHelp(true); ceEmailTemplate.Text = communicationTemplate.Message; hfAttachedBinaryFileIds.Value = communicationTemplate.Attachments.Select(a => a.BinaryFileId).ToList().AsDelimited(","); UpdateAttachedFiles(false); // SMS Fields dvpSMSFrom.SetValue(communicationTemplate.SMSFromDefinedValueId); tbSMSTextMessage.Text = communicationTemplate.SMSMessage; // render UI based on Authorized and IsSystem var readOnly = false; var restrictedEdit = false; if (!newTemplate && !communicationTemplate.IsAuthorized(Authorization.EDIT, CurrentPerson)) { restrictedEdit = true; readOnly = true; nbEditModeMessage.Text = EditModeMessage.NotAuthorizedToEdit(CommunicationTemplate.FriendlyTypeName); nbEditModeMessage.Visible = true; } if (communicationTemplate.IsSystem) { restrictedEdit = true; nbEditModeMessage.Text = EditModeMessage.System(CommunicationTemplate.FriendlyTypeName); nbEditModeMessage.Visible = true; } tbName.ReadOnly = restrictedEdit; cbIsActive.Enabled = !restrictedEdit; tbFromName.ReadOnly = restrictedEdit; tbName.ReadOnly = restrictedEdit; tbFromAddress.ReadOnly = restrictedEdit; tbReplyToAddress.ReadOnly = restrictedEdit; tbCCList.ReadOnly = restrictedEdit; tbBCCList.ReadOnly = restrictedEdit; tbEmailSubject.ReadOnly = restrictedEdit; fupAttachments.Visible = !restrictedEdit; fupAttachments.BinaryFileTypeGuid = this.GetAttributeValue(AttributeKey.AttachmentBinaryFileType).AsGuidOrNull() ?? Rock.SystemGuid.BinaryFiletype.DEFAULT.AsGuid(); // Allow these to be Editable if they are IsSystem, but not if they don't have EDIT Auth tbDescription.ReadOnly = readOnly; imgTemplatePreview.Enabled = !readOnly; ceEmailTemplate.ReadOnly = readOnly; mfpSMSMessage.Visible = !restrictedEdit; dvpSMSFrom.Enabled = !restrictedEdit; tbSMSTextMessage.ReadOnly = restrictedEdit; ceEmailTemplate.ReadOnly = restrictedEdit; btnSave.Enabled = !readOnly; tglPreviewAdvanced.Checked = true; var pushNotificationControl = phPushNotification.Controls[0] as PushNotification; if (pushNotificationControl != null) { pushNotificationControl.SetFromCommunication(pushCommunication); } SetEmailMessagePreviewModeEnabled(tglPreviewAdvanced.Checked); }
/// <summary> /// Handles the Click event of the mdSaveTemplate control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void mdSaveTemplate_Click(object sender, EventArgs e) { if (!Page.IsValid || !CommunicationId.HasValue) { return; } using (var rockContext = new RockContext()) { var communication = new CommunicationService(rockContext).Get(CommunicationId.Value); if (communication == null) { return; } var template = new CommunicationTemplate { SenderPersonAliasId = CurrentPersonAliasId, Name = tbTemplateName.Text, CategoryId = cpTemplateCategory.SelectedValue.AsIntegerOrNull(), Description = tbTemplateDescription.Text, Subject = communication.Subject, FromName = communication.FromName, FromEmail = communication.FromEmail, ReplyToEmail = communication.ReplyToEmail, CCEmails = communication.CCEmails, BCCEmails = communication.BCCEmails, Message = "{% raw %}" + communication.Message + "{% endraw %}", MessageMetaData = communication.MessageMetaData, SMSFromDefinedValueId = communication.SMSFromDefinedValueId, SMSMessage = communication.SMSMessage, PushTitle = communication.PushTitle, PushMessage = communication.PushMessage, PushSound = communication.PushSound }; foreach (var attachment in communication.Attachments.ToList()) { var newAttachment = new CommunicationTemplateAttachment { BinaryFileId = attachment.BinaryFileId, CommunicationType = attachment.CommunicationType }; template.Attachments.Add(newAttachment); } var templateService = new CommunicationTemplateService(rockContext); templateService.Add(template); rockContext.SaveChanges(); template = templateService.Get(template.Id); if (template != null) { template.MakePrivate(Authorization.VIEW, CurrentPerson); template.MakePrivate(Authorization.EDIT, CurrentPerson); template.MakePrivate(Authorization.ADMINISTRATE, CurrentPerson); } nbTemplateCreated.Visible = true; } HideDialog(); }
/// <summary> /// Gets the template data. /// </summary> /// <exception cref="System.Exception">Missing communication template configuration.</exception> private bool GetTemplateData() { if ( string.IsNullOrWhiteSpace( GetAttributeValue( "PhotoRequestTemplate" ) ) ) { nbError.Title = "Configuration Error"; nbError.Text = "Missing communication template configuration."; nbError.Visible = true; return false; } var template = new CommunicationTemplateService( new RockContext() ).Get( GetAttributeValue( "PhotoRequestTemplate" ).AsGuid() ); if ( template == null ) { nbError.Title = "Configuration Error"; nbError.Text = "The communication template appears to be missing."; nbError.Visible = true; return false; } var mediumData = template.MediumData; if ( !mediumData.ContainsKey( "Subject" ) ) { mediumData.Add( "Subject", template.Subject ); } foreach ( var dataItem in mediumData ) { if ( !string.IsNullOrWhiteSpace( dataItem.Value ) ) { if ( MediumData.ContainsKey( dataItem.Key ) ) { MediumData[dataItem.Key] = dataItem.Value; } else { MediumData.Add( dataItem.Key, dataItem.Value ); } } } return true; }
/// <summary> /// Shows the detail. /// </summary> /// <param name="communication">The communication.</param> private void ShowDetail(Rock.Model.Communication communication) { Recipients.Clear(); if ( communication != null ) { this.AdditionalMergeFields = communication.AdditionalMergeFields.ToList(); lTitle.Text = ( communication.Subject ?? "New Communication" ).FormatAsHtmlTitle(); var recipientList = new CommunicationRecipientService( new RockContext() ) .Queryable() //.Include() .Where( r => r.CommunicationId == communication.Id ) .Select(a => new { a.PersonAlias.Person, PersonHasSMS = a.PersonAlias.Person.PhoneNumbers.Any( p => p.IsMessagingEnabled ), a.Status, a.StatusNote, a.OpenedClient, a.OpenedDateTime }).ToList(); Recipients = recipientList.Select( recipient => new Recipient( recipient.Person, recipient.PersonHasSMS, recipient.Status, recipient.StatusNote, recipient.OpenedClient, recipient.OpenedDateTime ) ).ToList(); } else { communication = new Rock.Model.Communication() { Status = CommunicationStatus.Transient }; communication.SenderPersonAliasId = CurrentPersonAliasId; lTitle.Text = "New Communication".FormatAsHtmlTitle(); int? personId = PageParameter( "Person" ).AsIntegerOrNull(); if ( personId.HasValue ) { communication.IsBulkCommunication = false; var person = new PersonService( new RockContext() ).Get( personId.Value ); if ( person != null ) { Recipients.Add( new Recipient( person, person.PhoneNumbers.Any(p => p.IsMessagingEnabled), CommunicationRecipientStatus.Pending, string.Empty, string.Empty, null ) ); } } } CommunicationId = communication.Id; MediumEntityTypeId = communication.MediumEntityTypeId; BindMediums(); MediumData = communication.MediumData; MediumData.AddOrReplace( "Subject", communication.Subject ); if (communication.Status == CommunicationStatus.Transient && !string.IsNullOrWhiteSpace(GetAttributeValue("DefaultTemplate"))) { var template = new CommunicationTemplateService( new RockContext() ).Get( GetAttributeValue( "DefaultTemplate" ).AsGuid() ); // If a template guid was passed in, it overrides any default template. string templateGuid = PageParameter( "templateGuid" ); if ( !string.IsNullOrEmpty( templateGuid ) ) { var guid = new Guid( templateGuid ); template = new CommunicationTemplateService( new RockContext() ).Queryable().Where( t => t.Guid == guid ).FirstOrDefault(); } if (template != null && template.MediumEntityTypeId == MediumEntityTypeId) { foreach(ListItem item in ddlTemplate.Items) { if (item.Value == template.Id.ToString()) { item.Selected = true; GetTemplateData( template.Id, false ); } else { item.Selected = false; } } } } cbBulk.Checked = communication.IsBulkCommunication; MediumControl control = LoadMediumControl( true ); InitializeControl( control ); dtpFutureSend.SelectedDateTime = communication.FutureSendDateTime; ShowStatus( communication ); ShowActions( communication ); }
private void GetTemplateData(int templateId, bool loadControl = true) { var template = new CommunicationTemplateService( new RockContext() ).Get( templateId ); if ( template != null ) { var mediumData = template.MediumData; if ( !mediumData.ContainsKey( "Subject" ) ) { mediumData.Add( "Subject", template.Subject ); } foreach ( var dataItem in mediumData ) { // Also check Subject so that empty subject values not set in template are cleared. (Fixes #1393) if ( !string.IsNullOrWhiteSpace( dataItem.Value ) || dataItem.Key == "Subject" ) { if ( MediumData.ContainsKey( dataItem.Key ) ) { MediumData[dataItem.Key] = dataItem.Value; } else { MediumData.Add( dataItem.Key, dataItem.Value ); } } } if ( loadControl ) { LoadMediumControl( true ); } } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { if ( Page.IsValid ) { var rockContext = new RockContext(); var service = new CommunicationTemplateService( rockContext ); Rock.Model.CommunicationTemplate template = null; if ( CommunicationTemplateId.HasValue ) { template = service.Get( CommunicationTemplateId.Value ); } bool newTemplate = false; if ( template == null ) { newTemplate = true; template = new Rock.Model.CommunicationTemplate(); service.Add( template ); } template.Name = tbName.Text; template.Description = tbDescription.Text; template.ChannelEntityTypeId = ChannelEntityTypeId; template.ChannelData.Clear(); GetChannelData(); foreach(var keyVal in ChannelData) { if (!string.IsNullOrEmpty(keyVal.Value)) { template.ChannelData.Add(keyVal.Key, keyVal.Value); } } if ( template.ChannelData.ContainsKey( "Subject" ) ) { template.Subject = template.ChannelData["Subject"]; template.ChannelData.Remove( "Subject" ); } if ( template != null ) { rockContext.SaveChanges(); NavigateToParentPage(); } if ( newTemplate && !_canEdit ) { template.MakePrivate( Authorization.VIEW, CurrentPerson ); template.MakePrivate( Authorization.EDIT, CurrentPerson ); } } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if (Page.IsValid) { var rockContext = new RockContext(); var communicationTemplateService = new CommunicationTemplateService(rockContext); var communicationTemplateAttachmentService = new CommunicationTemplateAttachmentService(rockContext); CommunicationTemplate communicationTemplate = null; int?communicationTemplateId = hfCommunicationTemplateId.Value.AsIntegerOrNull(); if (communicationTemplateId.HasValue) { communicationTemplate = communicationTemplateService.Get(communicationTemplateId.Value); } bool newTemplate = false; if (communicationTemplate == null) { newTemplate = true; communicationTemplate = new Rock.Model.CommunicationTemplate(); communicationTemplateService.Add(communicationTemplate); } communicationTemplate.Name = tbName.Text; communicationTemplate.IsActive = cbIsActive.Checked; communicationTemplate.Description = tbDescription.Text; communicationTemplate.ImageFileId = imgTemplatePreview.BinaryFileId; communicationTemplate.LogoBinaryFileId = imgTemplateLogo.BinaryFileId; communicationTemplate.FromName = tbFromName.Text; communicationTemplate.FromEmail = tbFromAddress.Text; communicationTemplate.ReplyToEmail = tbReplyToAddress.Text; communicationTemplate.CCEmails = tbCCList.Text; communicationTemplate.BCCEmails = tbBCCList.Text; communicationTemplate.LavaFields = kvlMergeFields.Value.AsDictionaryOrNull(); communicationTemplate.CssInliningEnabled = cbCssInliningEnabled.Checked; var binaryFileIds = hfAttachedBinaryFileIds.Value.SplitDelimitedValues().AsIntegerList(); // delete any attachments that are no longer included foreach (var attachment in communicationTemplate.Attachments.Where(a => !binaryFileIds.Contains(a.BinaryFileId)).ToList()) { communicationTemplate.Attachments.Remove(attachment); communicationTemplateAttachmentService.Delete(attachment); } // add any new attachments that were added foreach (var attachmentBinaryFileId in binaryFileIds.Where(a => !communicationTemplate.Attachments.Any(x => x.BinaryFileId == a))) { communicationTemplate.Attachments.Add(new CommunicationTemplateAttachment { BinaryFileId = attachmentBinaryFileId }); } communicationTemplate.Subject = tbEmailSubject.Text; communicationTemplate.Message = ceEmailTemplate.Text; communicationTemplate.SMSFromDefinedValueId = ddlSMSFrom.SelectedValue.AsIntegerOrNull(); communicationTemplate.SMSMessage = tbSMSTextMessage.Text; communicationTemplate.CategoryId = cpCategory.SelectedValueAsInt(); if (communicationTemplate != null) { rockContext.SaveChanges(); NavigateToParentPage(); } if (newTemplate && !IsUserAuthorized(Authorization.EDIT)) { communicationTemplate.MakePrivate(Authorization.VIEW, CurrentPerson); communicationTemplate.MakePrivate(Authorization.EDIT, CurrentPerson); } } }
/// <summary> /// Returns breadcrumbs specific to the block that should be added to navigation /// based on the current page reference. This function is called during the page's /// oninit to load any initial breadcrumbs. /// </summary> /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param> /// <returns> /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>. /// </returns> public override List<Rock.Web.UI.BreadCrumb> GetBreadCrumbs( Rock.Web.PageReference pageReference ) { var breadCrumbs = new List<BreadCrumb>(); string pageTitle = "New Template"; int? templateId = PageParameter( "TemplateId" ).AsIntegerOrNull(); if ( templateId.HasValue ) { var template = new CommunicationTemplateService( new RockContext() ).Get( templateId.Value ); if ( template != null ) { pageTitle = template.Name; } } breadCrumbs.Add( new BreadCrumb( pageTitle, pageReference ) ); RockPage.Title = pageTitle; return breadCrumbs; }
/// <summary> /// Shows the detail. /// </summary> /// <param name="communication">The communication.</param> private void ShowDetail(Rock.Model.Communication communication) { Recipients.Clear(); if (communication != null) { this.AdditionalMergeFields = communication.AdditionalMergeFields.ToList(); lTitle.Text = (communication.Subject ?? "New Communication").FormatAsHtmlTitle(); foreach (var recipient in new CommunicationRecipientService(new RockContext()) .Queryable("PersonAlias.Person.PhoneNumbers") .Where(r => r.CommunicationId == communication.Id)) { Recipients.Add(new Recipient(recipient.PersonAlias.Person, recipient.Status, recipient.StatusNote, recipient.OpenedClient, recipient.OpenedDateTime)); } } else { communication = new Rock.Model.Communication() { Status = CommunicationStatus.Transient }; lTitle.Text = "New Communication".FormatAsHtmlTitle(); int?personId = PageParameter("Person").AsIntegerOrNull(); if (personId.HasValue) { communication.IsBulkCommunication = false; var person = new PersonService(new RockContext()).Get(personId.Value); if (person != null) { Recipients.Add(new Recipient(person, CommunicationRecipientStatus.Pending, string.Empty, string.Empty, null)); } } } CommunicationId = communication.Id; MediumEntityTypeId = communication.MediumEntityTypeId; BindMediums(); MediumData = communication.MediumData; MediumData.Add("Subject", communication.Subject); if (communication.Status == CommunicationStatus.Transient && !string.IsNullOrWhiteSpace(GetAttributeValue("DefaultTemplate"))) { var template = new CommunicationTemplateService(new RockContext()).Get(GetAttributeValue("DefaultTemplate").AsGuid()); // If a template guid was passed in, it overrides any default template. string templateGuid = PageParameter("templateGuid"); if (!string.IsNullOrEmpty(templateGuid)) { var guid = new Guid(templateGuid); template = new CommunicationTemplateService(new RockContext()).Queryable().Where(t => t.Guid == guid).FirstOrDefault(); } if (template != null && template.MediumEntityTypeId == MediumEntityTypeId) { foreach (ListItem item in ddlTemplate.Items) { if (item.Value == template.Id.ToString()) { item.Selected = true; GetTemplateData(template.Id, false); } else { item.Selected = false; } } } } cbBulk.Checked = communication.IsBulkCommunication; MediumControl control = LoadMediumControl(true); if (control != null && CurrentPerson != null) { control.InitializeFromSender(CurrentPerson); } dtpFutureSend.SelectedDateTime = communication.FutureSendDateTime; ShowStatus(communication); ShowActions(communication); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="templateId">The template identifier.</param> private void ShowDetail( int templateId ) { Rock.Model.CommunicationTemplate template = null; if ( !templateId.Equals( 0 ) ) { template = new CommunicationTemplateService( new RockContext() ) .Queryable() .Where( c => c.Id == templateId ) .FirstOrDefault(); if ( template != null ) { lTitle.Text = template.Name.FormatAsHtmlTitle(); } } if (template == null) { template = new Rock.Model.CommunicationTemplate(); RockPage.PageTitle = "New Communication Template"; lTitle.Text = "New Communication Template".FormatAsHtmlTitle(); } CommunicationTemplateId = template.Id; tbName.Text = template.Name; tbDescription.Text = template.Description; ChannelEntityTypeId = template.ChannelEntityTypeId; BindChannels(); ChannelData = template.ChannelData; ChannelData.Add( "Subject", template.Subject ); ChannelControl control = LoadChannelControl( true ); }
/// <summary> /// Gets the template data. /// </summary> /// <exception cref="System.Exception">Missing communication template configuration.</exception> private void GetTemplateData() { if ( string.IsNullOrWhiteSpace( GetAttributeValue( "PhotoRequestTemplate" ) ) ) { throw new Exception( "Missing communication template configuration." ); } var template = new CommunicationTemplateService( new RockContext() ).Get( GetAttributeValue( "PhotoRequestTemplate" ).AsGuid() ); if ( template != null ) { var mediumData = template.MediumData; if ( !mediumData.ContainsKey( "Subject" ) ) { mediumData.Add( "Subject", template.Subject ); } foreach ( var dataItem in mediumData ) { if ( !string.IsNullOrWhiteSpace( dataItem.Value ) ) { if ( MediumData.ContainsKey( dataItem.Key ) ) { MediumData[dataItem.Key] = dataItem.Value; } else { MediumData.Add( dataItem.Key, dataItem.Value ); } } } } else { throw new Exception( "The communication template appears to be missing." ); } }