public EmailCampaignViewModel GetById(int id) { EmailCampaign emailCampaign = unitOfWork.EmailCampaigns.GetById(id); emailCampaign.Email = unitOfWork.Emails.GetById((int)emailCampaign.EmailId); return(mapper.Map <EmailCampaignViewModel>(emailCampaign)); }
public void GetUnsentEmails_EmailCollection_EmptyArray() { EmailCampaign ec = new EmailCampaign() { SendingTime = DateTime.MaxValue, Name = "name", EmailId = 2 }; EmailRecipient item = new EmailRecipient() { CompanyId = 1 }; mockUnitOfWork .Setup(u => u.EmailRecipients.Get(It.IsAny <Expression <Func <EmailRecipient, bool> > >(), null, "")) .Returns(new List <EmailRecipient>() { item }); mockUnitOfWork.Setup(u => u.Emails.GetById(1)).Returns(new Email()); mockUnitOfWork.Setup(u => u.EmailCampaigns.GetById(1)).Returns(ec); mockMapper .Setup(m => m.Map <IEnumerable <EmailRecipient>, IEnumerable <EmailDTO> >(new List <EmailRecipient>())) .Returns(new List <EmailDTO>() { new EmailDTO() }); var result = manager.GetUnsentEmails(); Assert.That(result, Is.Not.Empty); }
public void SupplyWithCampaignNotifications_UserInCampaign_CampaignWithNotifications() { var user = new ApplicationUser { Id = "Hell", PhoneNumber = "+380566754454", PhoneNumberConfirmed = true, SmsNotificationsEnabled = true, Email = "*****@*****.**", EmailConfirmed = true, EmailNotificationsEnabled = true }; EmailCampaign item = new EmailCampaign { Id = 10, Name = "Hello, world", SendingTime = DateTime.MaxValue, UserId = "Hell", User = user }; mockUnitOfWork.Setup(m => m.ApplicationUsers.Get( It.IsAny <Expression <Func <ApplicationUser, bool> > >() , It.IsAny <Func <IQueryable <ApplicationUser>, IOrderedQueryable <ApplicationUser> > >(), It.IsAny <string>())) .Returns(new List <ApplicationUser>()); var result = generator.SupplyWithCampaignNotifications(item); Assert.That(result.EmailCampaignNotifications.Any()); }
protected void btnCreateCampaign_Click(object sender, EventArgs e) { try { string _accessToken = GetListService();// OAuth.GetAccessTokenByCode(HttpContext.Current, Request.QueryString["code"].ToString()); string _apiKey = ConfigurationManager.AppSettings["APIKey"]; IUserServiceContext userServiceContext = new UserServiceContext(_accessToken, _apiKey); ConstantContactFactory _constantContactFactory = new ConstantContactFactory(userServiceContext); _emailCampaignService = _constantContactFactory.CreateEmailCampaignService(); _emailCampaginScheduleService = _constantContactFactory.CreateCampaignScheduleService(); // EmailCampaign campaign = CreateCampaignFromInputs(); EmailCampaign campaign = CreateCampaignFromInputs(); var savedCampaign = _emailCampaignService.AddCampaign(campaign); if (savedCampaign != null) { //campaign was saved, but need to schedule it, if the case Schedule schedule = null; { schedule = new Schedule() { ScheduledDate = Convert.ToDateTime(DateTime.Now.AddMinutes(1).ToShortTimeString().Trim()).ToUniversalTime() }; } Schedule savedSchedule = _emailCampaginScheduleService.AddSchedule(savedCampaign.Id, schedule); } } catch (Exception ex) { } }
/// <summary> /// Update a specific email campaign. /// </summary> /// <param name="campaign">Campaign to be updated.</param> /// <returns>Returns a campaign.</returns> public EmailCampaign UpdateCampaign(EmailCampaign campaign) { if (campaign == null) { throw new IllegalArgumentException(CTCT.Resources.Errors.EmailCampaignOrId); } string url = String.Concat(Settings.Endpoints.Default.BaseUrl, String.Format(Settings.Endpoints.Default.Campaign, campaign.Id)); // Invalidate data that are not supported by the update API procedure campaign.CreatedDate = null; campaign.TrackingSummary = null; campaign.ModifiedDate = null; campaign.IsVisibleInUI = null; // Convert to JSON string string json = campaign.ToJSON(); RawApiResponse response = RestClient.Put(url, UserServiceContext.AccessToken, UserServiceContext.ApiKey, json); try { var emailCampaign = response.Get <EmailCampaign>(); return(emailCampaign); } catch (Exception ex) { throw new CtctException(ex.Message, ex); } }
/// <summary> /// Update a specific email campaign. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="campaign">Campaign to be updated.</param> /// <returns>Returns a campaign.</returns> public EmailCampaign UpdateCampaign(string accessToken, string apiKey, EmailCampaign campaign) { EmailCampaign emailCampaign = null; string url = String.Concat(Config.Endpoints.BaseUrl, String.Format(Config.Endpoints.Campaign, campaign.Id)); // Invalidate data that are not supported by the update API procedure campaign.CreatedDate = null; campaign.TrackingSummary = null; campaign.ModifiedDate = null; campaign.IsVisibleInUI = null; // Convert to JSON string string json = campaign.ToJSON(); CUrlResponse response = RestClient.Put(url, accessToken, apiKey, json); if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } if (response.HasData) { emailCampaign = response.Get <EmailCampaign>(); } return(emailCampaign); }
public void Initialize() { EmailCampaign sampleEmailCampaign = campaignData.GetCustomEmailCampaign(campaign1, CampaignStatus.Draft, 1, new Email() { EmailId = "*****@*****.**" }, campaignData.GetSampleMailingList(3), new DateTime(), new DateTime(), null); }
public void Update(EmailCampaignViewModel item) { try { EmailCampaign emailCampaign = mapper.Map <EmailCampaign>(item); Email email = unitOfWork.Emails.Get(filter: e => e.EmailAddress == item.EmailAddress).FirstOrDefault(); if (email == null) { email = new Email(); email.EmailAddress = item.EmailAddress; unitOfWork.Emails.Insert(email); emailCampaign.Email = email; } else { emailCampaign.EmailId = email.Id; } unitOfWork.EmailCampaigns.Update(emailCampaign); unitOfWork.Save(); } catch (Exception e) { throw e; } }
public void SupplyWithCampaignNotifications_NullCampaign_Null() { EmailCampaign item = null; var result = generator.SupplyWithCampaignNotifications(item); Assert.That(result, Is.Null); }
public void EmailCampaignDomain_FromEmailIsNotNullOrEmpty_NoException() { DC.Campaign campaign = campaignData.GetCustomCampaign("Test", "Test subject", "test", CampaignTemplate.Blank, 1); EmailCampaign emailCampaign = campaignData.GetCustomEmailCampaign(CampaignStatus.Draft, 1, null, campaignData.GetSampleMailingList(3), new DateTime(), new DateTime(), null); emailCampaign.Campaign = campaign; Assert.IsFalse(emailCampaign.IsFromEmailValid()); }
public void EmailCampaignDomain_CampaignStatusIsScheduledAndScheduleTimeIsFutureTime_NoException() { DC.Campaign campaign = campaignData.GetCustomCampaign("Test", "Test subject", "test", CampaignTemplate.Blank, 1); EmailCampaign emailCampaign = campaignData.GetCustomEmailCampaign(CampaignStatus.Scheduled, 1, new Email() { EmailId = "*****@*****.**" }, campaignData.GetSampleMailingList(3), new DateTime(2020, 1, 1), new DateTime(), null); emailCampaign.Campaign = campaign; Assert.IsTrue(emailCampaign.IsScheduleTimeValid()); }
public void EmailCampaignDomain_FromEmailIsNullOrEmpty_ThrowException() { DC.Campaign campaign = campaignData.GetCustomCampaign("Test", "Test subject", "test", CampaignTemplate.Blank, 1); EmailCampaign emailCampaign = campaignData.GetCustomEmailCampaign(CampaignStatus.Draft, 1, new Email() { EmailId = "*****@*****.**" }, campaignData.GetSampleMailingList(3), new DateTime(), new DateTime(), null); emailCampaign.Campaign = campaign; Assert.IsTrue(emailCampaign.IsToMailingListValid()); }
public void EmailCampaignDomain_CampaignIsNotValidNull_ThrowException() { DC.Campaign campaign = campaignData.GetCustomCampaign(null, null, null, CampaignTemplate.Blank, 1); EmailCampaign emailCampaign = campaignData.GetCustomEmailCampaign(CampaignStatus.Draft, 1, new Email() { EmailId = "*****@*****.**" }, campaignData.GetSampleMailingList(3), new DateTime(), new DateTime(), null); emailCampaign.Campaign = campaign; Assert.IsFalse(emailCampaign.IsCampaignValid()); }
public static void SeedEmailCampaigns(IUnitOfWork unitOfWork) { if (unitOfWork.EmailCampaigns.Get(com => com.Name == "Great email campaign!").Any()) { return; } var ecompany = new EmailCampaign { Email = new Email() { EmailAddress = "*****@*****.**" }, Message = "Hello User!", Name = "Great email campaign!", Description = "example", SendingTime = DateTime.Now }; var recipients = new List <EmailRecipient>() { new EmailRecipient() { Email = new Email() { EmailAddress = "*****@*****.**" } }, new EmailRecipient() { Email = new Email() { EmailAddress = "*****@*****.**" } } }; ecompany.EmailRecipients = recipients; ecompany.UserId = unitOfWork.ApplicationUsers.Get().First(a => a.Email == "*****@*****.**").Id; ecompany.EmailCampaignNotifications = new List <EmailCampaignNotification>() { new EmailCampaignNotification() { ApplicationUserId = ecompany.UserId, BeenSent = true, Type = NotificationType.Email } }; unitOfWork.EmailCampaigns.Insert(ecompany); unitOfWork.Save(); }
public void Delete(int id) { try { EmailCampaign emailCampaign = unitOfWork.EmailCampaigns.GetById(id); unitOfWork.EmailCampaigns.Delete(emailCampaign); unitOfWork.Save(); } catch (Exception e) { throw e; } }
/** Creates a list of campaigns, and sends it, with content based on the campaignTemplate transform */ public int SendEmails(Dictionary <string, string> parameters) { int status = 0; try { IEnumerable <EmailCampaign> campaigns = CreateCampaigns(parameters); GlobalFunctions.InfoLog($"{0} campaigns has been created. Scheduling campaigns."); if (campaigns.Count() == 0) { status = -1; } foreach (EmailCampaign campaign in campaigns) { EmailCampaign campaign_ = _emailCampaignService.AddCampaign(campaign); Schedule schedule; schedule = new Schedule() { ScheduledDate = DateTime.Now.AddMinutes(20).ToUniversalTime() }; schedule = _emailCampaginScheduleService.AddSchedule(campaign_.Id, schedule); if (schedule == null) { GlobalFunctions.WarnLog("Campaign was saved, but failed to schedule it!"); status = -1; } } } catch (IllegalArgumentException illegalEx) { GlobalFunctions.ErrorLog(GetExceptionsDetails(illegalEx, "IllegalArgumentException")); status = -1; } catch (CtctException ctcEx) { GlobalFunctions.ErrorLog(GetExceptionsDetails(ctcEx, "CtctException")); status = -1; } catch (OAuth2Exception oauthEx) { GlobalFunctions.ErrorLog(GetExceptionsDetails(oauthEx, "OAuth2Exception")); status = -1; } catch (Exception ex) { GlobalFunctions.ErrorLog(GetExceptionsDetails(ex, "Exception")); status = -1; } return(status); }
public void IncertWithRecepients(EmailCampaignViewModel campaign, List <EmailRecipientViewModel> emailRecipients) { try { EmailCampaign emailCampaign = mapper.Map <EmailCampaign>(campaign); Email email = unitOfWork.Emails.Get(filter: e => e.EmailAddress == campaign.EmailAddress).FirstOrDefault(); if (email == null) { email = new Email(); email.EmailAddress = campaign.EmailAddress; unitOfWork.Emails.Insert(email); emailCampaign.Email = email; } else { emailCampaign.EmailId = email.Id; } notificationsGenerator.SupplyWithCampaignNotifications(emailCampaign); unitOfWork.EmailCampaigns.Insert(emailCampaign); unitOfWork.Save(); foreach (var recipient in emailRecipients) { EmailRecipient newRecepient = mapper.Map <EmailRecipientViewModel, EmailRecipient>(recipient); newRecepient.CompanyId = emailCampaign.Id; email = unitOfWork.Emails.Get(filter: e => e.EmailAddress == recipient.EmailAddress).FirstOrDefault(); if (email == null) { email = new Email(); email.EmailAddress = recipient.EmailAddress; unitOfWork.Emails.Insert(email); newRecepient.Email = email; } else { newRecepient.EmailId = email.Id; } unitOfWork.EmailRecipients.Insert(newRecepient); unitOfWork.Save(); } } catch (Exception e) { throw e; } }
/// <summary> /// Get campaign details for a specific campaign. /// </summary> /// <param name="accessToken">Access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="campaignId">Campaign id.</param> /// <returns>Returns a campaign.</returns> public EmailCampaign GetCampaign(string accessToken, string apiKey, string campaignId) { EmailCampaign campaign = null; string url = String.Concat(Config.Endpoints.BaseUrl, String.Format(Config.Endpoints.Campaign, campaignId)); CUrlResponse response = RestClient.Get(url, accessToken, apiKey); if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } if (response.HasData) { campaign = response.Get <EmailCampaign>(); } return(campaign); }
/// <summary> /// Create a new campaign. /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token.</param> /// <param name="apiKey">The API key for the application</param> /// <param name="campaign">Campign to be created</param> /// <returns>Returns a campaign.</returns> public EmailCampaign AddCampaign(string accessToken, string apiKey, EmailCampaign campaign) { EmailCampaign emailcampaign = null; string url = String.Concat(Config.Endpoints.BaseUrl, Config.Endpoints.Campaigns); string json = campaign.ToJSON(); CUrlResponse response = RestClient.Post(url, accessToken, apiKey, json); if (response.HasData) { emailcampaign = response.Get <EmailCampaign>(); } else if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } return(emailcampaign); }
/// <summary> /// Create a new campaign. /// </summary> /// <param name="campaign">Campign to be created</param> /// <returns>Returns a campaign.</returns> public EmailCampaign AddCampaign(EmailCampaign campaign) { if (campaign == null) { throw new IllegalArgumentException(CTCT.Resources.Errors.EmailCampaignOrId); } string url = String.Concat(Settings.Endpoints.Default.BaseUrl, Settings.Endpoints.Default.Campaigns); string json = campaign.ToJSON(); RawApiResponse response = RestClient.Post(url, UserServiceContext.AccessToken, UserServiceContext.ApiKey, json); try { var emailcampaign = response.Get <EmailCampaign>(); return(emailcampaign); } catch (Exception ex) { throw new CtctException(ex.Message, ex); } }
/// <summary> /// Get Email Campaign from the Http response stream. /// </summary> /// <param name="stream">Response stream</param> /// <returns>Email Campaign</returns> public static EmailCampaign GetEmailCampaign(Stream stream) { EmailCampaign campaign = new EmailCampaign(); const string xpathSelect = @"//at:entry"; StreamReader reader = new StreamReader(stream); XmlTextReader xmlreader = new XmlTextReader(reader); XPathDocument doc = new XPathDocument(xmlreader); // initialize navigator XPathNavigator pn = doc.CreateNavigator(); // initialize namespace manager XmlNamespaceManager resolver = new XmlNamespaceManager(pn.NameTable); resolver.AddNamespace("at", AtomNamespace); resolver.AddNamespace("cc", ConstantNamespace); XPathExpression expr = pn.Compile(xpathSelect); expr.SetContext(resolver); XPathNodeIterator nodes = pn.Select(expr); while (nodes.MoveNext()) { // save current node XPathNavigator node = nodes.Current; // add Contact List object to the collection campaign = GetEmailCampaign(node, resolver); break; } reader.Close(); xmlreader.Close(); return(campaign); }
private void btnSave_Click(object sender, EventArgs e) { btnSave.Enabled = false; try { EmailCampaign campaign = CreateCampaignFromInputs(); EmailCampaign savedCampaign = ConstantContact.AddCampaign(campaign); if (savedCampaign != null) { //campaign was saved, but need to schedule it, if the case Schedule schedule = null; if (rbnSendNow.Checked || rbnScheduled.Checked) { if (rbnSendNow.Checked) { schedule = new Schedule() { ScheduledDate = DateTime.Now }; } else { schedule = new Schedule() { ScheduledDate = Convert.ToDateTime(txtScheduleDate.Text.Trim()) }; } Schedule savedSchedule = ConstantContact.AddSchedule(savedCampaign.Id, schedule); if (savedSchedule != null) { MessageBox.Show("Campaign successfully saved and scheduled!", "Success"); } else { MessageBox.Show("Campaign was saved, but failed to schedule it!", "Failure"); } } else { MessageBox.Show("Campaign successfully saved!", "Success"); } } else { MessageBox.Show("Failed to save campaign!", "Failure"); } } catch (IllegalArgumentException illegalEx) { MessageBox.Show(GetExceptionsDetails(illegalEx, "IllegalArgumentException"), "Exception"); } catch (CtctException ctcEx) { MessageBox.Show(GetExceptionsDetails(ctcEx, "CtctException"), "Exception"); } catch (OAuth2Exception oauthEx) { MessageBox.Show(GetExceptionsDetails(oauthEx, "OAuth2Exception"), "Exception"); } catch (Exception ex) { MessageBox.Show(GetExceptionsDetails(ex, "Exception"), "Exception"); } btnSave.Enabled = true; }
/// <summary> /// Get EmailCampaign object from specified Xml data /// </summary> /// <param name="node">Xml data cursor model</param> /// <param name="resolver">Xml namespace resolver</param> /// <returns>EmailCampaign</returns> private static EmailCampaign GetEmailCampaign(XPathNavigator node, IXmlNamespaceResolver resolver) { EmailCampaign emailCampaign = new EmailCampaign(); const string xpathSelect = @"at:content/cc:Campaign"; XPathNodeIterator emailCampaignContentNodes = node.Select(xpathSelect, resolver); while (emailCampaignContentNodes.MoveNext()) { XPathNavigator currentNode = emailCampaignContentNodes.Current; emailCampaign.ID = GetEmailCampaignId(currentNode); if (currentNode.HasChildren) { currentNode.MoveToFirstChild(); do { switch (currentNode.Name) { case EmailCampaignXmlNodeName: emailCampaign.Name = currentNode.Value; break; case EmailCampaignXmlNodeStatus: emailCampaign.State = (CampaignState)Enum.Parse(typeof(CampaignState), currentNode.Value); break; case EmailCampaignXmlNodeDate: emailCampaign.Date = currentNode.ValueAsDateTime; break; case EmailCampaignXmlNodeLastEditDate: emailCampaign.LastEditDate = currentNode.ValueAsDateTime; break; case EmailCampaignXmlNodeNextRunDate: emailCampaign.NextRunDate = currentNode.ValueAsDateTime; break; case EmailCampaignXmlNodeSent: emailCampaign.Sent = currentNode.ValueAsInt; break; case EmailCampaignXmlNodeOpens: emailCampaign.Opens = currentNode.ValueAsInt; break; case EmailCampaignXmlNodeClicks: emailCampaign.Clicks = currentNode.ValueAsInt; break; case EmailCampaignXmlNodeBounces: emailCampaign.Bounces = currentNode.ValueAsInt; break; case EmailCampaignXmlNodeForwards: emailCampaign.Forwards = currentNode.ValueAsInt; break; case EmailCampaignXmlNodeSpamReports: emailCampaign.SpamReports = currentNode.ValueAsInt; break; case EmailCampaignXmlNodeOptOuts: emailCampaign.OptOuts = currentNode.ValueAsInt; break; case EmailCampaignXmlNodeSubject: emailCampaign.Subject = currentNode.Value; break; case EmailCampaignXmlNodeFromName: emailCampaign.FromName = currentNode.Value; break; case EmailCampaignXmlNodeCampaignType: emailCampaign.CampaignType = (CampaignType)Enum.Parse(typeof(CampaignType), currentNode.Value); break; case EmailCampaignXmlNodeViewAsWebpage: emailCampaign.ViewAsWebpage = currentNode.Value.Equals("YES", StringComparison.CurrentCultureIgnoreCase) ? true : false; break; case EmailCampaignXmlNodeViewAsWebpageLinkText: emailCampaign.ViewAsWebpageLinkText = currentNode.Value; break; case EmailCampaignXmlNodeViewAsWebpageText: emailCampaign.ViewAsWebpageText = currentNode.Value; break; case EmailCampaignXmlNodePermissionReminder: emailCampaign.PermissionReminder = currentNode.Value.Equals("YES", StringComparison.CurrentCultureIgnoreCase) ? true : false; break; case EmailCampaignXmlNodePermissionReminderText: emailCampaign.PermissionReminderText = currentNode.Value; break; case EmailCampaignXmlNodeGreetingName: emailCampaign.GreetingName = currentNode.Value; break; case EmailCampaignXmlNodeGreetingSalutation: emailCampaign.GreetingSalutation = currentNode.Value; break; case EmailCampaignXmlNodeGreetingString: emailCampaign.GreetingString = currentNode.Value; break; case EmailCampaignXmlNodeOrganizationName: emailCampaign.OrganizationName = currentNode.Value; break; case EmailCampaignXmlNodeOrganizationAddress1: emailCampaign.OrganizationAddress1 = currentNode.Value; break; case EmailCampaignXmlNodeOrganizationAddress2: emailCampaign.OrganizationAddress2 = currentNode.Value; break; case EmailCampaignXmlNodeOrganizationAddress3: emailCampaign.OrganizationAddress3 = currentNode.Value; break; case EmailCampaignXmlNodeOrganizationCity: emailCampaign.OrganizationCity = currentNode.Value; break; case EmailCampaignXmlNodeOrganizationState: emailCampaign.OrganizationState = currentNode.Value; break; case EmailCampaignXmlNodeOrganizationInternationalState: emailCampaign.OrganizationInternationalState = currentNode.Value; break; case EmailCampaignXmlNodeOrganizationCountry: emailCampaign.OrganizationCountry = currentNode.Value; break; case EmailCampaignXmlNodeOrganizationPostalCode: emailCampaign.OrganizationPostalCode = currentNode.Value; break; case EmailCampaignXmlNodeIncludeForwardEmail: emailCampaign.IncludeForwardEmail = currentNode.Value.Equals("YES", StringComparison.CurrentCultureIgnoreCase) ? true : false; break; case EmailCampaignXmlNodeForwardEmailLinkText: emailCampaign.ForwardEmailLinkText = currentNode.Value; break; case EmailCampaignXmlNodeIncludeSubscribeLink: emailCampaign.IncludeSubscribeLink = currentNode.Value.Equals("YES", StringComparison.CurrentCultureIgnoreCase) ? true : false; break; case EmailCampaignXmlNodeSubscribeLinkText: emailCampaign.SubscribeLinkText = currentNode.Value; break; case EmailCampaignXmlNodeEmailContentFormat: emailCampaign.EmailContentFormat = currentNode.Value; break; case EmailCampaignXmlNodeEmailContent: if (emailCampaign.EmailContentFormat.Equals("HTML")) { emailCampaign.Content = currentNode.Value; } else { emailCampaign.XContent = currentNode.Value; } break; case EmailCampaignXmlNodeEmailTextContent: emailCampaign.TextContent = currentNode.Value; break; case EmailCampaignXmlNodeContactLists: emailCampaign.ContactLists = GetContactListFromCampaignResponse(currentNode); break; case EmailCampaignXmlNodeFromEmail: ConstantContactEmail fromEmail = GetEmailFromCampaignResponse(currentNode); emailCampaign.FromEmailID = fromEmail.EmailId; emailCampaign.FromEmail = fromEmail.EmailAddress; break; case EmailCampaignXmlNodeReplyToEmail: ConstantContactEmail replyToEmail = GetEmailFromCampaignResponse(currentNode); emailCampaign.ReplyToEmailID = replyToEmail.EmailId; emailCampaign.ReplyToEmail = replyToEmail.EmailAddress; break; case EmailCampaignXmlNodeStyleSheet: emailCampaign.StyleSheet = currentNode.Value; break; } } while (currentNode.MoveToNext()); } break; } return(emailCampaign); }
private IEnumerable <EmailCampaign> CreateCampaigns(Dictionary <string, string> parameters) { XDocument emailTemplate = new XDocument(); using (System.Xml.XmlWriter writer = emailTemplate.CreateWriter()) { XslCompiledTransform emailTemplateTransform = new XslCompiledTransform(); XsltArgumentList emailTemplateArgList = new XsltArgumentList(); foreach (KeyValuePair <string, string> parameter in parameters) { emailTemplateArgList.AddParam(parameter.Key, "", parameter.Value); } emailTemplateTransform.Load(_emailTemplateTransformUrl); emailTemplateTransform.Transform(createEmailConnectionXML().CreateReader(), emailTemplateArgList, writer); } List <EmailCampaign> campaigns = new List <EmailCampaign>(); foreach (XElement campaignElement in emailTemplate.Descendants("campaign")) { EmailCampaign campaign = new EmailCampaign(); campaign.EmailContentFormat = CampaignEmailFormat.XHTML; campaign.Status = CampaignStatus.SENT; foreach (XElement property in campaignElement.Elements("property")) { string name = property.Attribute("name").Value; string value = String.Concat(property.Nodes()); try { campaign.GetType().GetProperty(name).SetValue(campaign, value, null); } catch (Exception) { throw new Exception($"Error with campaign property setting, {name}, with value, {value}"); } } MessageFooter msgFooter = new MessageFooter(); campaign.MessageFooter = msgFooter; foreach (XElement method in emailTemplate.Descendants("footer").Elements("property")) { string name = method.Attribute("name").Value; string value = method.Value; try { msgFooter.GetType().GetProperty(name).SetValue(msgFooter, value, null); } catch (Exception) { throw new Exception($"Error with footer property setting, {name}, with value, {value}"); } } List <SentContactList> lists = new List <SentContactList>(); foreach (XElement method in emailTemplate.Descendants("contacts").Elements("contact")) { string id = method.Attribute("id").Value; SentContactList contactList = new SentContactList() { Id = id }; lists.Add(contactList); } campaign.Lists = lists; campaigns.Add(campaign); } return(campaigns); }
/// <summary> /// Create an EmailCampaign object from user inputs /// </summary> /// <returns></returns> private EmailCampaign CreateCampaignFromInputs() { EmailCampaign campaign = new EmailCampaign(); #region General settings if (!string.IsNullOrWhiteSpace(txtCampaignName.Text)) { campaign.Name = txtCampaignName.Text.Trim(); } if (cbCampaignType.SelectedItem != null) { //campaign.TemplateType = GetCampaignType(cbCampaignType.SelectedItem as ItemInfo); } if (!string.IsNullOrWhiteSpace(txtSubject.Text)) { campaign.Subject = txtSubject.Text.Trim(); } if (!string.IsNullOrWhiteSpace(txtFromName.Text)) { campaign.FromName = txtFromName.Text.Trim(); } if (cbFromEmail.SelectedIndex != null) { campaign.FromEmail = GetSelectedValue(cbFromEmail.SelectedItem as ItemInfo); } if (cbReplyToEmail.SelectedIndex != null) { campaign.ReplyToEmail = GetSelectedValue(cbReplyToEmail.SelectedItem as ItemInfo); } if (rbnHtml.Checked) { campaign.EmailContentFormat = CampaignEmailFormat.HTML; } else { campaign.EmailContentFormat = CampaignEmailFormat.XHTML; } if (!string.IsNullOrWhiteSpace(txtGreetingString.Text)) { campaign.GreetingString = txtGreetingString.Text.Trim(); } if (!string.IsNullOrWhiteSpace(txtEmailContent.Text)) { campaign.EmailContent = txtEmailContent.Text.Trim(); } if (!string.IsNullOrWhiteSpace(txtContent.Text)) { campaign.TextContent = txtContent.Text.Trim(); } #endregion General settings #region Message footer settings //organization name is required for message footer section if (!string.IsNullOrWhiteSpace(txtOrganizationName.Text)) { MessageFooter msgFooter = new MessageFooter(); if (!string.IsNullOrWhiteSpace(txtOrganizationName.Text)) { msgFooter.OrganizationName = txtOrganizationName.Text.Trim(); } if (!string.IsNullOrWhiteSpace(txtAddressLine1.Text)) { msgFooter.AddressLine1 = txtAddressLine1.Text.Trim(); } if (!string.IsNullOrWhiteSpace(txtAddressLine2.Text)) { msgFooter.AddressLine2 = txtAddressLine2.Text.Trim(); } if (!string.IsNullOrWhiteSpace(txtAddressLine3.Text)) { msgFooter.AddressLine3 = txtAddressLine3.Text.Trim(); } if (!string.IsNullOrWhiteSpace(txtCity.Text)) { msgFooter.City = txtCity.Text.Trim(); } if (!string.IsNullOrWhiteSpace(txtZip.Text)) { msgFooter.PostalCode = txtZip.Text.Trim(); } if (cbCountry.SelectedItem != null) { msgFooter.Country = GetSelectedValue(cbCountry.SelectedItem as ItemInfo); } if (cbState.SelectedItem != null) { var state = cbState.SelectedItem as ItemInfo; if (state != null) { msgFooter.State = state.Name; } } if (chkIncludeForwardEmail.Checked) { msgFooter.ForwardEmailLinkText = txtIncludeForwardEmail.Text.Trim(); msgFooter.IncludeForwardEmail = true; } if (chkIncludeSubscribeLink.Checked) { msgFooter.SubscribeLinkText = txtIncludeSubscribeLink.Text.Trim(); msgFooter.IncludeSubscribeLink = true; } campaign.MessageFooter = msgFooter; } #endregion Message footer settings #region Contact lists settings List <SentContactList> lists = new List <SentContactList>(); if (lstContactList.SelectedItems.Count > 0) { foreach (var item in lstContactList.SelectedItems) { SentContactList contactList = new SentContactList() { Id = GetSelectedValue(item as ItemInfo) }; lists.Add(contactList); } } campaign.Lists = lists; #endregion Contact lists settings #region Schedule campaign settings if (rbnDraft.Checked) { campaign.Status = CampaignStatus.DRAFT; } else if (rbnSendNow.Checked) { campaign.Status = CampaignStatus.SENT; } else if (rbnScheduled.Checked) { campaign.Status = CampaignStatus.SCHEDULED; } #endregion Schedule campaign settings return(campaign); }
private EmailCampaign CreateCampaignFromInputs() { EmailCampaign campaign = new EmailCampaign(); #region General settings // if (!string.IsNullOrWhiteSpace(txtCampaignName.Text)) { campaign.Name = "Campaign Name here"; } // if (cbCampaignType.SelectedItem != null) { //campaign.TemplateType = GetCampaignType(cbCampaignType.SelectedItem as ItemInfo); } // if (!string.IsNullOrWhiteSpace(txtSubject.Text)) { campaign.Subject = "subject here"; } // if (!string.IsNullOrWhiteSpace(txtFromName.Text)) { campaign.FromName = "FromName"; } // if (cbFromEmail.SelectedIndex != null) { campaign.FromEmail = "FromEmail"; } // if (cbReplyToEmail.SelectedIndex != null) { campaign.ReplyToEmail = "ReplyEmail"; } // if (rbnHtml.Checked) { campaign.EmailContentFormat = CampaignEmailFormat.HTML; } // else // { // campaign.EmailContentFormat = CampaignEmailFormat.XHTML; // } // if (!string.IsNullOrWhiteSpace(txtGreetingString.Text)) { campaign.GreetingString = "greetings"; } // if (!string.IsNullOrWhiteSpace(txtEmailContent.Text)) { campaign.EmailContent = "email body"; } // if (!string.IsNullOrWhiteSpace(txtContent.Text)) { campaign.TextContent = ".text content"; } #endregion General settings //#region Message footer settings ////organization name is required for message footer section //if (!string.IsNullOrWhiteSpace(txtOrganizationName.Text)) //{ MessageFooter msgFooter = new MessageFooter(); // if (!string.IsNullOrWhiteSpace(txtOrganizationName.Text)) // { msgFooter.OrganizationName = "Org name"; // } // if (!string.IsNullOrWhiteSpace(txtAddressLine1.Text)) // { msgFooter.AddressLine1 = "address"; // } // if (!string.IsNullOrWhiteSpace(txtAddressLine2.Text)) // { // msgFooter.AddressLine2 = txtAddressLine2.Text.Trim(); // } // if (!string.IsNullOrWhiteSpace(txtAddressLine3.Text)) // { // msgFooter.AddressLine3 = txtAddressLine3.Text.Trim(); // } // if (!string.IsNullOrWhiteSpace(txtCity.Text)) // { msgFooter.City = "NJ"; // } // if (!string.IsNullOrWhiteSpace(txtZip.Text)) // { msgFooter.PostalCode = "07095"; // } // if (cbCountry.SelectedItem != null) // { msgFooter.Country = "US";// GetSelectedValue(cbCountry.SelectedItem as ItemInfo); // } // if (cbState.SelectedItem != null) // { // var state = cbState.SelectedItem as ItemInfo; // if (state != null) // { msgFooter.State = "NJ"; // } // } // if (chkIncludeForwardEmail.Checked) // { // msgFooter.ForwardEmailLinkText = txtIncludeForwardEmail.Text.Trim(); // msgFooter.IncludeForwardEmail = true; // } // if (chkIncludeSubscribeLink.Checked) // { // msgFooter.SubscribeLinkText = txtIncludeSubscribeLink.Text.Trim(); // msgFooter.IncludeSubscribeLink = true; // } campaign.MessageFooter = msgFooter; //} //#endregion Message footer settings #region Contact lists settings List <SentContactList> lists = new List <SentContactList>(); if (contactListFromListService.Count > 0) { foreach (var item in contactListFromListService.ToList <ContactList>()) { SentContactList contactList = new SentContactList() { Id = item.Id }; lists.Add(contactList); } } campaign.Lists = lists; #endregion Contact lists settings #region Schedule campaign settings //if (rbnDraft.Checked) //{ // campaign.Status = CampaignStatus.DRAFT; //} //else if (rbnSendNow.Checked) //{ // campaign.Status = CampaignStatus.SENT; //} //else if (rbnScheduled.Checked) //{ campaign.Status = CampaignStatus.SCHEDULED; //} #endregion Schedule campaign settings return(campaign); }
void tmrAutomation_Elapsed(object sender, ElapsedEventArgs e) { // ReSharper disable once CSharpWarnings::CS0420 if (Interlocked.CompareExchange(ref tmrAutomationSync, 1, 0) == 0) { try { NHibernateHelper.ClearCache(); var emailManager = new EaEmailService("auth.smtp.1and1.co.uk", 25, "*****@*****.**", "a9215361", SmtpConnectType.ConnectSSLAuto, null); // changes batch status using (var trans = Session.BeginTransaction()) { try { var batches = Session.CreateQuery(@"select distinct ob from OrderBatch as ob where ob.Status = :bst and ob.Order.Status = :ost") .SetParameter("bst", OrderBatch.BatchStatus.Purchasing) .SetParameter("ost", Order.OrderStatus.Technical) .List <OrderBatch>(); var lst = new List <OrderBatch>(); foreach (var batch in batches) { if (batch.IsReadyInWarehouse) { logger.InfoFormat("tmrAutomation_Elapsed: Changing batch #{0} to 'Ready In Warehouse'", batch.Code); batch.Status = OrderBatch.BatchStatus.Ready_In_Warehouse; Session.SaveOrUpdate(batch); lst.Add(batch); } } Session.Flush(); trans.Commit(); if (lst.Count > 0) { // send email var sb = new StringBuilder(5000); sb.AppendFormat("<html>"); sb.AppendFormat("<body>"); sb.AppendFormat("<div dir=\"ltr\">"); sb.AppendFormat( "<h1>The following batches were changed to status: Ready In Warehouse</h1>"); sb.AppendFormat("<ul>"); foreach (var batch in lst) { sb.AppendFormat("<li>#{0} - {1}</li>", batch.Code, batch.Order.CustomerName); } sb.AppendFormat("</ul>"); sb.AppendFormat("</div>"); sb.AppendFormat("</body>"); sb.AppendFormat("</html>"); using (var mm = new MailMessage()) { mm.From = new MailAddress("*****@*****.**", "Miracle System"); mm.To.Add(new MailAddress("*****@*****.**")); mm.Subject = "Batches changed their status"; mm.IsBodyHtml = true; mm.Body = sb.ToString(); emailManager.SendMessage(mm); } } } catch (Exception ex) { if (!trans.WasCommitted) { trans.Rollback(); } logger.Error("tmrAutomation_Elapsed - batch status chaging", ex); } } var now = DateTime.Now; if (now.Hour == 12 && 0 <= now.Minute && now.Minute < 5 && now.DayOfWeek != DayOfWeek.Sunday && now.DayOfWeek != DayOfWeek.Saturday) { var unsubscribers = new HashSet <string>(Session.GetAll <Unsubscriber>().Select(us => us.Email), StringComparer.OrdinalIgnoreCase); var campaigns = new EmailCampaign[specialCampaigns.Length]; var lists = new IList <Customer> [specialCampaigns.Length]; for (var i = 0; i < specialCampaigns.Length; i++) { campaigns[i] = Session.Get <EmailCampaign>(specialCampaigns[i]); lists[i] = new List <Customer>(); } // Web Quotes Campaign if (campaigns[0].Started) { using (var trans = Session.BeginTransaction()) { try { var minDate = DateTime.Now.AddDays(-14).Date; var maxDate = DateTime.Now.AddDays(-1).DayEnd(); var quotes = Session.QueryOver <Quote>() .Where(q => q.Company.ID == "A" && minDate <= q.DateCreated && q.DateCreated < maxDate && q.EFollowUpCheck == false) .JoinQueryOver(q => q.CreatedUser) .Where(u => u.IsWebsite) .List(); foreach (var quote in quotes) { // check if customer was already emailed in the last 48 hours if (quote.Customer.LastAutoEmail == null || quote.Customer.LastAutoEmail.Value < now.AddDays(-2).Date) { var q = quote; if (!quote.Customer.Orders.Any(o => o.DateCreated >= q.DateCreated) && !quote.Customer.Invoices.Any(i => i.DateCreated >= q.DateCreated)) { quote.Customer.LastAutoEmail = now; Session.SaveOrUpdate(quote.Customer); lists[0].Add(quote.Customer); } else { logger.WarnFormat("WebQuotes campaign - Customer: '{0}' Rejected due to existance of future orders or invoices", quote.Customer.Code); } } else { logger.WarnFormat("WebQuotes campaign - Customer: '{0}' Rejected due to LastAutoEmail: '{1}'", quote.Customer.Code, quote.Customer.LastAutoEmail); } quote.EFollowUpCheck = true; Session.SaveOrUpdate(quote); Session.Flush(); } trans.Commit(); } catch (Exception ex) { trans.Rollback(); lists[0] = new List <Customer>(); logger.Error("tmrAutomation_Elapsed - web quotes follow up", ex); } } } // Request Brochures Campaign if (campaigns[1].Started) { using (var trans = Session.BeginTransaction()) { try { var minDate = DateTime.Now.AddDays(-18).Date; var maxDate = DateTime.Now.AddDays(-9).DayEnd(); var events = Session.QueryOver <Event>().Where(ev => ev.EventType.ID == 2 && minDate <= ev.DateCreated && ev.DateCreated < maxDate && ev.EFollowUpCheck == false).List(); foreach (var evnt in events) { // check if customer was already emailed in the last 48 hours if (evnt.Customer.LastAutoEmail == null || evnt.Customer.LastAutoEmail.Value < now.AddDays(-2).Date) { var ev = evnt; if (!evnt.Customer.Quotes.Any(q => q.DateCreated >= ev.DateCreated && q.CreatedUser.IsWebsite) && !evnt.Customer.Orders.Any(o => o.DateCreated >= ev.DateCreated) && !evnt.Customer.Invoices.Any(i => i.DateCreated >= ev.DateCreated)) { evnt.Customer.LastAutoEmail = now; Session.SaveOrUpdate(evnt.Customer); lists[1].Add(evnt.Customer); } else { logger.WarnFormat("Brochure Requests campaign - Customer: '{0}' Rejected due to existance of future web-quotes, orders or invoices", evnt.Customer.Code); } } else { logger.WarnFormat("Brochure Requests campaign - : '{0}' Rejected due to LastAutoEmail: '{1}'", evnt.Customer.Code, evnt.Customer.LastAutoEmail); } evnt.EFollowUpCheck = true; Session.SaveOrUpdate(evnt); Session.Flush(); } trans.Commit(); } catch (Exception ex) { trans.Rollback(); lists[1] = new List <Customer>(); logger.Error("tmrAutomation_Elapsed - brochure requests follow up", ex); } } } // Digital Request Brochures Campaign if (campaigns[2].Started) { using (var trans = Session.BeginTransaction()) { try { var minDate = DateTime.Now.AddDays(-14).Date; var maxDate = DateTime.Now.AddDays(-1).DayEnd(); var events = Session.QueryOver <Event>().Where(ev => ev.EventType.ID == 42 && minDate <= ev.DateCreated && ev.DateCreated < maxDate && ev.EFollowUpCheck == false).List(); foreach (var evnt in events) { // check if customer was already emailed in the last 48 hours if (evnt.Customer.LastAutoEmail == null || evnt.Customer.LastAutoEmail.Value < now.AddDays(-2).Date) { var ev = evnt; if (!evnt.Customer.Quotes.Any(q => q.DateCreated >= ev.DateCreated && q.CreatedUser.IsWebsite) && !evnt.Customer.Orders.Any(o => o.DateCreated >= ev.DateCreated) && !evnt.Customer.Invoices.Any(i => i.DateCreated >= ev.DateCreated) && !evnt.Customer.RawCustomerEvents.Any(ce => ce.DateCreated >= ev.DateCreated && ce.EventType.ID == 2)) { evnt.Customer.LastAutoEmail = now; Session.SaveOrUpdate(evnt.Customer); lists[2].Add(evnt.Customer); } else { logger.WarnFormat("Digital Brochure Requests campaign - Customer: '{0}' Rejected due to existance of future web-quotes, orders or invoices", evnt.Customer.Code); } } else { logger.WarnFormat("Digital Brochure Requests campaign - Customer: '{0}' Rejected due to LastAutoEmail: '{1}'", evnt.Customer.Code, evnt.Customer.LastAutoEmail); } evnt.EFollowUpCheck = true; Session.SaveOrUpdate(evnt); Session.Flush(); } trans.Commit(); } catch (Exception ex) { trans.Rollback(); lists[2] = new List <Customer>(); logger.Error("tmrAutomation_Elapsed - digital brochure requests follow up", ex); } } } for (var i = 0; i < campaigns.Length; i++) { var campaign = campaigns[i]; var list = lists[i]; if (campaign != null) { var sentAddrs = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var strBody = new StringBuilder(1000); strBody.AppendLine("<div dir=\"ltr\">"); strBody.AppendLine(campaign.Body); strBody.AppendLine("</div>"); var bodyTemplate = strBody.ToString(); // send emails foreach (var customer in list) { try { var addr = customer.DefaultEmail ?? ""; addr = addr.Trim().ToLower(); if (String.IsNullOrEmpty(addr) || sentAddrs.Contains(addr) || unsubscribers.Contains(addr)) { logger.WarnFormat("Address: '{0}' is invalid or unsubscribed.", addr); continue; } sentAddrs.Add(addr); using (var mm = new MailMessage()) { mm.From = new MailAddress(campaign.Sender, campaign.SenderName); mm.To.Add(new MailAddress(addr)); mm.Bcc.Add("*****@*****.**"); mm.Subject = campaign.Subject; mm.IsBodyHtml = true; mm.Body = TemplateService.GetText(bodyTemplate, customer.DefaultContact); foreach (var sf in campaign.Files) { var ms = new MemoryStream(sf.Data.Length); ms.Write(sf.Data, 0, sf.Data.Length); ms.Seek(0, SeekOrigin.Begin); mm.Attachments.Add(new Attachment(ms, sf.FileName)); } emailManager.SendMessage(mm); } } catch (Exception ex) { logger.Warn("tmrAutomation_Elapsed - error sending campaign email " + ex.Message + "\n" + ex.StackTrace); } } } else { logger.Warn("tmrAutomation_Elapsed - campaign " + i + " not found"); } } } } catch (Exception ex) { logger.Error("tmrAutomation_Elapsed", ex); } finally { DisposeSession(); tmrAutomationSync = 0; } } }
/// <summary> /// Create an Atom entry used to create a new EmailCampaign /// </summary> /// <param name="emailCampaign">EmailCampaign to be created</param> /// <param name="authenticationData">Account Owner EmailCampaign resource</param> /// <param name="id">Account Owner EmailCampaign id - if its already created</param> /// <returns>Atom entry used to create new EmailCampaign /// </returns> private static StringBuilder CreateAtomEntry(EmailCampaign emailCampaign, AuthenticationData authenticationData, string id) { string atomId = string.IsNullOrEmpty(id) ? "0000000000000" : id; StringBuilder data = new StringBuilder(); data.Append("<?xml version='1.0' encoding='UTF-8'?>"); data.AppendFormat("<entry xmlns=\"{0}\">", AtomNamespace); if (atomId.Equals("0000000000000")) { data.AppendFormat("<link href=\"/ws/customers/{0}/{1}\" rel=\"{2}\" />", authenticationData.Username, authenticationData.CampaignsURI, EmailCampaignXmlAttributeValueEdit); data.AppendFormat("<id>http://api.constantcontact.com/ws/customers/{0}/{1}</id>", authenticationData.Username, authenticationData.CampaignsURI); } else { data.AppendFormat("<link href=\"/ws/customers/{0}/{1}/{3}\" rel=\"{2}\" />", authenticationData.Username, authenticationData.CampaignsURI, EmailCampaignXmlAttributeValueEdit, atomId); data.AppendFormat("<id>http://api.constantcontact.com/ws/customers/{0}/{1}/{2}</id>", authenticationData.Username, authenticationData.CampaignsURI, atomId); } data.AppendFormat("<title type=\"text\">{0}</title>", emailCampaign.Name); data.AppendFormat("<updated>{0}</updated>", DateTime.Now.ToString("o"));//yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z' data.AppendFormat("<author><name>{0}</name></author>", "Constant Contact"); data.Append("<content type=\"application/vnd.ctct+xml\">"); data.AppendFormat("<Campaign xmlns=\"{0}\" id=\"http://api.constantcontact.com/ws/customers/{1}/{2}/{3}\" >", ConstantNamespace, authenticationData.Username, authenticationData.CampaignsURI, atomId); data.AppendFormat("<Name>{0}</Name>", emailCampaign.Name); data.Append("<Status>Draft</Status>"); data.AppendFormat("<Date>{0}</Date>", emailCampaign.Date.ToString("o"));//yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z' if (!atomId.Equals("0000000000000")) { data.AppendFormat("<LastEditDate>{0}</LastEditDate>", emailCampaign.LastEditDate.ToString("o")); //data.AppendFormat("<NextRunDate>{0}</NextRunDate>", emailCampaign.NextRunDate.ToString("o")); data.AppendFormat("<Sent>{0}</Sent>", emailCampaign.Sent); data.AppendFormat("<Opens>{0}</Opens>", emailCampaign.Opens); data.AppendFormat("<Clicks>{0}</Clicks>", emailCampaign.Clicks); data.AppendFormat("<Bounces>{0}</Bounces>", emailCampaign.Bounces); data.AppendFormat("<Forwards>{0}</Forwards>", emailCampaign.Forwards); data.AppendFormat("<OptOuts>{0}</OptOuts>", emailCampaign.OptOuts); data.AppendFormat("<SpamReports>{0}</SpamReports>", emailCampaign.SpamReports); data.AppendFormat("<CampaignType>{0}</CampaignType>", emailCampaign.CampaignType); } data.AppendFormat("<Subject>{0}</Subject>", emailCampaign.Subject); data.AppendFormat("<FromName>{0}</FromName>", emailCampaign.FromName); data.AppendFormat("<ViewAsWebpage>{0}</ViewAsWebpage>", emailCampaign.ViewAsWebpage ? "YES" : "NO"); data.AppendFormat("<ViewAsWebpageLinkText>{0}</ViewAsWebpageLinkText>", emailCampaign.ViewAsWebpageLinkText); data.AppendFormat("<ViewAsWebpageText>{0}</ViewAsWebpageText>", emailCampaign.ViewAsWebpageText); data.AppendFormat("<PermissionReminder>{0}</PermissionReminder>", emailCampaign.PermissionReminder ? "YES" : "NO"); data.AppendFormat("<PermissionReminderText>{0}</PermissionReminderText>", emailCampaign.PermissionReminderText); data.AppendFormat("<GreetingSalutation>{0}</GreetingSalutation>", emailCampaign.GreetingSalutation); data.AppendFormat("<GreetingString>{0}</GreetingString>", emailCampaign.GreetingString); data.AppendFormat("<OrganizationName>{0}</OrganizationName>", emailCampaign.OrganizationName); data.AppendFormat("<OrganizationAddress1>{0}</OrganizationAddress1>", emailCampaign.OrganizationAddress1); data.AppendFormat("<OrganizationAddress2>{0}</OrganizationAddress2>", emailCampaign.OrganizationAddress2); data.AppendFormat("<OrganizationAddress3>{0}</OrganizationAddress3>", emailCampaign.OrganizationAddress3); data.AppendFormat("<OrganizationCity>{0}</OrganizationCity>", emailCampaign.OrganizationCity); data.AppendFormat("<OrganizationState>{0}</OrganizationState>", emailCampaign.OrganizationState); data.AppendFormat("<OrganizationInternationalState>{0}</OrganizationInternationalState>", emailCampaign.OrganizationInternationalState); data.AppendFormat("<OrganizationCountry>{0}</OrganizationCountry>", emailCampaign.OrganizationCountry); data.AppendFormat("<OrganizationPostalCode>{0}</OrganizationPostalCode>", emailCampaign.OrganizationPostalCode); data.AppendFormat("<IncludeForwardEmail>{0}</IncludeForwardEmail>", emailCampaign.IncludeForwardEmail ? "YES" : "NO"); data.AppendFormat("<ForwardEmailLinkText>{0}</ForwardEmailLinkText>", emailCampaign.ForwardEmailLinkText); data.AppendFormat("<IncludeSubscribeLink>{0}</IncludeSubscribeLink>", emailCampaign.IncludeSubscribeLink ? "YES" : "NO"); data.AppendFormat("<SubscribeLinkText>{0}</SubscribeLinkText>", emailCampaign.SubscribeLinkText); // These nodes are currently only supported in CUSTOM campaign types if (emailCampaign.CampaignType == CampaignType.CUSTOM) { data.AppendFormat("<GreetingName>{0}</GreetingName>", emailCampaign.GreetingName); data.AppendFormat("<EmailContentFormat>{0}</EmailContentFormat>", emailCampaign.EmailContentFormat); data.AppendFormat("<EmailContent>{0}</EmailContent>", emailCampaign.EmailContentFormat.Equals("HTML") ? emailCampaign.Content : emailCampaign.XContent); data.AppendFormat("<EmailTextContent>{0}</EmailTextContent>", emailCampaign.TextContent); data.AppendFormat("<StyleSheet>{0}</StyleSheet>", emailCampaign.StyleSheet); } data.Append("<ContactLists>"); if (emailCampaign.ContactLists.Count > 0) { foreach (var contact in emailCampaign.ContactLists) { data.AppendFormat("<ContactList id=\"http://api.constantcontact.com/ws/customers/{0}/lists/{1}\">", authenticationData.Username, contact.Id); data.AppendFormat("<link xmlns=\"{0}\" href=\"/ws/customers/{1}/lists/{2}\" rel=\"self\" />", AtomNamespace, authenticationData.Username, contact.Id); data.Append("</ContactList>"); } } data.Append("</ContactLists>"); data.Append("<FromEmail>"); data.AppendFormat("<Email id=\"http://api.constantcontact.com/ws/customers/{0}/settings/emailaddresses/{1}\">", authenticationData.Username, emailCampaign.FromEmailID); data.AppendFormat("<link xmlns=\"{0}\" href=\"/ws/customers/{1}/settings/emailaddresses/{2}\" rel=\"self\" />", AtomNamespace, authenticationData.Username, emailCampaign.FromEmailID); data.Append("</Email>"); data.AppendFormat("<EmailAddress>{0}</EmailAddress>", emailCampaign.FromEmail); data.Append("</FromEmail>"); data.Append("<ReplyToEmail>"); data.AppendFormat("<Email id=\"http://api.constantcontact.com/ws/customers/{0}/settings/emailaddresses/{1}\">", authenticationData.Username, emailCampaign.ReplyToEmailID); data.AppendFormat("<link xmlns=\"{0}\" href=\"/ws/customers/{1}/settings/emailaddresses/{2}\" rel=\"self\" />", AtomNamespace, authenticationData.Username, emailCampaign.ReplyToEmailID); data.Append("</Email>"); data.AppendFormat("<EmailAddress>{0}</EmailAddress>", emailCampaign.ReplyToEmail); data.Append("</ReplyToEmail>"); data.Append("</Campaign></content><source>"); data.AppendFormat("<id>http://api.constantcontact.com/ws/customers/{0}/campaigns</id>", authenticationData.Username); data.AppendFormat("<title type=\"text\">Campaigns for customer: {0}</title>", authenticationData.Username); data.AppendFormat("<link href=\"campaigns\" /><link href=\"campaigns\" rel=\"self\" /><author><name>{0}</name></author><updated>{1}</updated></source></entry>", authenticationData.Username, DateTime.Now.ToString("o"));//yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z' return(data); }
protected override void Initialize() { base.Initialize(); manager = new EmailCampaignManager(mockUnitOfWork.Object, mockMapper.Object, mockNotification.Object); Emails = new List <Email>(); Emails.Add( new Email() { Id = 10, EmailAddress = "*****@*****.**" }); Emails.Add( new Email() { Id = 11, EmailAddress = "*****@*****.**" }); recipientViewModels = new List <EmailRecipientViewModel>(); recipientViewModels.Add(new EmailRecipientViewModel() { EmailAddress = "*****@*****.**", BirthDate = DateTime.Now, Gender = "Male", KeyWords = "add", Name = "John", Surname = "Snow", Priority = "Low", Id = 0, CompanyId = 0 }); emailCampaignViewModel = new EmailCampaignViewModel() { Id = 0, EmailAddress = "*****@*****.**", Description = "test", Message = "test", Name = "test", SendingTime = DateTime.Now, UserId = "1cf1c047-9687-4663-be13-09e4a99f35f3", RecipientsCount = 1, EmailId = 0 }; emailRecipient = new EmailRecipient() { BirthDate = DateTime.Now, Gender = 0, IsSend = 0, KeyWords = "test", Name = "test", Priority = "Low", Surname = "test" }; emailCampaign = new EmailCampaign() { Name = "test", Description = "test", Message = "test", SendingTime = DateTime.Now }; TestContext.WriteLine("Overrided"); }
public static Customer WithEmailCampaign(this Customer customer, EmailCampaign emailCampaign) { Assert.Equal(emailCampaign, customer.EmailingSettings.EmailCampaign); return(customer); }