示例#1
0
        public ProjectWorkflowENT InsertRecordInEmailHistory(ProjectWorkflowENT Param)
        {
            if (Param.FileName == null)
            {
                Param.FileName = "";
            }
            NbkDbEntities dbcontext = new NbkDbEntities();
            EmailHistory  Data      = new EmailHistory
            {
                ProjectId      = Param.ProjectId,
                WorkflowId     = Param.WorkflowId,
                WorkflowStepId = Param.WorkflowStepId,
                //PartyId =
                Subject   = Param.EmailSubject,
                ToEmail   = Param.EmailTo,
                FromEmail = Param.EmailFrom,
                Message   = Param.EmailContent,
                FileName  = Param.FileName.ToString(),
                Date      = DateTime.Now
                            //PartyTypeId =
                            //IsEmail =
            };

            dbcontext.EmailHistory.Add(Data);
            dbcontext.SaveChanges();
            Param.EmailHistoryId = Data.Id;
            return(Param);
        }
示例#2
0
 /// <summary>
 /// populates a EmailHistory with its child entities
 /// </summary>
 /// <param name="emailHistory"></param>
 /// <param name="fillChilds"></param>
 private void FillEmailHistoryWithChilds(EmailHistory emailHistoryObject, bool fillChilds)
 {
     // populate child data for a emailHistoryObject
     if (emailHistoryObject != null)
     {
     }
 }
        public void SendNotification()
        {
            IEnumerable <ContactDTO> contacts = _reader.Read();

            foreach (var contact in contacts)
            {
                _reminder.RegistrationDate = contact.ConvertRegistrationToDate();
                if (_reminder.HasExpiryDateApproaching())
                {
                    if (_repo.IsMailSentToday(contact.Id))
                    {
                        continue;
                    }

                    //_emailService.SendEmail(contact.Email,
                    //"Your IMG registration is expiring " +
                    //_formatter.GetEmailSubject(_reminder), _formatter.GenerateHtml(contact, _reminder));

                    _emailService.SendEmail(contact.Email,
                                            " Membership Reminder from the IMG ", _formatter.GenerateHtml(contact, _reminder));



                    var history = new EmailHistory()
                    {
                        ContactID     = contact.Id,
                        LastEmailSent = DateTime.Today,
                        Name          = contact.Name
                    };
                    history.TotalReminders += 1;
                    _repo.Add(history);
                }
            }
        }
示例#4
0
        /// <summary>
        /// Retrieves list of EmailHistory objects from SqlCommand, after database query
        /// number of rows retrieved and returned depends upon the rows field value
        /// </summary>
        /// <param name="cmd">The command object to use for query</param>
        /// <param name="rows">Number of rows to process</param>
        /// <returns>A list of EmailHistory objects</returns>
        private EmailHistoryList GetList(SqlCommand cmd, long rows)
        {
            // Select multiple records
            SqlDataReader reader;
            long          result = SelectRecords(cmd, out reader);

            //EmailHistory list
            EmailHistoryList list = new EmailHistoryList();

            using ( reader )
            {
                // Read rows until end of result or number of rows specified is reached
                while (reader.Read() && rows-- != 0)
                {
                    EmailHistory emailHistoryObject = new EmailHistory();
                    FillObject(emailHistoryObject, reader);

                    list.Add(emailHistoryObject);
                }

                // Close the reader in order to receive output parameters
                // Output parameters are not available until reader is closed.
                reader.Close();
            }

            return(list);
        }
        /// <summary>
        /// Sends the booking delayed emails.
        /// </summary>
        /// <param name="dateToConsider">The date to consider.</param>
        public static void SendBookingDelayedEmails(DateTime dateToConsider)
        {
            using (StageBitzDB dataContext = new StageBitzDB())
            {
                InventoryBL inventoryBL        = new InventoryBL(dataContext);
                int         delayedEmailCodeId = Utils.GetCodeIdByCodeValue("EmailTemplateTypeCode", "BOOKINGDELAYED");
                string      userWebUrl         = Utils.GetSystemValue("SBUserWebURL");

                var delayedBookings = (from ibs in dataContext.ItemBookings.Where(ibs => dataContext.IsItemBookingDelayedByDate(ibs.ItemBookingId, dateToConsider))
                                       from eh in dataContext.EmailHistories.Where(eh => ibs.ItemBookingId == eh.RelatedId &&
                                                                                   eh.RelatedTable == "ItemBooking" && eh.EmailTemplateTypeCodeId == delayedEmailCodeId).DefaultIfEmpty().Take(1)
                                       join b in dataContext.Bookings on ibs.BookingId equals b.BookingId
                                       from ib in dataContext.ItemBriefs.Where(ib => ib.ItemBriefId == ibs.RelatedId && b.RelatedTable == "Project").DefaultIfEmpty().Take(1)
                                       from npb in dataContext.NonProjectBookings.Where(npb => npb.NonProjectBookingId == b.RelatedId && b.RelatedTable == "NonProject").DefaultIfEmpty().Take(1)
                                       join i in dataContext.Items on ibs.ItemId equals i.ItemId
                                       join u in dataContext.Users on ibs.CreatedBy equals u.UserId
                                       where eh == null && ibs.IsActive && i.CompanyId.HasValue
                                       select new
                {
                    ItemBrief = ib,
                    NonProjectBooking = npb,
                    CompanyId = i.CompanyId.Value,
                    CreatedBy = u,
                    ItemBooking = ibs,
                    Item = i
                }).ToList();

                foreach (var delayedBooking in delayedBookings)
                {
                    User locationManager = inventoryBL.GetContactBookingManager(delayedBooking.Item.CompanyId.Value, delayedBooking.Item.LocationId);
                    if (locationManager != null)
                    {
                        Data.EmailHistory emailHistory = new EmailHistory
                        {
                            EmailTemplateTypeCodeId = delayedEmailCodeId,
                            RelatedId    = delayedBooking.ItemBooking.ItemBookingId,
                            RelatedTable = "ItemBooking",
                            CreatedDate  = Utils.Now
                        };

                        dataContext.EmailHistories.AddObject(emailHistory);
                        dataContext.SaveChanges();
                        string inventoryManagerName = string.Concat(locationManager.FirstName, " ", locationManager.LastName);

                        if (delayedBooking.ItemBrief != null)
                        {
                            string url = string.Format("{0}/ItemBrief/ItemBriefDetails.aspx?ItemBriefId={1}&TabId=3", userWebUrl, delayedBooking.ItemBrief.ItemBriefId);
                            EmailSender.SendBookingDelayedEmail(delayedBooking.CreatedBy.Email1, delayedBooking.CreatedBy.FirstName, delayedBooking.ItemBrief.Name,
                                                                url, inventoryManagerName, locationManager.Email1);
                        }
                        else
                        {
                            EmailSender.SendBookingDelayedEmailForNonProject(delayedBooking.CreatedBy.Email1, delayedBooking.CreatedBy.FirstName, delayedBooking.NonProjectBooking.Name,
                                                                             inventoryManagerName, locationManager.Email1);
                        }
                    }
                }
            }
        }
示例#6
0
        /// <summary>
        /// Update EmailHistory Object.
        /// Data manipulation processing for: new, deleted, updated EmailHistory
        /// </summary>
        /// <param name="emailHistoryObject"></param>
        /// <returns></returns>
        public bool Update(EmailHistory emailHistoryObject)
        {
            bool success = false;

            success = UpdateBase(emailHistoryObject);

            return(success);
        }
示例#7
0
        protected void SaveHistory <TModel>(
            bool mailWasSentSuccessfully,
            string toName, string toEmail,
            string subject,
            TModel model,
            string fromName          = null, string fromEmail = null,
            List <MailAddress> cced  = null,
            List <MailAddress> bcced = null)
        {
            string body = this.TemplateProvider.GetTemplate <TModel>().TransformTemplate(model), message = body;

            if (message != null)
            {
                message = Regex.Replace(message, "<[^>]*(>|$)", string.Empty);
                message = message.Replace("\r\n", "\n").Replace("\r", "\n").Replace("&nbsp;", " ").Replace("&#39;", @"'");
                message = Regex.Replace(message, @"[ ]{2,}", " ");
                message = message.Replace("\n ", "\n");
                message = Regex.Replace(message, @"[\n]{2,}", "\n");
                message = message.Replace("Enriching online interaction for meetings, training and education on Adobe Connect", string.Empty);
                message = message.TrimStart("\n".ToCharArray());
            }

            var emailHistory = new EmailHistory
            {
                SentTo       = toEmail,
                SentToName   = toName,
                SentFrom     = fromEmail,
                SentFromName = fromName,
                Date         = DateTime.Now,
                SentBcc      =
                    bcced != null
                        ? bcced.Select(ma => ma.Address)
                    .Aggregate((a1, a2) => a1 + ";" + a2)
                        : null,
                SentCc =
                    cced != null
                        ? cced.Select(ma => ma.Address)
                    .Aggregate((a1, a2) => a1 + ";" + a2)
                        : null,
                Subject = subject,
                User    = UserModel.GetOneByEmail(toEmail).Value,
                Body    = body,
                Message = message,
                Status  = mailWasSentSuccessfully ? EmailHistory.StatusSent : EmailHistory.StatusFailed,
            };

            this.EmailHistoryModel.RegisterSave(emailHistory, true);

            if (!mailWasSentSuccessfully)
            {
                Logger.ErrorFormat("[BaseService.SaveHistory] '{0}' mail to '{1}' has not been sent.", subject, toEmail);

                var error = new Error {
                    errorCode = 201, errorMessage = "Email has not been sent."
                };
                throw new FaultException <Error>(error, error.errorMessage);
            }
        }
示例#8
0
        public async Task AddMessage(string email, int templateId, string subject, string body)
        {
            var template = await _context.Templates.SingleOrDefaultAsync(x => x.Id == templateId);

            var historyEntity = new EmailHistory(email, subject, body, DateTime.Now, template);
            await _context.AddAsync(historyEntity);

            await _context.SaveChangesAsync();
        }
示例#9
0
        public void MailNotSentForThisEntry()
        {
            EmailHistoryRepository manager = new EmailHistoryRepository();
            var contact = new EmailHistory()
            {
                LastEmailSent = DateTime.Today,
                ContactID     = "AB-3215"
            };

            Assert.IsTrue(!manager.IsMailSentToday(contact.ContactID));
        }
        /// <summary>
        /// Save email history
        /// </summary>
        /// <param name="familyMemberId">Family member identifier</param>
        /// <param name="emailType">Email template type</param>
        public void SaveEmailHistory(int familyMemberId, EmailType emailType)
        {
            var emailHistory = new EmailHistory
            {
                FamilyMemberID = familyMemberId,
                EmailType      = emailType,
                TriggeredOn    = DateTime.UtcNow
            };

            Repository.Insert(emailHistory);
        }
示例#11
0
        public async Task Then_Do_Not_Update_Email_History_If_PayLoad_Notification_Id_Is_Null(
            string status,
            MatchingDbContext dbContext,
            [Frozen] Domain.Models.Opportunity opportunity,
            [Frozen] Domain.Models.Provider provider,
            [Frozen] Domain.Models.ProviderVenue venue,
            [Frozen] EmailHistory emailHistory,
            [Frozen] BackgroundProcessHistory backgroundProcessHistory,
            IMessageQueueService messageQueueService,
            EmailDeliveryStatusPayLoad payload,
            MatchingConfiguration configuration,
            ILogger <OpportunityRepository> opportunityRepoLogger,
            ILogger <GenericRepository <EmailTemplate> > emailTemplateLogger,
            ILogger <GenericRepository <EmailHistory> > emailHistoryLogger,
            ILogger <GenericRepository <FunctionLog> > functionLogLogger,
            ILogger <Application.Services.EmailDeliveryStatusService> emailDeliveryServiceStatusLogger,
            ILogger <EmailService> emailServiceLogger,
            IAsyncNotificationClient notificationClient
            )
        {
            //Arrange
            await DataBuilder.SetTestData(dbContext, provider, venue, opportunity, backgroundProcessHistory);

            dbContext.Add(emailHistory);
            await dbContext.SaveChangesAsync();

            payload.Status = status;
            payload.Id     = Guid.Empty;

            var sut = SutSetUp(dbContext, opportunityRepoLogger, emailTemplateLogger, emailHistoryLogger, functionLogLogger,
                               emailDeliveryServiceStatusLogger, emailServiceLogger, notificationClient, configuration, messageQueueService);

            var serializedPayLoad = JsonConvert.SerializeObject(payload);

            //Act
            await sut.HandleEmailDeliveryStatusAsync(serializedPayLoad);

            //Assert
            var data = dbContext.EmailHistory.FirstOrDefault(em => em.NotificationId == payload.Id);

            data.Should().BeNull();

            var existingData = dbContext.EmailHistory.Where(history => history.OpportunityId == opportunity.Id).ToList();

            existingData.Select(history => history.ModifiedBy).Should().Equal(new List <string> {
                null, null
            });
            existingData.Select(history => history.ModifiedOn).Should().Equal(new List <string> {
                null, null
            });

            await messageQueueService.DidNotReceive().PushEmailDeliveryStatusMessageAsync(Arg.Any <SendEmailDeliveryStatus>());
        }
示例#12
0
        private void SaveHistory <TModel>(string toName, User user, string subject, TModel model, string fromName = null, string fromEmail = null, List <MailAddress> cced = null, List <MailAddress> bcced = null)
        {
            try
            {
                string body = this.TemplateProvider.GetTemplate <TModel>().TransformTemplate(model), message = body;
                if (message != null)
                {
                    message = Regex.Replace(message, "<[^>]*(>|$)", "");
                    message = message.Replace("\r\n", "\n")
                              .Replace("\r", "\n")
                              .Replace("&nbsp;", " ")
                              .Replace("&#39;", @"'");
                    message = Regex.Replace(message, @"[ ]{2,}", " ");
                    message = message.Replace("\n ", "\n");
                    message = Regex.Replace(message, @"[\n]{2,}", "\n");
                    while (message.StartsWith("\n"))
                    {
                        message = message.Remove(0, 1);
                    }
                }

                var emailHistory = new EmailHistory()
                {
                    SentTo       = user.Email,
                    SentToName   = toName,
                    SentFrom     = fromEmail,
                    SentFromName = fromName,
                    Date         = DateTime.Now,
                    SentBcc      =
                        bcced != null
                                               ? bcced.Select(ma => ma.Address)
                        .Aggregate((a1, a2) => a1 + ";" + a2)
                                               : null,
                    SentCc =
                        cced != null
                                               ? cced.Select(ma => ma.Address)
                        .Aggregate((a1, a2) => a1 + ";" + a2)
                                               : null,
                    Subject = subject,
                    User    = user,
                    Body    = body,
                    Message = message
                };

                this.EmailHistoryModel.RegisterSave(emailHistory, true);
            }
            catch (Exception e)
            {
                Logger.Error(e.StackTrace);
                throw;
            }
        }
示例#13
0
    public static void sendEmail(string emails, string body, string subject, int IdTask, int IdProject, int IdPopupLoad, bool SaveInHystory = false, int IdForm = 0, bool IsBodyHtml = false)
    {
        if (SaveInHystory)
        {
            string EMAIL_COPY = setting("EMAIL_COPY", IdTask);
            string from       = setting("EMAIL_FROM", IdTask);

            PopupLoadContext db = new PopupLoadContext();
            EmailHistory     eh = new EmailHistory()
            {
                Body           = body,
                Copy           = EMAIL_COPY,
                From           = from,
                Subject        = subject,
                To             = emails,
                DTCreated      = DateTime.Now,
                IdType         = 1,
                MessageArrived = "",
                MessageID      = "",
                ParentID       = 0,
                IdTask         = IdTask,
                IdProject      = IdProject,
                IdPopupLoad    = IdPopupLoad,
                IdForm         = IdForm
            };
            db.EmailHistorys.Add(eh);
            db.SaveChanges();
            subject    = "[" + eh.Id + "] " + subject;
            eh.Subject = subject;
            db.SaveChanges();
        }

        string className = "BaseSendEmail_" + IdForm;

        //string className = "BaseSendEmail" ;
        //Response.Write(className);

        System.Type t = null;
        try { t = System.Web.Compilation.BuildManager.GetType(className, true); }
        catch (Exception e) { };

        if (t != null)
        {
            var senderEmail = (BaseSendEmail)Activator.CreateInstance(t);
            senderEmail.send(emails, body, subject, IdTask, SaveInHystory, IdForm, IsBodyHtml);
        }
        else
        {
            var senderEmail = new BaseSendEmail();
            senderEmail.send(emails, body, subject, IdTask, SaveInHystory, IdForm, IsBodyHtml);
        }
    }
        public async Task Then_Send_Email_And_Save_Email_History(
            MatchingConfiguration configuration,
            [Frozen] MatchingDbContext dbContext,
            IAsyncNotificationClient notificationClient,
            ILogger <GenericRepository <EmailTemplate> > emailTemplateLogger,
            ILogger <GenericRepository <EmailHistory> > emailHistoryLogger,
            ILogger <GenericRepository <FunctionLog> > functionLogLogger,
            ILogger <EmailService> emailServiceLogger,
            [Frozen] Domain.Models.Opportunity opportunity,
            [Frozen] OpportunityItem opportunityItem,
            [Frozen] Domain.Models.Provider provider,
            [Frozen] Domain.Models.ProviderVenue venue,
            [Frozen] BackgroundProcessHistory backgroundProcessHistory,
            [Frozen] EmailHistory emailHistory,
            [Frozen] EmailTemplate emailTemplate,
            [Frozen] EmailNotificationResponse emailNotificationResponse
            )
        {
            //Arrange
            var(templateRepository, emailHistoryRepository, functionLogRepository, mapper)
                = SetUp(dbContext, emailTemplateLogger, emailHistoryLogger, functionLogLogger);

            var sut = new EmailService(configuration, notificationClient, templateRepository, emailHistoryRepository,
                                       functionLogRepository, mapper, emailServiceLogger);

            var tokens = new Dictionary <string, string>
            {
                { "contactname", "name" }
            };

            notificationClient.SendEmailAsync(Arg.Any <string>(), Arg.Any <string>(),
                                              Arg.Any <Dictionary <string, dynamic> >()).Returns(Task.FromResult(emailNotificationResponse));

            await DataBuilder.SetTestData(dbContext, provider, venue, opportunity, backgroundProcessHistory);

            await DataBuilder.SetEmailTemplate(dbContext, emailTemplate);

            //Act
            await sut.SendEmailAsync(emailTemplate.TemplateName, "*****@*****.**", opportunity.Id, opportunityItem.Id, tokens, "System");

            //Assert
            Guid.TryParse(emailNotificationResponse.id, out var notificationId);
            var data = dbContext.EmailHistory.AsNoTracking().FirstOrDefault(x => x.NotificationId == notificationId);

            data.Should().NotBeNull();
            data?.EmailTemplateId.Should().Be(emailHistory.EmailTemplateId);
            data?.Status.Should().BeNullOrEmpty();
            data?.NotificationId.Should().Be(emailNotificationResponse.id);
            data?.CreatedBy.Should().Be("System");
            data?.SentTo.Should().Be("*****@*****.**");
        }
示例#15
0
        public static async Task SetEmailHistory(
            MatchingDbContext dbContext,
            EmailHistory emailHistory)
        {
            emailHistory.Status     = null;
            emailHistory.ModifiedBy = null;
            emailHistory.ModifiedOn = null;

            await dbContext.AddAsync(emailHistory);

            await dbContext.SaveChangesAsync();

            dbContext.DetachAllEntities();
        }
        public async void Then_Do_Not_Update_Email_History_If_Authorization_Failed(
            MatchingConfiguration matchingConfiguration,
            EmailDeliveryStatusPayLoad payLoad,
            EmailHistory emailHistory,
            ExecutionContext context,
            IRepository <EmailHistory> emailHistoryRepository,
            IMessageQueueService messageQueueService,
            IEmailService emailService,
            IOpportunityRepository opportunityRepository,
            IRepository <FunctionLog> functionLogRepository,
            ILogger <EmailDeliveryStatusService> logger
            )
        {
            //Arrange
            matchingConfiguration.EmailDeliveryStatusToken = Guid.NewGuid();
            var serializedPayLoad   = JsonConvert.SerializeObject(payLoad);
            var notificationService = new EmailDeliveryStatusService(matchingConfiguration, emailService,
                                                                     opportunityRepository, messageQueueService, logger);

            emailService.UpdateEmailStatus(Arg.Any <EmailDeliveryStatusPayLoad>()).Returns(-1);

            var query = new Dictionary <string, StringValues>();

            query.TryAdd("content-type", "application/json");

            emailHistoryRepository.GetFirstOrDefaultAsync(Arg.Any <Expression <Func <EmailHistory, bool> > >())
            .Returns(emailHistory);

            //Act
            var emailDeliveryStatusFunctions = new Functions.EmailDeliveryStatus(matchingConfiguration, notificationService, functionLogRepository);
            var result = await emailDeliveryStatusFunctions.EmailDeliveryStatusHandlerAsync(
                HttpRequestSetup(query, serializedPayLoad),
                context, logger) as BadRequestObjectResult;

            //Assert
            result.Should().NotBeNull();
            result?.StatusCode.Should().Be(400);
            result?.Should().BeOfType <BadRequestObjectResult>();

            await emailHistoryRepository.DidNotReceive().UpdateWithSpecifiedColumnsOnlyAsync(Arg.Any <EmailHistory>(),
                                                                                             Arg.Any <Expression <Func <EmailHistory, object> >[]>());

            await emailHistoryRepository.DidNotReceive().UpdateWithSpecifiedColumnsOnlyAsync(
                Arg.Is <EmailHistory>(eh =>
                                      eh.Status == "delivered" && eh.ModifiedBy == "System"),
                Arg.Any <Expression <Func <EmailHistory, object> >[]>());

            await messageQueueService.DidNotReceive().PushEmailDeliveryStatusMessageAsync(Arg.Any <SendEmailDeliveryStatus>());
        }
示例#17
0
        public async Task Then_Update_Email_History_With_Status_And_Push_To_Email_Delivery_Status_Queue(
            string status,
            MatchingDbContext dbContext,
            MatchingConfiguration configuration,
            [Frozen] Domain.Models.Opportunity opportunity,
            [Frozen] Domain.Models.Provider provider,
            [Frozen] Domain.Models.ProviderVenue venue,
            [Frozen] EmailHistory emailHistory,
            [Frozen] BackgroundProcessHistory backgroundProcessHistory,
            ILogger <OpportunityRepository> opportunityRepoLogger,
            IMessageQueueService messageQueueService,
            EmailDeliveryStatusPayLoad payload,
            ILogger <GenericRepository <EmailTemplate> > emailTemplateLogger,
            ILogger <GenericRepository <EmailHistory> > emailHistoryLogger,
            ILogger <GenericRepository <FunctionLog> > functionLogLogger,
            ILogger <Application.Services.EmailDeliveryStatusService> emailDeliveryServiceStatusLogger,
            ILogger <EmailService> emailServiceLogger,
            IAsyncNotificationClient notificationClient
            )
        {
            //Arrange
            await DataBuilder.SetTestData(dbContext, provider, venue, opportunity, backgroundProcessHistory);

            dbContext.Add(emailHistory);
            await dbContext.SaveChangesAsync();

            dbContext.DetachAllEntities();

            payload.Status = status;
            payload.Id     = emailHistory.NotificationId.GetValueOrDefault();

            var sut = SutSetUp(dbContext, opportunityRepoLogger, emailTemplateLogger, emailHistoryLogger, functionLogLogger,
                               emailDeliveryServiceStatusLogger, emailServiceLogger, notificationClient, configuration, messageQueueService);

            var serializedPayLoad = JsonConvert.SerializeObject(payload);

            //Act
            await sut.HandleEmailDeliveryStatusAsync(serializedPayLoad);

            //Assert
            var data = dbContext.EmailHistory.FirstOrDefault(em => em.NotificationId == payload.Id);

            data.Should().NotBeNull();
            data?.NotificationId.Should().Be(payload.Id);
            data?.Status.Should().Be(payload.Status);
            data?.ModifiedBy.Should().Be("System");

            await messageQueueService.Received(1).PushEmailDeliveryStatusMessageAsync(Arg.Any <SendEmailDeliveryStatus>());
        }
示例#18
0
        /// <summary>
        /// 加载邮件列表
        /// </summary>
        private void LoadEmailHistory()
        {
            EmailHistory cEmailHistory = new EmailHistory();

            if (EmailType != "")
            {
                cEmailHistory.EmailType = EmailType;
            }
            if (MasterCode != "")
            {
                cEmailHistory.MasterCode = MasterCode;
            }

            string    Receiver = "";
            DataTable dt       = new DataTable();

            switch (EmailType)
            {
            case "BiddingEmitTo":
                dt = SupplierRule.GetSupplierByCode(Request["SupplierCode"]).CurrentTable;
                if (dt.Rows.Count > 0)
                {
                    Receiver = dt.Rows[0]["Email"].ToString();
                }
                dt.Dispose();
                break;

            default:
                Receiver = "";
                break;
            }
            if (Receiver != "")
            {
                cEmailHistory.Receiver = Receiver;
            }

            dt = cEmailHistory.GetEmailHistorys();
            dt.Columns.Add(new DataColumn("EmailTypeCN", Type.GetType("System.String")));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["EmailTypeCN"] = GetEmailTypeCNByEmailType(dt.Rows[i]["EmailType"].ToString());
            }

            this.gvEmailHistoryList.DataSource          = dt;
            this.gvEmailHistoryList.AutoGenerateColumns = false;
            this.gvEmailHistoryList.Columns[6].Visible  = false;
            this.gvEmailHistoryList.DataBind();
        }
示例#19
0
        internal static EmailHistoryList getEmailHistoryList(HttpResponseMessage responce)
        {
            var emailHistoryList = new EmailHistoryList();
            var jsonObj          = JsonConvert.DeserializeObject <Dictionary <string, object> >(responce.Content.ReadAsStringAsync().Result);

            if (jsonObj.ContainsKey("email_history"))
            {
                var emailHistoryArray = JsonConvert.DeserializeObject <List <object> >(jsonObj["email_history"].ToString());
                foreach (var emailHistoryObj in emailHistoryArray)
                {
                    var emailHistory = new EmailHistory();
                    emailHistory = JsonConvert.DeserializeObject <EmailHistory>(emailHistoryObj.ToString());
                    emailHistoryList.Add(emailHistory);
                }
            }
            return(emailHistoryList);
        }
示例#20
0
        /// <summary>
        /// Update base of EmailHistory Object.
        /// Data manipulation processing for: new, deleted, updated EmailHistory
        /// </summary>
        /// <param name="emailHistoryObject"></param>
        /// <returns></returns>
        public bool UpdateBase(EmailHistory emailHistoryObject)
        {
            // use of switch for different types of DML
            switch (emailHistoryObject.RowState)
            {
            // insert new rows
            case BaseBusinessEntity.RowStateEnum.NewRow:
                return(Insert(emailHistoryObject));

            // delete rows
            case BaseBusinessEntity.RowStateEnum.DeletedRow:
                return(Delete(emailHistoryObject.Id));
            }
            // update rows
            using (EmailHistoryDataAccess data = new EmailHistoryDataAccess(ClientContext))
            {
                return(data.Update(emailHistoryObject) > 0);
            }
        }
示例#21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EmailHistoryDTO"/> class.
 /// </summary>
 /// <param name="emailHistory">
 /// The email history.
 /// </param>
 public EmailHistoryDTO(EmailHistory emailHistory)
 {
     if (emailHistory != null)
     {
         this.emailHistoryId = emailHistory.Id;
         this.sentTo         = emailHistory.SentTo;
         this.sentFrom       = emailHistory.SentFrom;
         this.sentToName     = emailHistory.SentToName;
         this.sentFromName   = emailHistory.SentFromName;
         this.sentCc         = emailHistory.SentCc;
         this.sentBcc        = emailHistory.SentBcc;
         this.subject        = emailHistory.Subject;
         this.message        = emailHistory.Message;
         this.body           = string.Empty; //// TODO Either escape HTML inside XML or disable AMF String Referencing via config emailHistory.Body;
         this.date           = emailHistory.Date.ConvertToUnixTimestamp();
         this.companyName    = emailHistory.Return(x => x.User.Return(y => y.Company.Return(z => z.CompanyName, null), null), null);
         this.status         = emailHistory.Status;
     }
 }
示例#22
0
 /// <summary>
 /// Insert new emailHistory.
 /// data manipulation for insertion of EmailHistory
 /// </summary>
 /// <param name="emailHistoryObject"></param>
 /// <returns></returns>
 private bool Insert(EmailHistory emailHistoryObject)
 {
     // new emailHistory
     using (EmailHistoryDataAccess data = new EmailHistoryDataAccess(ClientContext))
     {
         // insert to emailHistoryObject
         Int32 _Id = data.Insert(emailHistoryObject);
         // if successful, process
         if (_Id > 0)
         {
             emailHistoryObject.Id = _Id;
             return(true);
         }
         else
         {
             return(false);
         }
     }
 }
示例#23
0
        /// <summary>
        /// Retrieves EmailHistory object from SqlCommand, after database query
        /// </summary>
        /// <param name="cmd">The command object to use for query</param>
        /// <returns>EmailHistory object</returns>
        private EmailHistory GetObject(SqlCommand cmd)
        {
            SqlDataReader reader;
            long          rows = SelectRecords(cmd, out reader);

            using (reader)
            {
                if (reader.Read())
                {
                    EmailHistory emailHistoryObject = new EmailHistory();
                    FillObject(emailHistoryObject, reader);
                    return(emailHistoryObject);
                }
                else
                {
                    return(null);
                }
            }
        }
        public async void Then_Update_Email_History_With_Failed_Status_And_Push_To_Email_Delivery_Status_Queue(
            string status,
            MatchingConfiguration matchingConfiguration,
            EmailDeliveryStatusPayLoad payLoad,
            EmailHistory emailHistory,
            ExecutionContext context,
            IRepository <EmailHistory> emailHistoryRepository,
            IMessageQueueService messageQueueService,
            IEmailService emailService,
            IOpportunityRepository opportunityRepository,
            IRepository <FunctionLog> functionLogRepository,
            ILogger <EmailDeliveryStatusService> logger
            )
        {
            //Arrange
            payLoad.Status = status;
            var serializedPayLoad   = JsonConvert.SerializeObject(payLoad);
            var notificationService = new EmailDeliveryStatusService(matchingConfiguration, emailService,
                                                                     opportunityRepository, messageQueueService, logger);

            emailService.UpdateEmailStatus(Arg.Any <EmailDeliveryStatusPayLoad>()).Returns(1);

            var query = new Dictionary <string, StringValues>();

            query.TryAdd("content-type", "application/json");

            emailHistoryRepository.GetFirstOrDefaultAsync(Arg.Any <Expression <Func <EmailHistory, bool> > >())
            .Returns(emailHistory);

            //Act
            var emailDeliveryStatusFunctions = new Functions.EmailDeliveryStatus(matchingConfiguration, notificationService, functionLogRepository);
            var result = await emailDeliveryStatusFunctions.EmailDeliveryStatusHandlerAsync(
                HttpRequestSetup(query, serializedPayLoad),
                context, logger) as OkObjectResult;

            //Assert
            result.Should().NotBeNull();
            result?.StatusCode.Should().Be(200);
            result?.Value.Should().Be("1 records updated.");

            await messageQueueService.Received(1).PushEmailDeliveryStatusMessageAsync(Arg.Is <SendEmailDeliveryStatus>(email => email.NotificationId == payLoad.Id));
        }
示例#25
0
        private async Task CreateDownloadTasks()
        {
            ReadConfiguration();

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

            IsRunning        = true;
            _downloadingTask = new List <Task <List <MimeMessage> > >();
            CurrentDownloadId++;
            CurrentDownloadedMessagesCount = 0;

            DownloadTimestamp = DateTime.Now.ToUnixTimeStamp();

            foreach (var email in _configuration)
            {
                _downloadingTask.Add(Task.Factory.StartNew(() => StartDownloadProcess(email)));
            }

            // Wait until all download is compleated
            await Task.WhenAll(_downloadingTask);

            EmailHistory lastHistory = new EmailHistory {
                Id = CurrentDownloadId
            };

            foreach (var task in _downloadingTask)
            {
                if (task.Result == null)
                {
                    continue;
                }

                lastHistory.Messages.AddRange(task.Result);
            }
            History.Add(lastHistory);

            IsRunning = false;
        }
        public async Task Then_Update_Email_History_With_Delivery_Status(
            MatchingConfiguration configuration,
            [Frozen] MatchingDbContext dbContext,
            IAsyncNotificationClient notificationClient,
            ILogger <GenericRepository <EmailTemplate> > emailTemplateLogger,
            ILogger <GenericRepository <EmailHistory> > emailHistoryLogger,
            ILogger <GenericRepository <FunctionLog> > functionLogLogger,
            ILogger <EmailService> emailServiceLogger,
            [Frozen] Domain.Models.Opportunity opportunity,
            [Frozen] Domain.Models.Provider provider,
            [Frozen] Domain.Models.ProviderVenue venue,
            [Frozen] BackgroundProcessHistory backgroundProcessHistory,
            EmailDeliveryStatusPayLoad payLoad,
            EmailHistory emailHistory
            )
        {
            //Arrange
            var(templateRepositoryLogger, emailHistoryRepository, functionLogRepository, mapper)
                = SetUp(dbContext, emailTemplateLogger, emailHistoryLogger, functionLogLogger);

            var sut = new EmailService(configuration, notificationClient, templateRepositoryLogger, emailHistoryRepository,
                                       functionLogRepository, mapper, emailServiceLogger);

            emailHistory.NotificationId = payLoad.Id;
            await DataBuilder.SetTestData(dbContext, provider, venue, opportunity, backgroundProcessHistory);

            await DataBuilder.SetEmailHistory(dbContext, emailHistory);

            //Act
            await sut.UpdateEmailStatus(payLoad);

            //Assert
            var data = dbContext.EmailHistory.AsNoTracking().FirstOrDefault(x => x.NotificationId == payLoad.Id);

            data.Should().NotBeNull();
            data?.Status.Should().Be(payLoad.Status);
            data?.NotificationId.Should().Be(payLoad.Id);
            data?.ModifiedBy.Should().Be("System");
        }
        private async Task SaveEmailHistoryAsync(Guid notificatonId, int emailTemplateId,
                                                 IDictionary <string, string> tokens,
                                                 int?opportunityId, int?opportunityItemId, string emailAddress, string createdBy)
        {
            var placeholders = ConvertTokensToEmailPlaceholderDtos(tokens, createdBy);

            var emailPlaceholders = _mapper.Map <IList <EmailPlaceholder> >(placeholders);

            _logger.LogInformation($"Saving {emailPlaceholders.Count} {nameof(EmailPlaceholder)} items.");

            var emailHistory = new EmailHistory
            {
                NotificationId    = notificatonId,
                OpportunityId     = opportunityId,
                OpportunityItemId = opportunityItemId,
                EmailTemplateId   = emailTemplateId,
                EmailPlaceholder  = emailPlaceholders,
                SentTo            = emailAddress,
                CreatedBy         = createdBy
            };

            await _emailHistoryRepository.CreateAsync(emailHistory);
        }
示例#28
0
 /// <summary>
 /// Fill External Childs of EmailHistory Object.
 /// </summary>
 /// <param name="emailHistoryObject"></param>
 /// <returns></returns>
 public void FillChilds(EmailHistory emailHistoryObject)
 {
     ///Fill external information of Childs of EmailHistoryObject
 }
示例#29
0
        private bool SentEmail(Hashtable TemplateValue, string TemplateKey)
        {
            EmailTemplate emailTemplate  = _EmailTemplateDataAccess.GetByQuery("TemplateKey='" + TemplateKey + "'").FirstOrDefault();
            EmailParser   parser         = null;
            string        toEmailAddress = "";

            if (emailTemplate == null || emailTemplate.Id == 0)
            {
                //Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Template not found for key :" + TemplateKey));
                return(false);
            }
            if (!string.IsNullOrWhiteSpace(emailTemplate.BodyFile))
            {
                parser = new EmailParser(HttpContext.Current.Server.MapPath(emailTemplate.BodyFile), TemplateValue, true);
            }
            else if (!string.IsNullOrWhiteSpace(emailTemplate.BodyContent))
            {
                parser = new EmailParser(emailTemplate.BodyContent, TemplateValue, false);
            }

            MailMessage message = new MailMessage();

            message.Body = parser.Parse();

            if (emailTemplate.ToEmail.IndexOf("##") > -1)
            {
                EmailParser ToEmailParser = new EmailParser(emailTemplate.ToEmail, TemplateValue, false);
                message.To.Add(new MailAddress(ToEmailParser.Parse()));
                toEmailAddress = message.To[0].ToString();
            }
            else
            {
                message.To.Add(emailTemplate.ToEmail);
                toEmailAddress = message.To[0].ToString();
            }
            if (emailTemplate.ReplyEmail.IndexOf("##") > -1)
            {
                EmailParser ToEmailParser = new EmailParser(emailTemplate.ReplyEmail, TemplateValue, false);
                message.ReplyTo = new MailAddress(ToEmailParser.Parse());
                toEmailAddress  = message.To[0].ToString();
            }
            else
            {
                message.ReplyTo = new MailAddress(emailTemplate.ReplyEmail);
            }

            if (emailTemplate.FromEmail.IndexOf("##") > -1)
            {
                EmailParser ToEmailParser = new EmailParser(emailTemplate.FromEmail, TemplateValue, false);
                message.From = new MailAddress(ToEmailParser.Parse());
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(emailTemplate.FromName))
                {
                    message.From = new MailAddress(emailTemplate.FromEmail, emailTemplate.FromName);
                }
                else
                {
                    message.From = new MailAddress(emailTemplate.FromEmail);
                }
            }

            if (!string.IsNullOrWhiteSpace(emailTemplate.BccEmail))
            {
                message.Bcc.Add(emailTemplate.BccEmail);
            }

            if (!string.IsNullOrWhiteSpace(emailTemplate.CcEmail))
            {
                message.CC.Add(emailTemplate.CcEmail);
            }

            if (emailTemplate.Subject.IndexOf("##") > -1)
            {
                EmailParser SubjectParser = new EmailParser(emailTemplate.Subject, TemplateValue, false);
                message.Subject = SubjectParser.Parse();
            }
            else
            {
                message.Subject = emailTemplate.Subject;
            }
            //if (Attachments != null)
            //{
            //    if (Attachments.Count > 0)
            //    {
            //        foreach (var attachment in Attachments)
            //        {
            //            message.Attachments.Add(attachment);
            //        }
            //    }
            //}
            message.IsBodyHtml   = true;
            message.BodyEncoding = System.Text.Encoding.UTF8;


            try
            {
                SmtpClient client = new SmtpClient();
                //GlobalSetting EmailHost = _GlobalSettingDataAccess.GetByQuery(string.Format(" SearchKey ='{0}' and CompanyId ='{1}'", "EmailHost", CompanyId)).FirstOrDefault();
                //GlobalSetting EmailHostUsername = _GlobalSettingDataAccess.GetByQuery(string.Format(" SearchKey ='{0}' and CompanyId ='{1}'", "EmailHostUsername", CompanyId)).FirstOrDefault();
                //GlobalSetting EmailHostPassword = _GlobalSettingDataAccess.GetByQuery(string.Format(" SearchKey ='{0}' and CompanyId ='{1}'", "EmailHostPassword", CompanyId)).FirstOrDefault();
                //GlobalSetting EmailPort = _GlobalSettingDataAccess.GetByQuery(string.Format(" SearchKey ='{0}' and CompanyId ='{1}'", "EmailPort", CompanyId)).FirstOrDefault();


                client.Host = "webmail.piiscenter.com";

                client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "piiscenter.com");

                client.Port      = 25;
                client.EnableSsl = false;
                //message.From = new MailAddress("*****@*****.**");
                //message.From = new MailAddress("*****@*****.**");
                //Need to user From email of default domain
                client.Send(message);

                //SmtpClient client = new SmtpClient();
                //client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "piiscenter.com");
                //client.EnableSsl = false;
                //client.Send(message);
                // if (!HttpContext.Current.Request.IsLocal)
                //{
                //SmtpClient client = new SmtpClient();
                //    client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Rezwan10");
                //    client.EnableSsl = false;
                //    client.Send(message);
                // }
                //SmtpClient smtp = new SmtpClient
                //{
                //    Host = "smtp.gmail.com",
                //    //change the port to prt 587. This seems to be the standard for Google smtp transmissions.
                //    Port = 587,
                //    //enable SSL to be true, otherwise it will get kicked back by the Google server.
                //   // EnableSsl = true,
                //    //The following properties need set as well
                //    DeliveryMethod = SmtpDeliveryMethod.Network,
                //    UseDefaultCredentials = false,
                //    Credentials = new NetworkCredential("*****@*****.**", "Inf0rmrcl@ud")
                //};
                //smtp.Send(message);

                EmailHistory emailHistory = new EmailHistory();
                emailHistory.TemplateKey      = TemplateKey;
                emailHistory.ToEmail          = toEmailAddress;
                emailHistory.CcEmail          = message.CC.ToString();
                emailHistory.BccEmail         = message.Bcc.ToString();
                emailHistory.FromEmail        = message.From.ToString();
                emailHistory.EmailBodyContent = message.Body;
                emailHistory.EmailSubject     = message.Subject;
                emailHistory.EmailSentDate    = DateTime.Now;
                emailHistory.LastUpdatedDate  = DateTime.Now;
                _EmailHistoryDataAccess.Insert(emailHistory);
                return(true);
            }
            catch (Exception ex)
            {
                EmailHistory emailHistory = new EmailHistory();
                emailHistory.TemplateKey      = TemplateKey;
                emailHistory.ToEmail          = toEmailAddress;
                emailHistory.CcEmail          = message.CC.ToString();
                emailHistory.BccEmail         = message.Bcc.ToString();
                emailHistory.FromEmail        = message.From.ToString();
                emailHistory.EmailBodyContent = message.Body;
                emailHistory.EmailSubject     = message.Subject;

                emailHistory.LastUpdatedDate = DateTime.Now;
                _EmailHistoryDataAccess.Insert(emailHistory);
                //Logger.AddElmah(ex);
            }


            return(false);
        }
        public async Task SendNotificationAsync()
        {
            var notifications = await _notificationRepository.SearchAsync(new NotificationFilter());

            var users = (await _userRepository.GetByIdAsync(notifications.Select(n => n.UserId))).ToDictionary(i => i.Id, i => i);

            foreach (var notification in notifications)
            {
                var filter = JsonConvert.DeserializeObject <PetFilter>(notification.PetFilterSerialized);
                filter.CreatedSince = DateTime.Now.Date;

                var user = users[notification.UserId];

                var pets = await _petRepository.SearchAsync(filter);

                if (pets.Count() == 0)
                {
                    continue;
                }

                var attachment = new List <Attachment>();
                if (await EmailExists(user.Id, notification.Id, DateTime.Now.Date))
                {
                    continue;
                }

                string mailTemplate = GetResource("notification-email.html")
                                      .Replace("{{user.Name}}", user.Name);
                string petRowTemplate = GetResource("notification-pet-row.html");

                StringBuilder sbPets = new StringBuilder();

                int fileCount = 0;

                foreach (var pet in pets)
                {
                    string html = petRowTemplate
                                  .Replace("{{pet.Name}}", pet.Name)
                                  .Replace("{{pet.Description}}", pet.Description)
                                  .Replace("{{pet.SourceLink}}", pet.SourceLink);

                    using (var client = new WebClient())
                    {
                        var content = client.DownloadData(Path.Combine(Constants.StorageUrl, pet.MetaFileLinks.First().Path));
                        using (var ms = new MemoryStream(content))
                        {
                            string imageName = $"image{fileCount++}.jpg";

                            var fileBytes = ms.ToArray();
                            attachment.Add(new Attachment(new MemoryStream(fileBytes), imageName));

                            html = html.Replace("{{pet-image}}", $"cid:{imageName}");
                        }
                    }
                    sbPets.AppendLine(html);
                }

                var bodyHtml = mailTemplate.Replace("{{pets-html}}", sbPets.ToString());

                var mail = new MailRequest()
                {
                    To          = user.Email,
                    Subject     = "בעלי חיים חדשים מחכים לאימוץ!",
                    Body        = bodyHtml,
                    Attachments = attachment
                };
                await _mailHandler.SendEmailAsync(mail);

                var emailHistory = new EmailHistory()
                {
                    UpdatedTimestamp  = DateTime.Now,
                    UserId            = user.Id,
                    NotificationId    = notification.Id,
                    CreationTimestamp = DateTime.Now,
                    SentDate          = DateTime.Now.Date
                };
                await _emailHistoryRepository.AddAsync(emailHistory);

                await _unitOfWork.SaveChangesAsync();
            }
        }