public string FormatURI(string nonce, FlowType?flow)
 {
     if (flow == FlowType.App)
     {
         var    urlHelper = _commonsServices.GetUrlHelper();
         string protocol  = "http://";
         if (HttpContext.Current != null && HttpContext.Current.Request.Url.ToString().StartsWith("https"))
         {
             protocol = "https://";
         }
         var sitebase = _workContextAccessor.GetContext().CurrentSite.BaseUrl.Replace("http://", "").Replace("https://", "");
         var site     = "/" + _shellSettings.RequestUrlPrefix + "/NonceAppCamouflage";
         site = protocol + sitebase + site.Replace("//", "/").Replace("//", "/") + string.Format("?n={0}", urlHelper.Encode(nonce));
         return(site);
     }
     else
     {
         return(string.Format(GetFormat(), nonce));
     }
 }
        private Dictionary <string, object> GetSettings(dynamic contentModel, int templateId, MailCommunicationPart part)
        {
            var data = new Dictionary <string, object>();

            var baseUri = new Uri(_orchardServices.WorkContext.CurrentSite.BaseUrl);

            Dictionary <string, object> similViewBag = new Dictionary <string, object>();

            similViewBag.Add("CampaignLink", _communicationService.GetCampaignLink("Email", part));

            string body = _templateService.RitornaParsingTemplate(contentModel, templateId, similViewBag);

            if (!body.StartsWith("Error On Template"))
            {
                string host = string.Format("{0}://{1}{2}",
                                            baseUri.Scheme,
                                            baseUri.Host,
                                            baseUri.Port == 80 ? string.Empty : ":" + baseUri.Port);

                var urlHelper = _commonServices.GetUrlHelper();


                // Add Link [UNSUBSCRIBE]
                string ph_Unsubscribe  = "[UNSUBSCRIBE]";
                string unsubscribe     = T("Click here to stop receiving email for commercial use").Text;
                string linkUnsubscribe = "<a href='" + string.Format("{0}{1}", host, urlHelper.UnsubscribeMailCommunication()) + "'>" + unsubscribe + "</a>";

                if (body.Contains(ph_Unsubscribe))
                {
                    body = body.Replace(ph_Unsubscribe, linkUnsubscribe);
                }
                else
                {
                    body += "<br /><br />" + linkUnsubscribe;
                }

                var    subject  = contentModel.TitlePart.Title;
                var    smtp     = _orchardServices.WorkContext.CurrentSite.As <SmtpSettingsPart>();
                string priority = "L";
                switch (_mailerConfig.MailPriority)
                {
                case MailPriorityValues.High:
                    priority = "H";
                    break;

                case MailPriorityValues.Normal:
                    priority = "N";
                    break;

                default:
                    priority = "L";
                    break;
                }

                var baseUrl = baseUri.ToString();
                // token di sicurezza: contiene data e ora (senza minuti e secondi) e id del content item
                var token = string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHH"), (contentModel as ContentItem).Id);
                token = Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(token));
                //var url = string.Format("{0}/Laser.Orchard.MailCommunication/MailerResult?tk={1}", baseUrl, token);  // versione per il GET
                var tenantPrefix = GetTenantUrlPrexix(_shellSettings);
                var url          = string.Format("{0}/{1}api/Laser.Orchard.MailCommunication/MailerResultAPI?tk={2}", baseUrl, tenantPrefix, token); // versione per il POST

                data.Add("Subject", subject);
                data.Add("Body", body);
                data.Add("Sender", smtp.Address);
                data.Add("Priority", priority);
                data.Add("Url", url);        // url di ritorno per comunicare a Orchard il numero di mail inviate con successo
                data.Add("Attachments", ""); // TODO esempio: "[\"prova.pdf\",\"prova.docx\"]" 2016-01-14: per ora non li gestiamo
            }

            return(data);
        }
        public void Process(ScheduledTaskContext context)
        {
            if (context.Task.TaskType != TaskType)
            {
                return;
            }
            try {
                dynamic content            = context.Task.ContentItem;
                NewsletterEditionPart part = context.Task.ContentItem.As <NewsletterEditionPart>();
                _mailerConfig = _orchardServices.WorkContext.CurrentSite.As <MailerSiteSettingsPart>();
                var   urlHelper = _commonServices.GetUrlHelper();
                int[] selectedAnnIds;
                IList <AnnouncementPart>    items = null;
                IEnumerable <ExpandoObject> fullyItems;
                if (!String.IsNullOrWhiteSpace(part.AnnouncementIds))
                {
                    selectedAnnIds = !String.IsNullOrWhiteSpace(part.AnnouncementIds) ? part.AnnouncementIds.Split(',').Select(s => Convert.ToInt32(s)).ToArray() : null;
                    items          = GetAnnouncements(selectedAnnIds);
                    fullyItems     = items.Select(
                        s => new {
                        AnnouncementPart = s,
                        DisplayUrl       = urlHelper.ItemDisplayUrl(s)
                    }.ToExpando());
                }
                else
                {
                    fullyItems = null;
                }
                var           subscribers       = _newslServices.GetSubscribers(part.NewsletterDefinitionPartRecord_Id).Where(w => w.Confirmed);
                var           subscribersEmails = subscribers.Select(s => new { s.Id, s.Name, EmailAddress = s.Email });
                List <object> listaSubscribers  = new List <object>(subscribersEmails);

                // ricava i settings e li invia tramite FTP
                var templateId = _newslServices.GetNewsletterDefinition(part.NewsletterDefinitionPartRecord_Id,
                                                                        VersionOptions.Published).As <NewsletterDefinitionPart>().TemplateRecord_Id;
                var model = new {
                    NewsletterEdition = content,
                    ContentItems      = fullyItems
                }.ToExpando();
                Dictionary <string, object> settings = GetSettings(model, templateId, part);

                if ((settings.Count > 0) && (listaSubscribers.Count > 0))
                {
                    SendSettings(settings, part.Id);

                    // impagina e invia i recipiens tramite FTP
                    int           pageNum  = 0;
                    List <object> pagina   = new List <object>();
                    int           pageSize = _mailerConfig.RecipientsPerJsonFile;

                    for (int i = 0; i < listaSubscribers.Count; i++)
                    {
                        if (((i + 1) % pageSize) == 0)
                        {
                            SendRecipients(pagina, part.Id, pageNum);
                            pageNum++;
                            pagina = new List <object>();
                        }
                        pagina.Add(listaSubscribers[i]);
                    }
                    // invia l'ultima pagina se non è vuota
                    if (pagina.Count > 0)
                    {
                        SendRecipients(pagina, part.Id, pageNum);
                    }

                    // Aggiorno la newsletter edition, e rimuovo la relazione tra Newletter e Announcement
                    part.Dispatched   = true;
                    part.DispatchDate = DateTime.Now;
                    part.Number       = GetNextNumber(part.NewsletterDefinitionPartRecord_Id);;

                    if (items != null)
                    {
                        foreach (var item in items)
                        {
                            var ids = ("," + item.AttachToNextNewsletterIds + ",").Replace("," + part.NewsletterDefinitionPartRecord_Id + ",", "");
                            item.AttachToNextNewsletterIds = ids;
                        }
                    }

                    _contentManager.Publish(context.Task.ContentItem);
                }
                else
                {
                    Logger.Error(T("Error parsing mail template.").Text);
                }
            } catch (Exception ex) {
                string idcontenuto = "nessun id ";
                try {
                    idcontenuto = context.Task.ContentItem.Id.ToString();
                } catch (Exception ex2) { Logger.Error(ex2, ex2.Message); }
                Logger.Error(ex, "Error on " + TaskType + " for ContentItem id = " + idcontenuto + " : " + ex.Message);
            }
        }