Esempio n. 1
0
        public Message AddOrEdit(NewsletterMail newsletterMail)
        {
            var message = new Message();
            var ID      = newsletterMail.NewsletterMailId;
            int result  = _iNewsletterMailRepository.AddOrEdit(newsletterMail);

            try
            {
                if (result > 0)
                {
                    if (Convert.ToInt32(ID) > 0)
                    {
                        message = Message.SetMessages.SetSuccessMessage("Submission Updated Successfully!");
                    }
                    else
                    {
                        message = Message.SetMessages.SetSuccessMessage("Submission Successful!");
                    }
                }
                else
                {
                    message = Message.SetMessages.SetErrorMessage("Could not be submitted!");
                }
            }
            catch (Exception e)
            {
                message = Message.SetMessages.SetWarningMessage(e.Message.ToString());
            }

            return(message);
        }
Esempio n. 2
0
        public ActionResult AddOrEdit(int id = 0)
        {
            NewsletterMail newsletterMail = new NewsletterMail();

            if (id != 0)
            {
                newsletterMail = _iNewsletterMailManager.GetANewsletterMail(id);
            }
            return(View(newsletterMail));
        }
Esempio n. 3
0
        /// <summary>
        /// Remove NewsletterMail.
        /// </summary>
        /// <param name="request">The NewsletterMail Request Pivot to remove.</param>
        public void DeleteNewsletterMail(NewsletterMailRequestPivot request)
        {
            if (request?.NewsletterMailPivot == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            NewsletterMail newsletterMail = _unitOfWork.NewsletterMailRepository.GetById(request.NewsletterMailPivot.NewsletterMailId);

            _unitOfWork.NewsletterMailRepository.Delete(newsletterMail);
            _unitOfWork.Save();
        }
Esempio n. 4
0
        /// <summary>
        /// Create new NewsletterMail.
        /// </summary>
        /// <param name="request">The NewsletterMail Request Pivot to add.</param>
        /// <returns>NewsletterMail Response Pivot created.</returns>
        public NewsletterMailResponsePivot CreateNewsletterMail(NewsletterMailRequestPivot request)
        {
            if (request?.NewsletterMailPivot == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            NewsletterMail newsletterMail = request.NewsletterMailPivot.ToEntity();

            _unitOfWork.NewsletterMailRepository.Insert(newsletterMail);
            _unitOfWork.Save();
            return(new NewsletterMailResponsePivot()
            {
                NewsletterMailPivot = newsletterMail.ToPivot()
            });
        }
Esempio n. 5
0
        public int AddOrEdit(NewsletterMail newsletterMail)
        {
            if (newsletterMail.NewsletterMailId == 0)
            {
                newsletterMail.CreatedBy   = "Ayesha";
                newsletterMail.CreatedDate = DateTime.Now;
                _dbContext.NewsletterMails.Add(newsletterMail);
            }
            else
            {
                newsletterMail.UpdatedBy               = "Ayesha";
                newsletterMail.UpdatedDate             = DateTime.Now;
                _dbContext.Entry(newsletterMail).State = EntityState.Modified;
            }

            return(_dbContext.SaveChanges());
        }
Esempio n. 6
0
        public IActionResult Index([FromForm] NewsletterMail newsletter)
        {
            if (ModelState.IsValid)
            {
                _nRepo.Register(newsletter);

                TempData["NEWS_E"] = "E";

                _mSender.SendNewsletter(newsletter);

                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                return(View());
            }
        }
Esempio n. 7
0
        public ActionResult AddOrEdit(NewsletterMail newsletterMail, HttpPostedFileBase uploadedFile)
        {
            var allowedExtensions = new[] { ".GIF", ".PNG", ".JPG", ".JPEG" };

            if (uploadedFile != null)
            {
                var ext = Path.GetExtension(uploadedFile.FileName);
                if (allowedExtensions.Contains(ext.ToUpper())) //check what type of extension
                {
                    string myfile    = "AttachFile" + DateTime.Now.ToString("ddMMyyhhmm") + ext;
                    var    path      = ConfigurationManager.AppSettings["AttachFile"];
                    var    finalpath = Path.Combine(Server.MapPath(path), myfile);
                    if (newsletterMail.NewsletterMailId > 0)
                    {
                        var imageName    = newsletterMail.AttachFile;
                        var existingpath = ConfigurationManager.AppSettings["AttachFile"];
                        if (System.IO.File.Exists(Server.MapPath(existingpath + imageName)))
                        {
                            System.IO.File.Delete(Server.MapPath(existingpath + imageName));
                        }
                    }
                    newsletterMail.AttachFile = myfile;
                    uploadedFile.SaveAs(finalpath);
                }
                else
                {
                    Message message = new Message();
                    message.ReturnMessage = "Choose only Image File!";
                    message.MessageType   = MessageTypes.Information;
                }
            }
            else
            {
                Message message = new Message();
                message.ReturnMessage = "Select an Image!";
                message.MessageType   = MessageTypes.Information;
            }
            var data = _iNewsletterMailManager.AddOrEdit(newsletterMail);

            return(Json(new { messageType = data.MessageType, message = data.ReturnMessage, html = GlobalClass.RenderRazorViewToString(this, "ViewAll", _iNewsletterMailManager.GetAllNewsletterMail()) }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 8
0
        public void SendNewsletter(NewsletterMail contato)
        {
            string corpoMsg = string.Format("<h2>Contato - LojaVirtual</h2>" +
                                            "<b>E-mail: </b> {0} <br />" +
                                            "<p>Você foi inscrito na nossa Newsletter com sucesso! <br/> A partir de agora você ira receber emails com promoções sobre a nossa loja!</p>" +
                                            "<br /> E-mail enviado automaticamente do site LojaVirtual.",
                                            contato.Email
                                            );


            /*
             * MailMessage -> Construir a mensagem
             */
            MailMessage mensagem = new MailMessage();

            mensagem.From = new MailAddress(_config.GetValue <string>("Email:EmailCredential"));
            mensagem.To.Add(contato.Email);
            mensagem.Subject    = "Contato - Registro Newsletter" + contato.Email;
            mensagem.Body       = corpoMsg;
            mensagem.IsBodyHtml = true;

            //Enviar Mensagem via SMTP
            _smtp.Send(mensagem);
        }
 public void Register(NewsletterMail data)
 {
     _db.Add(data);
     _db.SaveChanges();
 }
Esempio n. 10
0
        private static void CheckOneBlog(string readerFeedUrl, int personId)
        {
            try
            {
                Person sender = Person.FromIdentity(personId);

                string senderName    = sender.Name + " (Piratpartiet)";
                string senderAddress = sender.PartyEmail;


                if (personId == 5)
                {
                    senderName = "=?utf-8?Q?Christian_Engstr=C3=B6m_(Piratpartiet)?="; // compensate for Mono bug
                }
                if (personId == 1)
                {
                    senderAddress = "*****@*****.**";
                }

                RssReader reader     = new RssReader(readerFeedUrl);
                People    recipients = null;

                DateTime highWaterMark  = DateTime.MinValue;
                string   persistenceKey = "Newsletter-Highwater-" + personId.ToString();

                string highWaterMarkString = Persistence.Key[persistenceKey];

                try
                {
                    highWaterMark = DateTime.Parse(highWaterMarkString);
                }
                catch (FormatException)
                {
                    highWaterMark = DateTime.MinValue;
                }
                catch (Exception e)
                {
                    throw new ReaderException("feed:" + readerFeedUrl, e);
                }

                try
                {
                    Rss rss = reader.Read();

                    // TODO: Read the high water mark from db

                    foreach (RssChannelItem item in rss.Channel.Items)
                    {
                        // Ignore any items older than the highwater mark.

                        if (item.PubDate < highWaterMark)
                        {
                            continue;
                        }

                        // For each item, look for the "Nyhetsbrev" category.

                        bool publish = false;

                        foreach (RssCategory category in item.Categories)
                        {
                            if (category.Name.ToLowerInvariant() == "nyhetsbrev")
                            {
                                publish = true;
                            }
                        }


                        if (publish)
                        {
                            // Set highwater datetime mark. We do this first as a defense against mail floods, should something go wrong.

                            Persistence.Key[persistenceKey] = item.PubDate.AddMinutes(5).ToString();

                            // Verify that it was written correctly to database. This is defensive programming to avoid a mail flood.

                            if (DateTime.Parse(Persistence.Key[persistenceKey]) < item.PubDate)
                            {
                                throw new Exception(
                                          "Unable to commit new highwater mark to database in NewsletterChecker.Run()");
                            }

                            bool testMode = false;

                            if (item.Title.ToLower().Contains("test"))
                            {
                                // Newsletter blog entry contains "test" in title -> testmode
                                testMode = true;
                            }

                            // Post to forum

                            string forumText   = Blog2Forum(item.Content);
                            string mailText    = Blog2Mail(item.Content);
                            int    forumPostId = 0;
                            try
                            {
                                forumPostId = SwedishForumDatabase.GetDatabase().CreateNewPost(
                                    testMode ? ForumIdTestPost : ForumIdNewsletter, sender,
                                    "Nyhetsbrev " + DateTime.Today.ToString("yyyy-MM-dd"),
                                    item.Title, forumText);
                            }
                            catch (Exception ex)
                            {
                                if (!System.Diagnostics.Debugger.IsAttached)
                                {   // ignore when debugging
                                    throw ex;
                                }
                            }


                            // Establish people to send to, if not already done.

                            if (recipients == null || recipients.Count == 1)
                            {
                                recipients = People.FromNewsletterFeed(NewsletterFeed.TypeID.ChairmanBlog);
                            }

                            /*
                             *  Disabled sending to activists -- this was done leading up to the election in 2009
                             */
                            // Add activists (HACK)
                            // Should probably be better to select by organization, not geography.

                            /*
                             * People activists = Activists.FromGeography(Country.FromCode("SE").Geography).People;
                             *
                             * recipients = recipients.LogicalOr(activists);*/


                            // OVERRIDE: If this is a TEST newsletter, send ONLY to the originator

                            if (testMode)
                            {
                                recipients  = People.FromSingle(sender);
                                item.Title += " [TEST MODE]";
                            }

                            //TODO: hardcoded Org & geo ... using PP & World
                            Organization org = Organization.PPSE;
                            Geography    geo = Geography.Root;


                            NewsletterMail newslettermail = new NewsletterMail();

                            newslettermail.pSubject      = item.Title;
                            newslettermail.pDate         = DateTime.Now;
                            newslettermail.pForumPostUrl =
                                String.Format("http://vbulletin.piratpartiet.se/showthread.php?t={0}", forumPostId);
                            newslettermail.pBodyContent = Blog2Mail(item.Content);
                            newslettermail.pOrgName     = org.MailPrefixInherited;


                            OutboundMail newMail = newslettermail.CreateOutboundMail(sender, OutboundMail.PriorityLow, org, geo);

                            int recipientCount = 0;
                            foreach (Person recipient in recipients)
                            {
                                if (!Formatting.ValidateEmailFormat(recipient.Mail) ||
                                    recipient.MailUnreachable ||
                                    recipient.NeverMail)
                                {
                                    continue;
                                }
                                ++recipientCount;
                                newMail.AddRecipient(recipient, false);
                            }

                            newMail.SetRecipientCount(recipientCount);
                            newMail.SetResolved();
                            newMail.SetReadyForPickup();
                        }
                    }
                }
                finally
                {
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                lock (feedErrorSignaled)
                {
                    if (!feedErrorSignaled.ContainsKey(readerFeedUrl) || feedErrorSignaled[readerFeedUrl].AddMinutes(60) < DateTime.Now)
                    {
                        feedErrorSignaled[readerFeedUrl] = DateTime.Now;
                        throw new ReaderException("NewsletterChecker got error " + ex.Message + "\n when checking feed:" + readerFeedUrl + "\n(feed will be continually checked, bu will not signal error again for an hour)", ex);
                    }
                }
            }
        }
        public ActionResult ViewAll(FormCollection formCollection, int NewsletterMailId, int SmtpHostId)
        {
            MailMessage mailMessage = new MailMessage();

            SentMailLog sentMailLog = new SentMailLog();
            //List<SentMailLog> sentMailLogList= new List<SentMailLog>();
            //var newsLetterMailList = _iNewsletterMailManager.GetAllNewsletterMail().Select(x => new
            //{
            //    x.NewsletterMailId,
            //    x.Subject
            //}).ToList();

            //ViewBag.NewsletterMailId = new SelectList(newsLetterMailList, "NewsletterMailId", "Subject");
            NewsletterMail newsletterMail = _iNewsletterMailManager.GetANewsletterMail(NewsletterMailId);
            SmtpHost       smtpHost       = _iSmtpHostManager.GetASmtpHost(SmtpHostId);

            string[] ids = formCollection["NewsletterSubscriberId"].Split(new char[] { ',' });
            foreach (string id in ids)
            {
                var newsletterSubscriber = _iNewsletterSubscriberManager.GetANewsletterSubscriber(int.Parse(id));
                if (newsletterSubscriber.IsActive == true)
                {
                    mailMessage.To.Add(new MailAddress(newsletterSubscriber.NewsletterSubscriberEmail));

                    //mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]);
                    mailMessage.From       = new MailAddress(smtpHost.UserName);
                    mailMessage.Subject    = newsletterMail.Subject;
                    mailMessage.IsBodyHtml = true;
                    mailMessage.Body       = newsletterMail.Body;

                    var    allowedExtensions = new[] { ".GIF", ".PNG", ".JPG", ".JPEG" };
                    string myfile            = Path.GetFileName(newsletterMail.AttachFile);

                    var        path = ConfigurationManager.AppSettings["AttachFile"];
                    var        file = Path.Combine(Server.MapPath(path), myfile);
                    Attachment data = new Attachment(file);

                    ContentDisposition disposition = data.ContentDisposition;
                    disposition.CreationDate     = System.IO.File.GetCreationTime(file);
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
                    disposition.ReadDate         = System.IO.File.GetLastAccessTime(file);

                    mailMessage.Attachments.Add(data);
                    //mailMessage.DeliveryNotificationOptions= DeliveryNotificationOptions.OnSuccess;
                    SmtpClient client = new SmtpClient();
                    //client.Host = ConfigurationManager.AppSettings["Host"];
                    client.Host = smtpHost.HostType.HostName;
                    //client.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
                    client.EnableSsl = smtpHost.HostType.EnableSsl;
                    System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                    //NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
                    NetworkCred.UserName = smtpHost.UserName;
                    //NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
                    NetworkCred.Password = smtpHost.Password;
                    //string encryptedPassword = smtpHost.Password;
                    //string password = new EncryptionDecryption().Decrypt(smtpHost.UserName, encryptedPassword);

                    client.UseDefaultCredentials = true;
                    client.Credentials           = NetworkCred;
                    //client.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
                    client.Port = int.Parse(smtpHost.HostType.PortNumber);


                    try
                    {
                        client.Send(mailMessage);
                        ViewBag.Result = "Mail Sent";
                        //if (ViewBag.Result==null)
                        //{
                        //    ViewBag.Result="Mail not sent" + newsletterSubscriber.NewsletterSubscriberEmail;
                        //}
                        sentMailLog.NewsletterSubscriberEmailId = newsletterSubscriber.NewsletterSubscriberEmail;
                        sentMailLog.NewsletterMailSubject       = newsletterMail.Subject;
                        sentMailLog.CreatedBy   = 1;
                        sentMailLog.CreatedDate = DateTime.Now;
                        sentMailLog.IsSent      = true;
                        AlphasoftWebsiteContext db = new AlphasoftWebsiteContext();
                        db.SentMailLogs.Add(sentMailLog);
                        db.SaveChanges();
                    }
                    catch (SmtpFailedRecipientException ex)
                    {
                        ViewBag.Result = ex.Message;
                    }
                }
            }
            return(RedirectToAction("Index"));
        }