示例#1
0
        public ActionResult Create(TemplateModel model)
        {
            try {
                using (var session = Raven.GetStore().OpenSession("Configuration")){
                    var existingTemplate = session.Load <CommunicationTemplate>(model.TemplateName);
                    if (existingTemplate != null)
                    {
                        throw new Exception("shouldn't exist");
                    }

                    var communicationTemplate = new CommunicationTemplate
                    {
                        EmailContent = model.EmailContent,
                        SmsContent   = model.SmsContent,
                        TemplateName = model.TemplateName
                    };
                    communicationTemplate.ExtractVariables();
                    session.Store(communicationTemplate, communicationTemplate.TemplateName);
                    session.SaveChanges();
                }
                return(RedirectToAction("Index"));
            } catch {
                return(View());
            }
        }
示例#2
0
文件: Database.cs 项目: lmorisse/Symu
        public void SetCognitiveArchitecture(CommunicationTemplate medium)
        {
            if (medium == null)
            {
                throw new ArgumentNullException(nameof(medium));
            }

            CognitiveArchitecture = new CognitiveArchitecture();
            // Communication
            CognitiveArchitecture.MessageContent.MaximumNumberOfBitsOfBeliefToSend =
                medium.MaximumNumberOfBitsOfBeliefToSend;
            CognitiveArchitecture.MessageContent.MaximumNumberOfBitsOfKnowledgeToSend =
                medium.MaximumNumberOfBitsOfKnowledgeToSend;
            CognitiveArchitecture.MessageContent.MinimumBeliefToSendPerBit =
                medium.MinimumBeliefToSendPerBit;
            CognitiveArchitecture.MessageContent.MinimumKnowledgeToSendPerBit =
                medium.MinimumKnowledgeToSendPerBit;
            CognitiveArchitecture.MessageContent.MinimumNumberOfBitsOfBeliefToSend =
                medium.MinimumNumberOfBitsOfBeliefToSend;
            CognitiveArchitecture.MessageContent.MinimumNumberOfBitsOfKnowledgeToSend =
                medium.MinimumNumberOfBitsOfKnowledgeToSend;
            CognitiveArchitecture.InternalCharacteristics.TimeToLive = medium.TimeToLive;
            // Knowledge
            CognitiveArchitecture.TasksAndPerformance.LearningRate = 1;
            CognitiveArchitecture.InternalCharacteristics.CanLearn = true;
            CognitiveArchitecture.KnowledgeAndBeliefs.HasKnowledge = true;
        }
示例#3
0
        /// <summary>
        ///     The agent have received a message that ask for belief in return
        ///     stochastic Filtering agentKnowledge based on MinimumBitsOfKnowledgeToSend/MaximumBitsOfKnowledgeToSend
        ///     Work with non binary KnowledgeBits
        /// </summary>
        /// <returns>null if he don't have the belief or the right</returns>
        /// <returns>a beliefBits if he has the belief or the right</returns>
        /// <returns>With binary KnowledgeBits it will return a float of 0</returns>
        /// <example>KnowledgeBits[0,1,0.6] and MinimumKnowledgeToSend = 0.8 => KnowledgeBits[0,1,0]</example>
        public Bits FilterBeliefToSendFromKnowledgeId(IAgentId knowledgeId, byte beliefBit,
                                                      CommunicationTemplate medium)
        {
            var beliefId = GetBeliefIdFromKnowledgeId(knowledgeId);

            return(FilterBeliefToSend(beliefId, beliefBit, medium));
        }
示例#4
0
        /// <summary>
        /// Handles the RowDataBound event of the gCommunicationTemplates control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void gCommunicationTemplates_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            Literal lSupports = e.Row.FindControl("lSupports") as Literal;
            CommunicationTemplate communicationTemplate = e.Row.DataItem as CommunicationTemplate;

            if (lSupports != null && communicationTemplate != null)
            {
                StringBuilder html = new StringBuilder();
                if (communicationTemplate.SupportsEmailWizard())
                {
                    html.AppendLine("<span class='label label-success' title='This template contains an email template that supports the new communication wizard'>Email Wizard</span>");
                }
                else if (!string.IsNullOrEmpty(communicationTemplate.Message))
                {
                    html.AppendLine("<span class='label label-default' title='This template does not contain an email template that supports the new communication wizard'>Simple Email Template</span>");
                }

                if (communicationTemplate.Guid == Rock.SystemGuid.Communication.COMMUNICATION_TEMPLATE_BLANK.AsGuid() || communicationTemplate.HasSMSTemplate())
                {
                    html.AppendLine("<span class='label label-success'>SMS</span>");
                }

                lSupports.Text = html.ToString();

                if (_templatesWithCommunications.Contains(communicationTemplate.Id))
                {
                    e.Row.AddCssClass("js-has-communications");
                }
            }
        }
        public void EmailContainsUnevenNumberOfCurlyBracketsRaisesException()
        {
            var communicationTemplate = new CommunicationTemplate();

            communicationTemplate.EmailContent = "<stuff>{var1}}</stuff><p>{var2}</p>";

            Assert.That(() => communicationTemplate.ExtractVariables(),
                        Throws.Exception.With.Message.EqualTo("Odd number of opening and closing brackets in template"));
        }
        public void EmailContainsOutOfOrderOpeningAndClosingBrackets_RaisesException()
        {
            var communicationTemplate = new CommunicationTemplate();

            communicationTemplate.EmailContent = "<stuff>}{var1</stuff><p>{var2}</p>";

            Assert.That(() => communicationTemplate.ExtractVariables(),
                        Throws.Exception.With.Message.EqualTo("Brackets must be open and closed before creating new ones"));
        }
        public void EmailContainsCurlyBracketUsesVariableName()
        {
            var communicationTemplate = new CommunicationTemplate();

            communicationTemplate.EmailContent = "<stuff>{var1}</stuff><p>{var2}</p>";

            communicationTemplate.ExtractVariables();

            Assert.That(communicationTemplate.TemplateVariables[0].VariableName, Is.EqualTo("var1"));
            Assert.That(communicationTemplate.TemplateVariables[1].VariableName, Is.EqualTo("var2"));
            Assert.That(communicationTemplate.TemplateVariables.Count, Is.EqualTo(2));
        }
        public void SmsContainsCurlyBracketUsesVariableName()
        {
            var communicationTemplate = new CommunicationTemplate();

            communicationTemplate.SmsContent = "stuff{var1}stuff{var2}";

            communicationTemplate.ExtractVariables();

            Assert.That(communicationTemplate.TemplateVariables[0].VariableName, Is.EqualTo("var1"));
            Assert.That(communicationTemplate.TemplateVariables[1].VariableName, Is.EqualTo("var2"));
            Assert.That(communicationTemplate.TemplateVariables.Count, Is.EqualTo(2));
        }
示例#9
0
 public ActionResult Delete(CommunicationTemplate template)
 {
     try {
         using (var session = Raven.GetStore().OpenSession("Configuration"))
         {
             var existingTemplate = session.Load <CommunicationTemplate>(template.TemplateName);
             if (existingTemplate == null)
             {
                 throw new Exception("should have a document here...");
             }
             session.Delete(existingTemplate);
             session.SaveChanges();
         }
         return(RedirectToAction("Index"));
     } catch {
         return(View());
     }
 }
示例#10
0
 public ActionResult Edit(string templateName, CommunicationTemplate model)
 {
     try {
         using (var session = Raven.GetStore().OpenSession("Configuration"))
         {
             var existingTemplate = session.Load <CommunicationTemplate>(templateName);
             if (existingTemplate == null)
             {
                 throw new Exception("should have a document here...");
             }
             existingTemplate = model;
             existingTemplate.ExtractVariables();
             session.SaveChanges();
         }
         return(RedirectToAction("Index"));
     } catch {
         return(View());
     }
 }
示例#11
0
文件: Database.cs 项目: lmorisse/Symu
        public Database(GraphMetaNetwork metaNetwork, MainOrganizationModels models, CommunicationTemplate medium,
                        IClassId classId) : base(metaNetwork, classId)
        {
            if (metaNetwork is null)
            {
                throw new ArgumentNullException(nameof(metaNetwork));
            }

            if (models is null)
            {
                throw new ArgumentNullException(nameof(models));
            }

            SetCognitiveArchitecture(medium);
            // There is no random level for database
            _learningModel = new LearningModel(EntityId, models, MetaNetwork.Knowledge, MetaNetwork.ResourceKnowledge,
                                               CognitiveArchitecture, models.Generator, 0);
            _forgettingModel =
                new ForgettingModel(EntityId, MetaNetwork.ResourceKnowledge, CognitiveArchitecture, models, 0);
        }
        /// <summary>
        /// Handles the ItemDataBound event of the rptSelectTemplate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param>
        protected void rptSelectTemplate_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            CommunicationTemplate communicationTemplate = e.Item.DataItem as CommunicationTemplate;

            if (communicationTemplate != null)
            {
                Literal    lTemplateImagePreview = e.Item.FindControl("lTemplateImagePreview") as Literal;
                Literal    lTemplateName         = e.Item.FindControl("lTemplateName") as Literal;
                Literal    lTemplateDescription  = e.Item.FindControl("lTemplateDescription") as Literal;
                LinkButton btnSelectTemplate     = e.Item.FindControl("btnSelectTemplate") as LinkButton;

                if (communicationTemplate.ImageFileId.HasValue)
                {
                    var imageUrl = string.Format("~/GetImage.ashx?id={0}", communicationTemplate.ImageFileId);
                    lTemplateImagePreview.Text = string.Format("<img src='{0}' width='100%'/>", this.ResolveRockUrl(imageUrl));
                }
                else
                {
                    lTemplateImagePreview.Text = string.Format("<img src='{0}'/>", this.ResolveRockUrl("~/Assets/Images/communication-template-default.svg"));
                }

                lTemplateName.Text                = communicationTemplate.Name;
                lTemplateDescription.Text         = communicationTemplate.Description;
                btnSelectTemplate.CommandName     = "CommunicationTemplateId";
                btnSelectTemplate.CommandArgument = communicationTemplate.Id.ToString();

                if (hfSelectedCommunicationTemplateId.Value == communicationTemplate.Id.ToString())
                {
                    btnSelectTemplate.AddCssClass("template-selected");
                }
                else
                {
                    btnSelectTemplate.RemoveCssClass("template-selected");
                }
            }
        }
        /// <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>
&lt;div class=""dropzone""&gt;
&lt;/div&gt;
</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>
&lt;div class=""structure-dropzone""&gt;
    &lt;div class=""dropzone""&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<br/>

<p>To have some starter text, include a 'component component-text' div within the 'dropzone' div</p> 
<br/>
<pre>
&lt;div class=""structure-dropzone""&gt;
    &lt;div class=""dropzone""&gt;
        &lt;div class=""component component-text"" data-content=""&lt;h1&gt;Hello There!&lt;/h1&gt;"" data-state=""component""&gt;
            &lt;h1&gt;Hello There!&lt;/h1&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</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>
&lt;!-- HIDDEN PREHEADER TEXT --&gt;
&lt;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;""&gt;
    Entice the open with some amazing preheader text. Use a little mystery and get those subscribers to read through...
&lt;/div&gt;
</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>
&lt;!-- LOGO --&gt;
&lt;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.' /&gt;
</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();
        }
示例#15
0
        /// <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);
                }
            }
        }
示例#16
0
        /// <summary>
        ///     The agent have received a message that ask for belief in return
        ///     stochastic Filtering agentKnowledge based on MinimumBitsOfKnowledgeToSend/MaximumBitsOfKnowledgeToSend
        ///     Work with non binary KnowledgeBits
        /// </summary>
        /// <returns>null if he don't have the belief or the right</returns>
        /// <returns>a beliefBits if he has the belief or the right</returns>
        /// <returns>With binary KnowledgeBits it will return a float of 0</returns>
        /// <example>KnowledgeBits[0,1,0.6] and MinimumKnowledgeToSend = 0.8 => KnowledgeBits[0,1,0]</example>
        public Bits FilterBeliefToSend(IAgentId beliefId, byte beliefBit, CommunicationTemplate medium)
        {
            if (medium is null)
            {
                throw new ArgumentNullException(nameof(medium));
            }

            // If don't have belief, can't send belief or no belief asked
            if (!_messageContent.CanSendBeliefs || !On)
            {
                return(null);
            }

            // intentionally after Cognitive.MessageContent.CanSendBeliefs test
            if (Beliefs == null)
            {
                throw new NullReferenceException(nameof(Beliefs));
            }

            // If Agent don't have the belief, he can't reply
            if (!BelievesEnough(beliefId, beliefBit,
                                _messageContent.MinimumBeliefToSendPerBit))
            {
                return(null);
            }

            var agentBelief = _actorBeliefNetwork.Edge <ActorBelief>(_agentId, beliefId);

            if (agentBelief is null)
            {
                throw new ArgumentNullException(nameof(agentBelief));
            }

            // Filter the belief to send, via the good communication channel// Filtering via the good channel
            var minBits = Math.Max(_messageContent.MinimumNumberOfBitsOfBeliefToSend,
                                   medium.MinimumNumberOfBitsOfBeliefToSend);
            var maxBits = Math.Min(_messageContent.MaximumNumberOfBitsOfBeliefToSend,
                                   medium.MaximumNumberOfBitsOfBeliefToSend);
            var minKnowledge = Math.Max(_messageContent.MinimumBeliefToSendPerBit,
                                        medium.MinimumBeliefToSendPerBit);

            // Random knowledgeBits to send
            if (minBits > maxBits)
            {
                minBits = maxBits;
            }

            var lengthToSend = DiscreteUniform.SampleToByte(minBits, maxBits);

            if (lengthToSend == 0)
            {
                return(null);
            }

            var beliefIndexToSend = DiscreteUniform.SamplesToByte(lengthToSend, agentBelief.Length - 1);

            // Force the first index of the knowledgeIndex To send to be the knowledgeBit asked by an agent
            beliefIndexToSend[0] = beliefBit;
            var beliefBitsToSend = agentBelief.CloneWrittenBeliefBits(_messageContent.MinimumBeliefToSendPerBit);

            // knowledgeBitsToSend full of 0 except for the random indexes knowledgeIndexToSend
            for (byte i = 0; i < beliefBitsToSend.Length; i++)
            {
                if (!beliefIndexToSend.Contains(i) || Math.Abs(beliefBitsToSend.GetBit(i)) < minKnowledge)
                {
                    beliefBitsToSend.SetBit(i, 0);
                }
            }

            // Check Length of message
            // We don't find always what we were looking for
            return(Math.Abs(beliefBitsToSend.GetSum()) < Tolerance ? null : beliefBitsToSend);
        }
示例#17
0
文件: Database.cs 项目: lmorisse/Symu
 public static Database CreateInstance(GraphMetaNetwork metaNetwork, MainOrganizationModels models, CommunicationTemplate medium,
                                       IClassId classId)
 {
     return(new Database(metaNetwork, models, medium, classId));
 }
示例#18
0
        /// <summary>
        ///     The agent have received a message that ask for knowledge in return
        ///     stochastic Filtering agentKnowledge based on MinimumBitsOfKnowledgeToSend/MaximumBitsOfKnowledgeToSend
        ///     Work with non binary KnowledgeBits
        /// </summary>
        /// <returns>null if he don't have the knowledge or the right</returns>
        /// <returns>a knowledgeBits if he has the knowledge or the right</returns>
        /// <returns>With binary KnowledgeBits it will return a float of 0</returns>
        /// <example>KnowledgeBits[0,1,0.6] and MinimumKnowledgeToSend = 0.8 => KnowledgeBits[0,1,0]</example>
        public Bits FilterKnowledgeToSend(IAgentId knowledgeId, byte knowledgeBit, CommunicationTemplate medium,
                                          ushort step, out byte[] knowledgeIndexToSend)
        {
            knowledgeIndexToSend = null;
            if (medium is null)
            {
                throw new ArgumentNullException(nameof(medium));
            }

            // If can't send knowledge or no knowledge asked
            if (!On || !_messageContent.CanSendKnowledge) //|| Expertise == null)
            {
                return(null);
            }

            if (!KnowsEnough(knowledgeId, knowledgeBit,
                             _messageContent.MinimumKnowledgeToSendPerBit, step))
            {
                return(null);
            }

            var agentKnowledge = GetActorKnowledge(knowledgeId);

            if (agentKnowledge is null)
            {
                throw new ArgumentNullException(nameof(agentKnowledge));
            }
            // Filter the Knowledge to send, via the good communication medium

            knowledgeIndexToSend = null;
            // Filtering via the good channel
            var minBits = Math.Max(_messageContent.MinimumNumberOfBitsOfKnowledgeToSend,
                                   medium.MinimumNumberOfBitsOfKnowledgeToSend);
            var maxBits = Math.Min(_messageContent.MaximumNumberOfBitsOfKnowledgeToSend,
                                   medium.MaximumNumberOfBitsOfKnowledgeToSend);
            var minKnowledge = Math.Max(_messageContent.MinimumKnowledgeToSendPerBit,
                                        medium.MinimumKnowledgeToSendPerBit);
            // Random knowledgeBits to send
            var lengthToSend = DiscreteUniform.SampleToByte(Math.Min(minBits, maxBits), Math.Max(minBits, maxBits));

            if (lengthToSend == 0)
            {
                return(null);
            }

            knowledgeIndexToSend = DiscreteUniform.SamplesToByte(lengthToSend, agentKnowledge.Length - 1);
            // Force the first index of the knowledgeIndex To send to be the knowledgeBit asked by an agent
            knowledgeIndexToSend[0] = knowledgeBit;
            var knowledgeBitsToSend = Bits.Initialize(agentKnowledge.Length, 0F);

            for (byte i = 0; i < knowledgeIndexToSend.Length; i++)
            {
                var index = knowledgeIndexToSend[i];
                if (agentKnowledge.GetKnowledgeBit(index) >= minKnowledge)
                {
                    knowledgeBitsToSend[index] = agentKnowledge.GetKnowledgeBit(index);
                }
            }

            var bitsToSend = new Bits(knowledgeBitsToSend, 0);

            // Check Length of message
            // We don't find always what we were looking for
            return(Math.Abs(bitsToSend.GetSum()) < Tolerance ? null : bitsToSend);
        }
示例#19
0
        /// <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();
        }
示例#20
0
        /// <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);
        }