protected override void OnDisplaying(Enumeration element, ElementDisplayingContext context)
        {
            var typeName    = element.GetType().Name;
            var displayType = context.DisplayType;
            var tokenData   = context.GetTokenData();

            // Allow the initially selected value to be tokenized.
            // If a value was posted, use that value instead (without tokenizing it).
            if (element.PostedValue == null)
            {
                var defaultValue = _tokenizer.Replace(element.DefaultValue, tokenData, new ReplaceOptions {
                    Encoding = ReplaceOptions.NoEncode
                });
                element.RuntimeValue = defaultValue;
            }

            context.ElementShape.ProcessedName  = _tokenizer.Replace(element.Name, tokenData);
            context.ElementShape.ProcessedLabel = _tokenizer.Replace(element.Label, tokenData, new ReplaceOptions {
                Encoding = ReplaceOptions.NoEncode
            });
            context.ElementShape.ProcessedOptions = _tokenizer.Replace(element.Options, tokenData, new ReplaceOptions {
                Encoding = ReplaceOptions.NoEncode
            }).ToArray();
            context.ElementShape.Metadata.Alternates.Add(String.Format("Elements_{0}__{1}", typeName, element.InputType));
            context.ElementShape.Metadata.Alternates.Add(String.Format("Elements_{0}_{1}__{2}", typeName, displayType, element.InputType));
        }
 protected override DriverResult Display(PayButtonPart part, string displayType, dynamic shapeHelper)
 {
     if (displayType == "Detail")
     {
         var partSettings = part.Settings.GetModel <PayButtonPartSettings>();
         var tokens       = new Dictionary <string, object> {
             { "Content", part.ContentItem }
         };
         dynamic ci      = part.ContentItem;
         var     payment = new PaymentRecord();
         payment.ContentItemId = part.Id;
         payment.Currency      = partSettings.DefaultCurrency;
         if (string.IsNullOrWhiteSpace(partSettings.CurrencyField) == false)
         {
             payment.Currency = _tokenizer.Replace(partSettings.CurrencyField, tokens);
         }
         payment.Amount = Convert.ToDecimal(_tokenizer.Replace(partSettings.AmountField, tokens), CultureInfo.InvariantCulture);
         if (part.ContentItem.Parts.SingleOrDefault(x => x.PartDefinition.Name == "TitlePart") != null)
         {
             payment.Reason = ci.TitlePart.Title;
         }
         var nonce = _paymentService.CreatePaymentNonce(payment);
         return(ContentShape("Parts_PayButton",
                             () => shapeHelper.Parts_PayButton(Nonce: nonce)));
     }
     else
     {
         return(null);
     }
 }
Example #3
0
        public void SendNewsPublicationNotification(NewsItem newItem)
        {
            if (newItem == null)
            {
                throw new ArgumentNullException("new item");
            }
            var account  = _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);
            var customer = newItem.Customer;
            var template = _messageTemplateService.GetMessageTemplateByName("NewPublishing");

            template.Subject = template.GetLocalized(x => x.Subject, newItem.LanguageId);
            template.Body    = template.GetLocalized(x => x.Body, newItem.LanguageId);
            var tokens = new List <Token>();

            _mesageTokenProvider.AddNewPublishingToken(tokens, newItem);
            _mesageTokenProvider.AddStoreTokens(tokens);
            template.Subject = _tokenizer.Replace(template.Subject, tokens, false);
            template.Body    = _tokenizer.Replace(template.Body, tokens, false);
            var email = new QueuedEmail()
            {
                Priority       = 3,
                From           = account.Email,
                FromName       = account.DisplayName,
                To             = customer.Email,
                Subject        = template.Subject,
                Body           = template.Body,
                CreatedOnUtc   = DateTime.UtcNow,
                EmailAccountId = account.Id
            };

            _queuedEmailService.InsertQueuedEmail(email);
        }
        private long SendNotification(MessageTemplate messageTemplate,
                                      EmailAccount emailAccount,
                                      IList <Token> tokens,
                                      string email,
                                      string toName)
        {
            var subjectReplaced = _tokenizer.Replace(messageTemplate.Subject, tokens, false);
            var bodyReplaced    = _tokenizer.Replace(messageTemplate.Body, tokens, true);

            var queuedEmail = new QueuedEmail {
                From           = emailAccount.Email,
                FromName       = emailAccount.DisplayName,
                To             = email,
                ToName         = toName,
                Cc             = string.Empty,
                Bcc            = messageTemplate.BccEmailAddresses,
                Subject        = subjectReplaced,
                Body           = bodyReplaced,
                SendPriority   = Priority.Medium,
                EmailAccountId = emailAccount.Id
            };

            _queuedEmailService.Save(queuedEmail);

            return(queuedEmail.Id);
        }
Example #5
0
        public List <EventViewModel> GetEventList(CalendarPart part)
        {
            try {
                string start = _tokenizer.Replace(part.StartDate, new Dictionary <string, object>());

                if (!String.IsNullOrEmpty(start))
                {
                    int duration = 1; //Valore standard da usare se la conversione fallisce
                    int.TryParse(_tokenizer.Replace(part.NumDays, new Dictionary <string, object>()), out duration);
                    if (duration <= 0)
                    {
                        duration = 1;
                    }

                    DateTime startDate = Convert.ToDateTime(start, _cultureInfo.Value);
                    return(GetEvents(part.QueryPartRecord.Id, startDate, startDate.AddDays(duration - 1), part));
                }
                else
                {
                    return(null);
                }
            }
            catch {
                return(null);
            }
        }
 protected override void OnDisplaying(Button element, ElementDisplayingContext context)
 {
     context.ElementShape.ProcessedName = _tokenizer.Replace(element.Name, context.GetTokenData());
     context.ElementShape.ProcessedText = _tokenizer.Replace(element.Text, context.GetTokenData(), new ReplaceOptions {
         Encoding = ReplaceOptions.NoEncode
     });
 }
Example #7
0
        public void SendCampaign(Campaign campaign, EmailAccount emailAccount, string email)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException("emailAccount");
            }

            var tokens = new List <Token>();

            _messageTokenProvider.AddStoreTokens(tokens, _storeContext.CurrentStore, emailAccount);
            var customer = _customerService.GetCustomerByEmail(email);

            if (customer != null)
            {
                _messageTokenProvider.AddCustomerTokens(tokens, customer);
            }

            string subject = _tokenizer.Replace(campaign.Subject, tokens, false);
            string body    = _tokenizer.Replace(campaign.Body, tokens, true);

            _emailSender.SendEmail(emailAccount, subject, body, emailAccount.Email, emailAccount.DisplayName, email, null);
        }
Example #8
0
        private int SendNotification(MessageTemplate messageTemplate,
                                     EmailAccount emailAccount, int languageId, IEnumerable <Token> tokens,
                                     string toEmailAddress, string toName)
        {
            //retrieve localized message template data
            var bcc     = messageTemplate.GetLocalized((mt) => mt.BccEmailAddresses, languageId);
            var subject = messageTemplate.GetLocalized((mt) => mt.Subject, languageId);
            var body    = messageTemplate.GetLocalized((mt) => mt.Body, languageId);

            //Replace subject and body tokens
            var subjectReplaced = _tokenizer.Replace(subject, tokens, false);
            var bodyReplaced    = _tokenizer.Replace(body, tokens, false);

            var email = new QueuedEmail()
            {
                Priority       = QueuedEmailPriority.High,
                From           = emailAccount.Email,
                FromName       = emailAccount.DisplayName,
                To             = toEmailAddress,
                ToName         = toName,
                CC             = string.Empty,
                Bcc            = bcc,
                Subject        = subjectReplaced,
                Body           = bodyReplaced,
                CreatedOnUtc   = DateTime.UtcNow,
                EmailAccountId = emailAccount.Id
            };

            _queuedEmailService.InsertQueuedEmail(email);
            return(email.Id);
        }
Example #9
0
        private IEnumerable <SelectListItem> GetOptions(Query element, int?queryId)
        {
            var optionLabel = element.OptionLabel;

            if (!String.IsNullOrWhiteSpace(optionLabel))
            {
                yield return(new SelectListItem {
                    Text = optionLabel
                });
            }

            if (queryId == null)
            {
                yield break;
            }


            var contentItems    = _projectionManager.GetContentItems(queryId.Value).ToArray();
            var valueExpression = !String.IsNullOrWhiteSpace(element.ValueExpression) ? element.ValueExpression : "{Content.Id}";
            var textExpression  = !String.IsNullOrWhiteSpace(element.TextExpression) ? element.TextExpression : "{Content.DisplayText}";

            foreach (var contentItem in contentItems)
            {
                var data  = new { Content = contentItem };
                var value = _tokenizer.Replace(valueExpression, data);
                var text  = _tokenizer.Replace(textExpression, data);

                yield return(new SelectListItem {
                    Text = text,
                    Value = value
                });
            }
        }
Example #10
0
 protected override void OnDisplaying(PasswordField element, ElementDisplayingContext context)
 {
     context.ElementShape.ProcessedName  = _tokenizer.Replace(element.Name, context.GetTokenData());
     context.ElementShape.ProcessedLabel = _tokenizer.Replace(element.Label, context.GetTokenData(), new ReplaceOptions {
         Encoding = ReplaceOptions.NoEncode
     });
 }
Example #11
0
        public bool TryUpdateSubscription(MailchimpSubscriptionPart part)
        {
            var sub = part.Subscription;

            if (sub.Audience == null || string.IsNullOrWhiteSpace(sub.Audience.Identifier))
            {
                return(false);
            }

            var settings    = part.Settings.GetModel <MailchimpSubscriptionPartSettings>();
            var putPayload  = _tokenizer.Replace(settings.PutPayload, new { Content = part.ContentItem });
            var memberEmail = _tokenizer.Replace(settings.MemberEmail, new { Content = part.ContentItem });

            var syncronized = false;
            var urlTokens   = new Dictionary <string, string> {
                { "{list-id}", sub.Audience.Identifier },
                { "{member-id}", _mailchimpService.ComputeSubscriberHash(memberEmail) }
            };
            string result = "";

            if (sub.Subscribed)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                JObject body = JObject.Parse(putPayload ?? "{}");
                syncronized = TryApiCall(HttpVerbs.Put, CalculateUrlByType(RequestTypes.Member, urlTokens), body, ref result);
            }
            else
            {
                syncronized = TryApiCall(HttpVerbs.Delete, CalculateUrlByType(RequestTypes.Member, urlTokens), null, ref result);
            }

            return(syncronized);
        }
Example #12
0
        public SpamStatus CheckForSpam(SpamFilterPart part)
        {
            var settings = part.TypePartDefinition.Settings.GetModel <SpamFilterPartSettings>();

            // evaluate the text to submit to the spam filters
            var text = _tokenizer.Replace(settings.Pattern, new Dictionary <string, object> {
                { "Content", part.ContentItem }
            });

            var result = CheckForSpam(text, settings.Action);

            // trigger events and rules
            switch (result)
            {
            case SpamStatus.Spam:
                _spamEventHandler.SpamReported(part);
                _rulesManager.TriggerEvent("AntiSpam", "Spam", () => new Dictionary <string, object> {
                    { "Content", part.ContentItem }
                });
                break;

            case SpamStatus.Ham:
                _spamEventHandler.HamReported(part);
                _rulesManager.TriggerEvent("AntiSpam", "Ham", () => new Dictionary <string, object> {
                    { "Content", part.ContentItem }
                });
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(result);
        }
Example #13
0
        public FacebookShopRequestContainer SyncProduct(ContentItem product)
        {
            var productPart = product.As <ProductPart>();

            try {
                var facebookPart = product.As <FacebookShopProductPart>();

                if (productPart != null && facebookPart != null && facebookPart.SynchronizeFacebookShop)
                {
                    var jsonTemplate = facebookPart.Settings.GetModel <FacebookShopProductPartSettings>().JsonForProductUpdate;
                    _fsssp = _workContext.GetContext().CurrentSite.As <FacebookShopSiteSettingsPart>();
                    if (string.IsNullOrWhiteSpace(jsonTemplate))
                    {
                        // Fallback to FacebookShopSiteSettingsPart
                        jsonTemplate = _fsssp.DefaultJsonForProductUpdate;
                    }

                    if (!string.IsNullOrWhiteSpace(jsonTemplate))
                    {
                        // jsonTemplate typically begins with a double '{' and ends with a double '}' (to make tokens work).
                        // For this reason, before deserialization, I need to replace tokens and replace double parenthesis.
                        string jsonBody = _tokenizer.Replace(jsonTemplate, product);
                        jsonBody = jsonBody.Replace("{{", "{").Replace("}}", "}");

                        var jsonContext = FacebookShopProductUpdateRequest.From(jsonBody);

                        CheckCompliance(jsonContext, product);

                        if (jsonContext != null && jsonContext.Valid)
                        {
                            return(SyncProduct(jsonContext));
                        }
                        else if (jsonContext != null)
                        {
                            // I need to tell it was impossible to synchronize the product on Facebook Shop.
                            Logger.Debug(T("Product {0} can't be synchronized on Facebook catalog.", productPart.Sku).Text);
                            Logger.Debug(jsonContext.Message.Text);

                            var returnValue = new FacebookShopRequestContainer();
                            returnValue.Requests.Add(jsonContext);
                            return(returnValue);
                        }
                    }
                }
            } catch (Exception ex) {
                // I need to tell it was impossible to synchronize the product on Facebook Shop.
                if (productPart != null)
                {
                    Logger.Debug(ex, T("Product {0} can't be synchronized on Facebook catalog.", productPart.Sku).Text);
                }
                else
                {
                    Logger.Debug(ex, T("Product part or Facebook part are not valid.").Text);
                }
                return(null);
            }

            return(null);
        }
 protected override void OnDisplaying(TextArea element, ElementDisplayContext context)
 {
     context.ElementShape.ProcessedName  = _tokenizer.Replace(element.Name, context.GetTokenData());
     context.ElementShape.ProcessedLabel = _tokenizer.Replace(element.Label, context.GetTokenData(), new ReplaceOptions {
         Encoding = ReplaceOptions.NoEncode
     });
     context.ElementShape.ProcessedValue = element.RuntimeValue;
 }
Example #15
0
        /// <summary>
        /// Send notification
        /// </summary>
        /// <param name="messageTemplate">Message template</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="languageId">Language identifier</param>
        /// <param name="tokens">Tokens</param>
        /// <param name="toEmailAddress">Recipient email address</param>
        /// <param name="toName">Recipient name</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name</param>
        /// <param name="replyToEmailAddress">"Reply to" email</param>
        /// <param name="replyToName">"Reply to" name</param>
        /// <param name="fromEmail">Sender email. If specified, then it overrides passed "emailAccount" details</param>
        /// <param name="fromName">Sender name. If specified, then it overrides passed "emailAccount" details</param>
        /// <param name="subject">Subject. If specified, then it overrides subject of a message template</param>
        /// <returns>Queued email identifier</returns>
        public virtual int SendNotification(MessageTemplate messageTemplate,
                                            EmailAccount emailAccount, int languageId, IEnumerable <Token> tokens,
                                            string toEmailAddress, string toName,
                                            string attachmentFilePath  = null, string attachmentFileName = null,
                                            string replyToEmailAddress = null, string replyToName        = null,
                                            string fromEmail           = null, string fromName = null, string subject = null)
        {
            if (messageTemplate == null)
            {
                throw new ArgumentNullException(nameof(messageTemplate));
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException(nameof(emailAccount));
            }

            //retrieve localized message template data
            var bcc = _localizationService.GetLocalized(messageTemplate, mt => mt.BccEmailAddresses, languageId);

            if (string.IsNullOrEmpty(subject))
            {
                subject = _localizationService.GetLocalized(messageTemplate, mt => mt.Subject, languageId);
            }
            var body = _localizationService.GetLocalized(messageTemplate, mt => mt.Body, languageId);

            //Replace subject and body tokens
            var subjectReplaced = _tokenizer.Replace(subject, tokens, false);
            var bodyReplaced    = _tokenizer.Replace(body, tokens, true);

            //limit name length
            toName = CommonHelper.EnsureMaximumLength(toName, 300);

            var email = new QueuedEmail
            {
                Priority              = QueuedEmailPriority.High,
                From                  = !string.IsNullOrEmpty(fromEmail) ? fromEmail : emailAccount.Email,
                FromName              = !string.IsNullOrEmpty(fromName) ? fromName : emailAccount.DisplayName,
                To                    = toEmailAddress,
                ToName                = toName,
                ReplyTo               = replyToEmailAddress,
                ReplyToName           = replyToName,
                CC                    = string.Empty,
                Bcc                   = bcc,
                Subject               = subjectReplaced,
                Body                  = bodyReplaced,
                AttachmentFilePath    = attachmentFilePath,
                AttachmentFileName    = attachmentFileName,
                AttachedDownloadId    = messageTemplate.AttachedDownloadId,
                CreatedOnUtc          = DateTime.UtcNow,
                EmailAccountId        = emailAccount.Id,
                DontSendBeforeDateUtc = !messageTemplate.DelayBeforeSend.HasValue ? null
                    : (DateTime?)(DateTime.UtcNow + TimeSpan.FromHours(messageTemplate.DelayPeriod.ToHours(messageTemplate.DelayBeforeSend.Value)))
            };

            _queuedEmailService.InsertQueuedEmail(email);
            return(email.Id);
        }
        public IHqlQuery GetCombinedContentQuery(int[] queryIds, Dictionary <string, object> tokens = null, string[] contentTypesToFilter = null)
        {
            var availableFilters = DescribeFilters().ToList();

            IEnumerable <ContentItem> contentItems = new List <ContentItem>();
            IHqlQuery contentQuery = null;

            contentQuery = _contentManager.HqlQuery();
            // Siccome sono in una Query Definita dallo User, devo anche filtrare per ContentType "CommunicationContact"
            if (contentTypesToFilter != null)
            {
                contentQuery = contentQuery.ForType(contentTypesToFilter);
            }
            foreach (var queryId in queryIds)
            {
                var queryRecord = _queryRepository.Get(queryId);
                // Per un bug di Orchard non si devono usare i gruppi, quindi prendo solo il primo gruppo
                var group = queryRecord.FilterGroups[0];
                // fatto da HERMES
                if (tokens == null)
                {
                    tokens = new Dictionary <string, object>();
                }
                //FINE
                // iterate over each filter to apply the alterations to the query object
                foreach (var filter in group.Filters)
                {
                    var tokenizedState = _tokenizer.Replace(filter.State, tokens /*new Dictionary<string, object>()*/);
                    var filterContext  = new FilterContext {
                        Query           = contentQuery,
                        State           = FormParametersHelper.ToDynamic(tokenizedState),
                        QueryPartRecord = queryRecord
                    };

                    string category = filter.Category;
                    string type     = filter.Type;

                    // look for the specific filter component
                    var descriptor = availableFilters
                                     .SelectMany(x => x.Descriptors)
                                     .FirstOrDefault(x => x.Category == category && x.Type == type);

                    // ignore unfound descriptors
                    if (descriptor == null)
                    {
                        continue;
                    }

                    // apply alteration
                    descriptor.Filter(filterContext);

                    contentQuery = filterContext.Query;
                }
            }
            // Filtro sullo stato di pubblicato
            contentQuery = contentQuery.ForVersion(VersionOptions.Published);
            return(contentQuery);
        }
Example #17
0
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual async Task <int> SendCampaignAsync(Campaign campaign, EmailAccount emailAccount,
                                                          IEnumerable <NewsLetterSubscription> subscriptions)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException(nameof(campaign));
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException(nameof(emailAccount));
            }

            var totalEmailsSent = 0;

            foreach (var subscription in subscriptions)
            {
                var customer = await _customerService.GetCustomerByEmailAsync(subscription.Email);

                //ignore deleted or inactive customers when sending newsletter campaigns
                if (customer != null && (!customer.Active || customer.Deleted))
                {
                    continue;
                }

                var tokens = new List <Token>();
                await _messageTokenProvider.AddStoreTokensAsync(tokens, await _storeContext.GetCurrentStoreAsync(), emailAccount);

                await _messageTokenProvider.AddNewsLetterSubscriptionTokensAsync(tokens, subscription);

                if (customer != null)
                {
                    await _messageTokenProvider.AddCustomerTokensAsync(tokens, customer);
                }

                var subject = _tokenizer.Replace(campaign.Subject, tokens, false);
                var body    = _tokenizer.Replace(campaign.Body, tokens, true);

                var email = new QueuedEmail
                {
                    Priority              = QueuedEmailPriority.Low,
                    From                  = emailAccount.Email,
                    FromName              = emailAccount.DisplayName,
                    To                    = subscription.Email,
                    Subject               = subject,
                    Body                  = body,
                    CreatedOnUtc          = DateTime.UtcNow,
                    EmailAccountId        = emailAccount.Id,
                    DontSendBeforeDateUtc = campaign.DontSendBeforeDateUtc
                };
                await _queuedEmailService.InsertQueuedEmailAsync(email);

                totalEmailsSent++;
            }

            return(totalEmailsSent);
        }
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual int SendCampaign(Campaign campaign, EmailAccount emailAccount, IEnumerable <NewsLetterSubscription> subscriptions)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException("emailAccount");
            }

            if (subscriptions == null || subscriptions.Count() <= 0)
            {
                return(0);
            }

            int totalEmailsSent = 0;

            var subscriptionData = subscriptions
                                   .Where(x => _storeMappingService.Authorize <Campaign>(campaign, x.StoreId))
                                   .GroupBy(x => x.Email);

            foreach (var group in subscriptionData)
            {
                var subscription = group.First();                       // only one email per email address

                var tokens = new List <Token>();
                _messageTokenProvider.AddStoreTokens(tokens, _storeContext.CurrentStore);
                _messageTokenProvider.AddNewsLetterSubscriptionTokens(tokens, subscription);

                var customer = _customerService.GetCustomerByEmail(subscription.Email);
                if (customer != null)
                {
                    _messageTokenProvider.AddCustomerTokens(tokens, customer);
                }

                string subject = _tokenizer.Replace(campaign.Subject, tokens, false);
                string body    = _tokenizer.Replace(campaign.Body, tokens, true);

                var email = new QueuedEmail()
                {
                    Priority       = 3,
                    From           = emailAccount.Email,
                    FromName       = emailAccount.DisplayName,
                    To             = subscription.Email,
                    Subject        = subject,
                    Body           = body,
                    CreatedOnUtc   = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id
                };

                _queuedEmailService.InsertQueuedEmail(email);
                totalEmailsSent++;
            }
            return(totalEmailsSent);
        }
        public void TestUserTokens()
        {
            var str = _tokenizer.Replace("{User.Name},{User.Email},{User.Id}", new { User = new TestUser {
                                                                                         UserName = "******", Email = "*****@*****.**", Id = 88
                                                                                     } });

            Assert.That(str, Is.EqualTo("Joe,[email protected],88"));
            str = _tokenizer.Replace("{User.Name},{User.Email},{User.Id}", null);
            Assert.That(str, Is.EqualTo("Fake,[email protected],5"));
        }
        public void TestDateTokens()
        {
            var dateTimeLocalization = _container.Resolve <IDateTimeFormatProvider>();
            var culture = CultureInfo.GetCultureInfo(_container.Resolve <IOrchardServices>().WorkContext.CurrentCulture);

            var dateTimeFormat = dateTimeLocalization.ShortDateFormat + " " + dateTimeLocalization.ShortTimeFormat;

            Assert.That(_tokenizer.Replace("{Date}", null), Is.EqualTo(_clock.UtcNow.ToString(dateTimeFormat, culture)));
            Assert.That(_tokenizer.Replace("{Date}", new { Date = new DateTime(1978, 11, 15, 0, 0, 0, DateTimeKind.Utc) }), Is.EqualTo(new DateTime(1978, 11, 15, 0, 0, 0, DateTimeKind.Utc).ToString(dateTimeFormat, culture)));
        }
Example #21
0
        private Template GetTemplateWithTkn(Template messageTemplate, ThresholdInfoDto eventMessage)
        {
            var    tokens  = GenerateTokens(messageTemplate, eventMessage);
            string subject = _tokenizer.Replace(messageTemplate.Subject, tokens, htmlEncode: false);
            string body    = _tokenizer.Replace(messageTemplate.Content, tokens, htmlEncode: true);

            messageTemplate.Subject = subject;
            messageTemplate.Content = body;
            return(messageTemplate);
        }
        /// <summary>
        /// Send SMS notification by message template
        /// </summary>
        /// <param name="messageTemplate">Message template</param>
        /// <param name="tokens">Tokens</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        private async Task SendSmsNotificationAsync(MessageTemplate messageTemplate, IEnumerable <Token> tokens)
        {
            //get plugin settings
            var storeId            = (int?)tokens.FirstOrDefault(token => token.Key == "Store.Id")?.Value;
            var sendinblueSettings = await _settingService.LoadSettingAsync <SendinblueSettings>(storeId ?? 0);

            //ensure SMS notifications enabled
            if (!sendinblueSettings.UseSmsNotifications)
            {
                return;
            }

            //whether to send SMS by the passed message template
            var sendSmsForThisMessageTemplate = await _genericAttributeService
                                                .GetAttributeAsync <bool>(messageTemplate, SendinblueDefaults.UseSmsAttribute);

            if (!sendSmsForThisMessageTemplate)
            {
                return;
            }

            //get text with replaced tokens
            var text = await _genericAttributeService.GetAttributeAsync <string>(messageTemplate, SendinblueDefaults.SmsTextAttribute);

            if (!string.IsNullOrEmpty(text))
            {
                text = _tokenizer.Replace(text, tokens, false);
            }

            //get phone number send to
            var phoneNumberTo = string.Empty;
            var phoneType     = await _genericAttributeService.GetAttributeAsync <int>(messageTemplate, SendinblueDefaults.PhoneTypeAttribute);

            switch (phoneType)
            {
            case 0:
                //merchant phone
                phoneNumberTo = sendinblueSettings.StoreOwnerPhoneNumber;
                break;

            case 1:
                //customer phone
                phoneNumberTo = tokens.FirstOrDefault(token => token.Key == "Customer.PhoneNumber")?.Value?.ToString();
                break;

            case 2:
                //order billing address phone
                phoneNumberTo = tokens.FirstOrDefault(token => token.Key == "Order.BillingPhoneNumber")?.Value?.ToString();
                break;
            }

            //try to send SMS
            await _sendinblueEmailManager.SendSMSAsync(phoneNumberTo, sendinblueSettings.SmsSenderName, text);
        }
Example #23
0
        protected override void OnDisplaying(Enumeration element, ElementDisplayingContext context)
        {
            var typeName    = element.GetType().Name;
            var displayType = context.DisplayType;
            var tokenData   = context.GetTokenData();

            context.ElementShape.ProcessedName    = _tokenizer.Replace(element.Name, tokenData);
            context.ElementShape.ProcessedLabel   = _tokenizer.Replace(element.Label, tokenData);
            context.ElementShape.ProcessedOptions = _tokenizer.Replace(element.Options, tokenData).ToArray();
            context.ElementShape.Metadata.Alternates.Add(String.Format("Elements_{0}__{1}", typeName, element.InputType));
            context.ElementShape.Metadata.Alternates.Add(String.Format("Elements_{0}_{1}__{2}", typeName, displayType, element.InputType));
        }
Example #24
0
        public static void AddTokenizers(dynamic elementShape, ITokenizer tokenizer) {
            var element = (Element)elementShape.Element;
            var content = (ContentItem)elementShape.ContentItem;
            var htmlId = element.HtmlId;
            var htmlClass = element.HtmlClass;
            var htmlStyle = element.HtmlStyle;

            // Provide tokenizer functions.
            elementShape.TokenizeHtmlId = (Func<string>)(() => tokenizer.Replace(htmlId, new { Content = content }));
            elementShape.TokenizeHtmlClass = (Func<string>)(() => tokenizer.Replace(htmlClass, new { Content = content }));
            elementShape.TokenizeHtmlStyle = (Func<string>)(() => tokenizer.Replace(htmlStyle, new { Content = content }));
        }
 private string FillString(string first, string second, Dictionary <string, object> tokens)
 {
     if (!string.IsNullOrEmpty(first))
     {
         return(_tokenizer.Replace(first, tokens));
     }
     if (!string.IsNullOrEmpty(second))
     {
         return(_tokenizer.Replace(second, tokens));
     }
     return(string.Empty);
 }
Example #26
0
        public string GetUrl(Dictionary <string, object> contesto, string externalUrl)
        {
            bool   threatUrlAsString = false;
            string pureCleanString, finalUrl;
            var    tokenizedzedUrl = _tokenizer.Replace(externalUrl, contesto, new ReplaceOptions {
                Encoding = ReplaceOptions.UrlEncode
            });

            pureCleanString = tokenizedzedUrl = tokenizedzedUrl.Replace("+", "%20");

            threatUrlAsString = !tokenizedzedUrl.StartsWith("http");
            if (threatUrlAsString)   // gestisco il caso in cui l'URl dell'externalField sia in realtà una stringa
            {
                tokenizedzedUrl = String.Format("http://{0}/{1}/{2}", _shellSetting.RequestUrlHost ?? "www.fakedomain.com", _shellSetting.RequestUrlPrefix ?? "", tokenizedzedUrl ?? "");
            }
            Uri tokenizedzedUri;

            try {
                tokenizedzedUri = new Uri(tokenizedzedUrl);
            }
            catch {
                // gestisco il caso in cui passo un'url e non i parametri di un'url
                tokenizedzedUrl = _tokenizer.Replace(externalUrl, contesto, new ReplaceOptions {
                    Encoding = ReplaceOptions.NoEncode
                });
                tokenizedzedUri = new Uri(tokenizedzedUrl);
            }
            if (threatUrlAsString)
            {
                finalUrl = pureCleanString.Split('?')[0];
            }
            else
            {
                finalUrl = String.Format("{0}{1}{2}{3}", tokenizedzedUri.Scheme, Uri.SchemeDelimiter, tokenizedzedUri.Authority, tokenizedzedUri.AbsolutePath);
            }
            var queryStringParameters = tokenizedzedUri.Query.Split('&');
            var i = 0;

            foreach (var item in queryStringParameters)
            {
                if (!item.Trim().EndsWith("="))
                {
                    finalUrl += ((i == 0 ? "?" : "&") + item.Replace("?", ""));
                    i++;
                }
            }

            if (finalUrl.Count(f => f == '?') == 1 && finalUrl[finalUrl.Length - 1] == '?')
            {
                finalUrl = finalUrl.TrimEnd('?'); //delete the last ? if there aren t parameter in query string
            }
            return(finalUrl);
        }
Example #27
0
        private string GetStartDate(ContentItem content)
        {
            CalendarPart calendar = content == null ? null : content.As <CalendarPart>();

            if (calendar == null)
            {
                return(null);
            }
            else
            {
                return(_tokenizer.Replace(calendar.StartDate, new Dictionary <string, object>()));
            }
        }
        public static void AddTokenizers(dynamic elementShape, ITokenizer tokenizer)
        {
            var element   = (Element)elementShape.Element;
            var content   = (ContentItem)elementShape.ContentItem;
            var htmlId    = element.HtmlId;
            var htmlClass = element.HtmlClass;
            var htmlStyle = element.HtmlStyle;

            // Provide tokenizer functions.
            elementShape.TokenizeHtmlId    = (Func <string>)(() => tokenizer.Replace(htmlId, new { Content = content }));
            elementShape.TokenizeHtmlClass = (Func <string>)(() => tokenizer.Replace(htmlClass, new { Content = content }));
            elementShape.TokenizeHtmlStyle = (Func <string>)(() => tokenizer.Replace(htmlStyle, new { Content = content }));
        }
Example #29
0
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual int SendCampaign(Campaign campaign, EmailAccount emailAccount,
                                        IEnumerable <NewsLetterSubscription> subscriptions)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException("emailAccount");
            }

            int totalEmailsSent = 0;

            foreach (var subscription in subscriptions)
            {
                var customer = _customerService.GetCustomerByEmail(subscription.Email);
                //ignore deleted or inactive customers when sending newsletter campaigns
                if (customer != null && (!customer.Active || customer.Deleted))
                {
                    continue;
                }

                var tokens = new List <Token>();
                _messageTokenProvider.AddStoreTokens(tokens, _storeContext.CurrentStore, emailAccount);
                _messageTokenProvider.AddNewsLetterSubscriptionTokens(tokens, subscription);
                if (customer != null)
                {
                    _messageTokenProvider.AddCustomerTokens(tokens, customer);
                }

                string subject = _tokenizer.Replace(campaign.Subject, tokens, false);
                string body    = _tokenizer.Replace(campaign.Body, tokens, true);

                var email = new QueuedEmail()
                {
                    Priority       = 3,
                    From           = emailAccount.Email,
                    FromName       = emailAccount.DisplayName,
                    To             = subscription.Email,
                    Subject        = subject,
                    Body           = body,
                    CreatedOnUtc   = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id
                };
                _queuedEmailService.InsertQueuedEmail(email);
                totalEmailsSent++;
            }
            return(totalEmailsSent);
        }
Example #30
0
 public void TestListJoinTokens()
 {
     Assert.That(_tokenizer.Replace("{List.Join:{Content.Id}}", new { List = new List <IContent> {
                                                                          new TestUser {
                                                                              Id = 5
                                                                          }, new TestUser {
                                                                              Id = 10
                                                                          }
                                                                      } }), Is.EqualTo("510"));
 }
Example #31
0
        public void SendMiniSiteActivationEmail(int miniSiteId, int languageId)
        {
            var miniSite = _miniSiteService.GetMiniSiteById(miniSiteId);
            //MiniSiteNew

            var template = _messageTemplateService.GetMessageTemplateByName("MiniSiteNew");

            template.Subject = template.GetLocalized(x => x.Subject, languageId, false, false);
            template.Body    = template.GetLocalized(x => x.Body, languageId, false, false);

            //template
            var tokens = new List <Token>();

            _messageTokenProvider.AddStoreTokens(tokens);
            _messageTokenProvider.AddNewMiniSiteTokens(tokens, miniSite);
            string subject = _tokenizer.Replace(template.Subject, tokens, true);
            string body    = _tokenizer.Replace(template.Body, tokens, true);

            var emailAccount = _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);
            var email        = new QueuedEmail()
            {
                Priority       = 3,
                From           = emailAccount.Email,
                FromName       = emailAccount.DisplayName,
                To             = emailAccount.Email,
                Subject        = subject,
                Body           = body,
                CreatedOnUtc   = DateTime.UtcNow,
                EmailAccountId = emailAccount.Id
            };

            _queuedEmailService.InsertQueuedEmail(email);
        }