Exemple #1
0
        /// <summary>
        /// Adds the specified site user.
        /// </summary>
        /// <param name="contact">The site user.</param>
        /// <returns></returns>
        public tbl_Contact Add(tbl_Contact contact)
        {
            contact.ID = Guid.NewGuid();

            if (contact.CreatedAt == DateTime.MinValue)
            {
                contact.CreatedAt = DateTime.Now;
            }

            if (!contact.LastActivityAt.HasValue || contact.LastActivityAt == DateTime.MinValue)
            {
                contact.LastActivityAt = DateTime.Now;
            }

            if (contact.CellularPhoneStatusID == null)
            {
                contact.CellularPhoneStatusID = 0;
            }
            if (contact.EmailStatusID == null)
            {
                contact.EmailStatusID = 0;
            }
            contact.RegistrationSourceID = (int)RegistrationSource.Manual;
            _dataContext.tbl_Contact.AddObject(contact);
            _dataContext.SaveChanges();
            return(contact);
        }
Exemple #2
0
        /// <summary>
        /// Gets the responsible.
        /// </summary>
        /// <param name="siteId">The site id.</param>
        /// <param name="contactRoleId">The contact role id.</param>
        /// <param name="contactId">The contact id.</param>
        /// <param name="workflowId">The workflow id.</param>
        /// <returns></returns>
        public tbl_Contact GetResponsible(Guid siteId, Guid contactRoleId, Guid contactId, Guid?workflowId = null)
        {
            var         dataManager        = new DataManager();
            tbl_Contact responsibleContact = null;

            var responsible = dataManager.Responsible.Select(contactRoleId, contactId, workflowId);

            if (responsible == null)
            {
                responsibleContact = dataManager.Responsible.GetResponsible(siteId, contactRoleId);
                if (responsibleContact != null)
                {
                    responsible = new tbl_Responsible {
                        ContactRoleID = contactRoleId, ContactID = contactId, ResponsibleID = responsibleContact.ID
                    };
                    if (workflowId != null)
                    {
                        responsible.WorkflowID = workflowId;
                    }
                    dataManager.Responsible.Add(responsible);
                }
            }
            else
            {
                responsibleContact = dataManager.Contact.SelectById(siteId, responsible.ResponsibleID);
            }

            return(responsibleContact);
        }
Exemple #3
0
        /// <summary>
        /// Gets the site action template recipients.
        /// </summary>
        /// <param name="siteId">The site id.</param>
        /// <param name="siteActionTemplateId">The site action template id.</param>
        /// <returns></returns>
        public List <Recipient> GetSiteActionTemplateRecipients(Guid siteId, Guid siteActionId, Guid siteActionTemplateId, Guid contactId)
        {
            var dataManager = new DataManager();
            var recipients  = new List <Recipient>();

            var siteActionTemplateRecipients = dataManager.SiteActionTemplateRecipient.SelectAll(siteActionTemplateId);

            foreach (var siteActionTemplateRecipient in siteActionTemplateRecipients)
            {
                // Если получатель Контакт
                tbl_Contact contact;
                if (siteActionTemplateRecipient.ContactID.HasValue)
                {
                    contact = dataManager.Contact.SelectById(siteId, (Guid)siteActionTemplateRecipient.ContactID);
                    if (contact != null)
                    {
                        recipients.Add(AddRecipient(contact.Email, contact.UserFullName));
                    }
                }

                // Если получатель Роль
                if (siteActionTemplateRecipient.ContactRoleID.HasValue)
                {
                    var contactRole = dataManager.ContactRole.SelectById(siteId, (Guid)siteActionTemplateRecipient.ContactRoleID);
                    if (contactRole != null)
                    {
                        tbl_Contact responsibleContact = null;
                        switch ((ContactRoleType)contactRole.RoleTypeID)
                        {
                        case ContactRoleType.GeneralEmail:
                            recipients.Add(AddRecipient(contactRole.Email, contactRole.DisplayName));
                            break;

                        case ContactRoleType.ContactRole:
                            responsibleContact = GetResponsible(siteId, contactRole.ID, contactId);
                            if (responsibleContact != null)
                            {
                                recipients.Add(AddRecipient(responsibleContact.Email, responsibleContact.UserFullName));
                            }
                            break;

                        case ContactRoleType.WorkflowRole:
                            responsibleContact = GetResponsible(siteId, contactRole.ID, contactId, WorkflowProcessing.GetWorkflowIdByValue(siteActionId));
                            if (responsibleContact != null)
                            {
                                recipients.Add(AddRecipient(responsibleContact.Email, responsibleContact.UserFullName));
                            }
                            break;
                        }
                    }
                }

                if (!siteActionTemplateRecipient.ContactID.HasValue && !siteActionTemplateRecipient.ContactRoleID.HasValue)
                {
                    recipients.Add(AddRecipient(siteActionTemplateRecipient.Email, siteActionTemplateRecipient.DisplayName));
                }
            }

            return(recipients);
        }
        public List <string> GetContactPhoneNumbers(Guid?ContactID)
        {
            List <string> nums    = new List <string>();
            tbl_Contact   contact = db.tbl_Contact.FirstOrDefault(c => c.ID == ContactID);

            if (contact == null)
            {
                return(nums);
            }
            string s1 = isBelarusMobilePhone(contact.Communication1);

            if (!String.IsNullOrEmpty(s1))
            {
                nums.Add(s1);
            }
            string s2 = isBelarusMobilePhone(contact.Communication2);

            if (!String.IsNullOrEmpty(s2))
            {
                nums.Add(s2);
            }
            string s3 = isBelarusMobilePhone(contact.Communication3);

            if (!String.IsNullOrEmpty(s3))
            {
                nums.Add(s3);
            }
            string s4 = isBelarusMobilePhone(contact.Communication4);

            if (!String.IsNullOrEmpty(s4))
            {
                nums.Add(s4);
            }
            return(nums);
        }
Exemple #5
0
        public ActionResult UpdateStatusContact(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            tbl_Contact tblContact = db.tbl_Contact.Find(id);

            if (tblContact == null)
            {
                return(HttpNotFound());
            }
            else
            {
                if (tblContact.IsReply)
                {
                    tblContact.IsReply = false;
                }
                else
                {
                    tblContact.IsReply = true;
                }
                db.SaveChanges();
            }
            var model = db.tbl_Contact.ToList().OrderByDescending(x => x.NgayGui);

            return(View("ListContact", model));
        }
        /// <summary>
        /// Creates the sender.
        /// </summary>
        /// <param name="siteId">The site id.</param>
        /// <param name="mailAddress">The mail address.</param>
        /// <returns></returns>
        private tbl_Contact CreateSender(Guid siteId, RfcMailAddress mailAddress)
        {
            var contact = new tbl_Contact
            {
                ID            = Guid.NewGuid(),
                SiteID        = siteId,
                UserFullName  = mailAddress.DisplayName,
                Email         = mailAddress.Address,
                IsNameChecked = false,
                UserIP        = string.Empty,
                RefferURL     = string.Empty,
                StatusID      = _dataManager.Status.SelectDefault(siteId).ID
            };


            var nameChecker = new NameChecker(Settings.ADONetConnectionString);
            var nameCheck   = nameChecker.CheckName(contact.UserFullName, NameCheckerFormat.FIO, Correction.Correct);

            if (!string.IsNullOrEmpty(nameCheck))
            {
                contact.UserFullName  = nameCheck;
                contact.Surname       = nameChecker.Surname;
                contact.Name          = nameChecker.Name;
                contact.Patronymic    = nameChecker.Patronymic;
                contact.IsNameChecked = nameChecker.IsNameCorrect;
            }

            return(contact);
        }
Exemple #7
0
 public CustomerContactViewModel(tbl_Customer customer, tbl_Contact contact)
 {
     CusId           = customer.CusId;
     CusCMND         = customer.CusCMND;
     CusName         = customer.CusName;
     CusPhone        = customer.CusPhone;
     CusAddress      = customer.CusAddress;
     CusCompany      = customer.CusCompany;
     CusPosition     = customer.CusPosition;
     CusSalary       = customer?.CusSalary;
     CusNote         = customer.CusNote;
     CusEmail        = customer.CusEmail;
     CusSexIsMale    = customer?.CusSexIsMale;
     CusDateOfBirth  = customer?.CusDateOfBirth;
     CusCICNumber    = customer.CusCICNumber;
     CusLimitOffer   = customer?.CusLimitOffer;
     CusDistrict     = customer.CusDistrict;
     CusCity         = customer.CusCity;
     CusLeadProDuct  = customer.CusLeadProDuct;
     CusVPID         = customer.CusVPID;
     Branches        = customer.Branches;
     contactId       = contact.id;
     dateStart       = contact?.dateStart;
     dateEnd         = contact?.dateEnd;
     lastUpdate      = contact?.lastUpdate;
     note            = contact.note;
     curAdminId      = contact.curAdminId;
     teamID          = contact.teamID;
     proID           = contact?.proID;
     loanAmounth     = contact?.loanAmounth;
     stageID         = contact?.stageID;
     history         = contact.history;
     referenceSource = contact.referenceSource;
     campainID       = contact?.campainID;
 }
        public void Notify(tbl_Contact post)
        {
            foreach (IContactObserver observer in observers)

            {
                observer.Update(post);
            }
        }
Exemple #9
0
        public void Update(tbl_Contact contact)
        {
            tbl_Activity notification = new tbl_Activity();

            notification.Description = $"New forum post - {contact} - received on {DateTime.Now}";
            notification.Time        = DateTime.Now;
            db.tbl_Activity.Add(notification);
            db.SaveChanges();
        }
Exemple #10
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            var accessCheck = Access.Check(TblUser, "Requests");

            if (!accessCheck.Read)
            {
                Response.Redirect(UrlsData.LFP_AccessDenied(PortalSettingsId));
            }

            Title = lrlTitle.Text = "Новый запрос";

            ucContentComments.ContentId = ObjectId;

            gridRequirements.SiteID = SiteId;
            gridRequirements.Where.Add(new GridWhere()
            {
                CustomQuery =
                    string.Format(
                        "(tbl_Requirement.RequestID = '{0}' " +
                        "OR tbl_Requirement.ID IN " +
                        "(SELECT RequirementID FROM tbl_RequestToRequirement WHERE RequestID = '{0}'))",
                        ObjectId.ToString())
            });

            if (ObjectId != Guid.Empty)
            {
                plViewRequest.Visible = true;
            }
            else
            {
                Contact      = DataManager.Contact.SelectById(SiteId, (Guid)CurrentUser.Instance.ContactID);
                ServiceLevel = DataManager.ServiceLevel.SelectForContact(SiteId, Contact);

                if (ServiceLevel != null)
                {
                    plAddRequest.Visible = true;
                    hlCancel.NavigateUrl = UrlsData.LFP_Requests(PortalSettingsId);
                }
                else
                {
                    ucNotificationMessage.Text = "Не определен уровень обслуживания.";
                }
            }

            gridRequirements.Actions.Add(new GridAction {
                Text = "Карточка требования", NavigateUrl = "~/" + PortalSettingsId + "/Main/Requirements/Edit/{0}", ImageUrl = "~/App_Themes/Default/images/icoView.png"
            });

            if (!Page.IsPostBack)
            {
                BindData();
            }
        }
Exemple #11
0
        public ActionResult ContactResult([Bind(Include = "Id,Ho,Ten,Email,TenCongTy,DiaChi,SoDT,GhiChu")] tbl_Contact tbl_Contact)
        {
            if (ModelState.IsValid)
            {
                var admin = db.tbl_Account.Where(x => x.IsAdmin).ToList().FirstOrDefault();
                db.tbl_Contact.Add(tbl_Contact);
                db.SaveChanges();
                try
                {
                    //send admin
                    string content = System.IO.File.ReadAllText(Server.MapPath("~/Views/ContactMail/ContactCustomSendAdmin.cshtml"));
                    content = content.Replace("{{TenKH}}", tbl_Contact.Ho + " " + tbl_Contact.Ten);
                    content = content.Replace("{{SoDT}}", tbl_Contact.SoDT);
                    content = content.Replace("{{Email}}", tbl_Contact.Email);
                    content = content.Replace("{{DiaChi}}", tbl_Contact.DiaChi);
                    content = content.Replace("{{TenCompany}}", tbl_Contact.TenCongTy);
                    content = content.Replace("{{Comment}}", tbl_Contact.GhiChu);

                    if (admin != null)
                    {
                        string contentCusstom = null;
                        if (CommonConstants.CurrentCulture == null)
                        {
                            contentCusstom = System.IO.File.ReadAllText(Server.MapPath("~/Views/ContactMail/ContactCustom.cshtml"));
                            new MailHelper().SendMail(tbl_Contact.Email, Resource.lblConfigFromEmailDisplayNameContact, null, contentCusstom, true, true);
                        }
                        else if (CommonConstants.CurrentCulture.Equals("vi"))
                        {
                            contentCusstom = System.IO.File.ReadAllText(Server.MapPath("~/Views/ContactMail/ContactCustom_vi.cshtml"));
                            new MailHelper().SendMail(tbl_Contact.Email, Resource.lblConfigFromEmailDisplayNameContact, null, contentCusstom, true, true);
                        }
                        else
                        {
                            contentCusstom = System.IO.File.ReadAllText(Server.MapPath("~/Views/ContactMail/ContactCustom_en.cshtml"));
                            new MailHelper().SendMail(tbl_Contact.Email, Resource.lblConfigFromEmailDisplayNameContact, null, contentCusstom, true, true);
                        }

                        new MailHelper().SendMail(admin.Email, "Liên hệ từ khách hàng ", tbl_Contact.Ho + " " + tbl_Contact.Ten, content, true, false);
                        Session[CommonConstants.CardSession] = null;
                        return(RedirectToAction("SendContactSuccess"));
                    }
                }
                catch (Exception ex)
                {
                    return(RedirectToAction("SendContactError"));
                }
                return(RedirectToAction("SendContactError"));
            }

            return(View("Contact"));
        }
        /// <summary>
        /// Selects for contact.
        /// </summary>
        /// <param name="siteId">The site id.</param>
        /// <param name="contact">The contact.</param>
        /// <returns></returns>
        public tbl_ServiceLevel SelectForContact(Guid siteId, tbl_Contact contact)
        {
            var dataManager = new DataManager();

            tbl_ServiceLevel serviceLevel = null;

            if (contact.CompanyID.HasValue)
            {
                serviceLevel = dataManager.ServiceLevel.SelectByCompanyId(siteId, (Guid)contact.CompanyID);
            }

            if (serviceLevel == null)
            {
                var serviceLevelContact = dataManager.ServiceLevelContact.SelectByContactId(contact.ID);
                if (serviceLevelContact != null)
                {
                    serviceLevel = serviceLevelContact.tbl_ServiceLevelClient.tbl_ServiceLevel;
                }
                else
                {
                    serviceLevel = dataManager.ServiceLevel.SelectDefault(siteId);
                    if (serviceLevel == null)
                    {
                        return(null);
                    }
                }
            }
            else
            {
                var serviceLevelClient = serviceLevel.tbl_ServiceLevelClient.FirstOrDefault(o => o.ClientID == contact.CompanyID);

                if (!dataManager.ServiceLevelContact.IsExistInClient(serviceLevelClient.ID, contact.ID))
                {
                    switch ((OutOfListServiceContacts)serviceLevelClient.OutOfListServiceContactsID)
                    {
                    case OutOfListServiceContacts.Reject:
                        return(null);

                    case OutOfListServiceContacts.Default:
                        serviceLevel = dataManager.ServiceLevel.SelectDefault(siteId);
                        break;
                    }
                }
            }

            return(serviceLevel);
        }
Exemple #13
0
        public int AddContacts(ContactModel model)
        {
            using (var context = new TravelAgencyEntities())
            {
                tbl_Contact contact = new tbl_Contact()
                {
                    Name        = model.Name,
                    Email       = model.Email,
                    Subject     = model.Subject,
                    MessageBody = model.MessageBody,
                    EmailSent   = true,
                    TimeStamp   = System.DateTime.Now
                };

                context.tbl_Contact.Add(contact);
                context.SaveChanges();
                return(contact.Id);
            }
        }
        public HttpResponseMessage CreateNewCustomerAndContact(
            string name, string identityCard, string phone, string address, string email,
            string company, string position, int stageId)
        {
            try
            {
                var customerService = this.Service <ICustomerService>();
                var contactService  = this.Service <IContactService>();

                //create new customer
                tbl_Customer customer = new tbl_Customer();
                customer.CusName     = name;
                customer.CusCMND     = identityCard;
                customer.CusPhone    = phone;
                customer.CusAddress  = address;
                customer.CusEmail    = email;
                customer.CusCompany  = company;
                customer.CusPosition = position;

                customerService.add(customer);

                //create new contact
                tbl_Contact contact = new tbl_Contact();
                contact.dateStart  = DateTime.Now;
                contact.lastUpdate = DateTime.Now;
                contact.cusID      = customer.CusId;
                contact.stageID    = stageId;

                contactService.add(contact);

                return(new HttpResponseMessage()
                {
                    Content = new JsonContent(new CustomerContactViewModel(customer, contact))
                });
            }
            catch (Exception e)
            {
                return(new HttpResponseMessage()
                {
                    Content = new JsonContent(e.Message)
                });
            }
        }
        //send email to all admins about New Contact Message
        public void Update(tbl_Contact contact)
        {
            var email       = db.Login_table.Where(x => x.Role == "A").Select(x => x.EmailAddress);
            var fromAddress = new MailAddress("*****@*****.**", "Farooq Abdullah");

            MailAddressCollection TO_addressList = new MailAddressCollection();

            //3.Prepare the Destination email Addresses list
            foreach (var curr_address in email)
            {
                MailAddress mytoAddress = new MailAddress(curr_address, curr_address);
                TO_addressList.Add(mytoAddress);
            }


            const string fromPassword = "******";
            const string subject      = "Notification";
            string       body         = "Hello" + TO_addressList + " Contact is From  User : "******" Description is  " + contact.Details + "";

            var smtp = new SmtpClient
            {
                Host                  = "smtp.gmail.com",
                Port                  = 587,
                EnableSsl             = true,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
            };

            //6.Complete the message and SEND the email:
            using (var message = new MailMessage()
            {
                From = fromAddress,
                Subject = subject,
                Body = body,
            })
            {
                message.To.Add(TO_addressList.ToString());
                smtp.Send(message);
            }
        }
Exemple #16
0
        /// <summary>
        /// Checks the name.
        /// </summary>
        /// <param name="contact">The contact.</param>
        private void CheckName(ref tbl_Contact contact)
        {
            var nameChecker = new NameChecker(ConfigurationManager.AppSettings["ADONETConnectionString"]);
            var nameCheck   = nameChecker.CheckName(contact.UserFullName, NameCheckerFormat.FIO, Correction.Correct);

            if (!string.IsNullOrEmpty(nameCheck))
            {
                contact.UserFullName  = nameCheck;
                contact.Surname       = nameChecker.Surname;
                contact.Name          = nameChecker.Name;
                contact.Patronymic    = nameChecker.Patronymic;
                contact.IsNameChecked = nameChecker.IsNameCorrect;
            }
            else
            {
                contact.UserFullName  = contact.UserFullName;
                contact.Name          = string.Empty;
                contact.Surname       = string.Empty;
                contact.Patronymic    = string.Empty;
                contact.IsNameChecked = false;
            }
        }
        public ActionResult Index(tbl_Contact post)
        {
            if (ModelState.IsValid)
            {
                Stopwatch       sw        = Stopwatch.StartNew();
                ContactNotifier observer1 = new ContactNotifier();

                ActivityNotifier observer2 = new ActivityNotifier();

                post.date = DateTime.Now;


                db.tbl_Contact.Add(post);
                db.SaveChanges();



                TempData["SM"] = "You have added a new Record!";
                MainNotifier notifier = new MainNotifier();

                //ForumNotifier notifier = new ForumNotifier();


                notifier.Subscribe(observer1);

                notifier.Subscribe(observer2);

                notifier.Notify(post);

                sw.Stop();
                ViewBag.ExecutionTime = sw.Elapsed.Milliseconds;
                return(View("Index", post));
            }
            else
            {
                return(View("Index"));
            }
        }
Exemple #18
0
        /// <summary>
        /// Registers the user.
        /// </summary>
        /// <param name="siteId">The site id.</param>
        /// <param name="name">The name.</param>
        /// <param name="login">The login.</param>
        /// <param name="email">The email.</param>
        /// <param name="password">The password.</param>
        /// <param name="ip">The ip.</param>
        /// <returns></returns>
        public Guid RegisterUser(Guid siteId, string name, string login, string email, string password, string ip = null)
        {
            var dataManager = new DataManager();
            var status      = dataManager.Status.SelectDefault(siteId) ?? dataManager.Status.SelectAll(siteId).FirstOrDefault();

            var contact = new tbl_Contact
            {
                SiteID               = siteId,
                CreatedAt            = DateTime.Now,
                RefferURL            = string.Empty,
                UserIP               = ip ?? string.Empty,
                UserFullName         = name,
                Email                = email,
                StatusID             = status.ID,
                Score                = 0,
                BehaviorScore        = 0,
                CharacteristicsScore = 0,
                IsNameChecked        = false
            };

            dataManager.Contact.Add(contact);

            var user = new tbl_User
            {
                SiteID        = siteId,
                ContactID     = contact.ID,
                Login         = login,
                Password      = password,
                IsActive      = false,
                AccessLevelID = (int)AccessLevel.Portal
            };

            Add(user);

            return(contact.ID);
        }
Exemple #19
0
        /// <summary>
        /// Replaces the specified subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body.</param>
        public override void Replace(ref string subject, ref string body)
        {
            if (!SiteAction.ObjectID.HasValue)
            {
                return;
            }

            PortalSettings = DataManager.PortalSettings.SelectMapBySiteId(SiteAction.SiteID, true);

            ReplaceUserInfo(ref body);

            if (PortalSettings != null)
            {
                PortalLink = DataManager.PortalSettings.SelectPortalLink(PortalSettings.SiteID);
                RequirementLinkTemplate = RequirementLinkTemplate.Replace("#PortalLink#", PortalLink);
                RequestLinkTemplate     = RequestLinkTemplate.Replace("#PortalLink#", PortalLink);
            }

            var request = DataManager.Request.SelectById(SiteAction.SiteID, (Guid)SiteAction.ObjectID);

            if (request != null)
            {
                var         serviceLevel = request.tbl_ServiceLevel;
                tbl_Contact responsible  = null;
                tbl_Contact contact      = null;
                tbl_Company company      = null;

                if (request.ResponsibleID.HasValue)
                {
                    responsible = DataManager.Contact.SelectById(SiteAction.SiteID, (Guid)request.ResponsibleID);
                }
                if (request.ContactID.HasValue)
                {
                    contact = DataManager.Contact.SelectById(SiteAction.SiteID, (Guid)request.ContactID);
                }
                company = request.tbl_Company;

                subject = ReplaceText(subject, request, serviceLevel, responsible, contact, company);
                body    = ReplaceText(body, request, serviceLevel, responsible, contact, company);
                if (body.Contains("#Requirement.RegisteredList#"))
                {
                    var requirements = DataManager.Requirement.SelectByRequestId(request.SiteID, request.ID);

                    ProceedRegisteredRequirements(ref body, requirements);
                }

                if (company != null)
                {
                    body    = body.Replace("#Request.Notification.Company#", company.Name);
                    subject = subject.Replace("#Request.Notification.Company#", company.Name);
                }
                else
                {
                    body    = body.Replace("#Request.Notification.Company#", string.Empty);
                    subject = subject.Replace("#Request.Notification.Company#", string.Empty);
                }
            }


            var requirement = DataManager.Requirement.SelectById(SiteAction.SiteID, (Guid)SiteAction.ObjectID);

            if (requirement != null)
            {
                var shortDescription = requirement.ShortDescription;
                var requirementLink  = string.Format(RequirementLinkTemplate, requirement.ID);
                shortDescription = string.Format("<a href='{0}'>{1}</a>", requirementLink, shortDescription);

                body = body.Replace("#Requirement.ShortDescription#", shortDescription);

                if (requirement.CompanyID.HasValue)
                {
                    body    = body.Replace("#Requirement.Notification.Company#", requirement.tbl_Company.Name);
                    subject = subject.Replace("#Requirement.Notification.Company#", requirement.tbl_Company.Name);
                }
                else
                {
                    body    = body.Replace("#Requirement.Notification.Company#", string.Empty);
                    subject = subject.Replace("#Requirement.Notification.Company#", string.Empty);
                }
            }


            if (((body.Contains("#Requirement.WorkedList#") || body.Contains("#Requirement.CompanyList#") ||
                  body.Contains("#Requirement.CompletedList#")) && SiteAction.ContactID.HasValue))
            {
                var serviceLevelContact = DataManager.ServiceLevelContact.SelectById((Guid)SiteAction.ObjectID);

                if (serviceLevelContact != null)
                {
                    body    = body.Replace("#Requirement.Notification.Company#", serviceLevelContact.tbl_ServiceLevelClient.tbl_Company.Name);
                    subject = subject.Replace("#Requirement.Notification.Company#", serviceLevelContact.tbl_ServiceLevelClient.tbl_Company.Name);

                    var startDate = SiteAction.ActionDate.Date;
                    var endDate   = SiteAction.ActionDate.Date;
                    RequestNotificationService.GetDatesRangeByServiceLevelContact(serviceLevelContact, SiteAction.ActionDate.Date, ref startDate, ref endDate);

                    var requirements = new List <tbl_Requirement>();

                    switch ((ServiceLevelIncludeToInform)serviceLevelContact.IncludeToInformID)
                    {
                    case ServiceLevelIncludeToInform.All:
                        requirements = DataManager.Requirement.SelectAllByCompanyId(serviceLevelContact.tbl_ServiceLevelClient.ClientID, startDate, endDate).ToList();
                        break;

                    case ServiceLevelIncludeToInform.Personal:
                        requirements = DataManager.Requirement.SelectPersonal(serviceLevelContact.ContactID, startDate, endDate).ToList();
                        break;
                    }

                    body = body.Replace("#Requirement.CompanyList#", string.Empty);

                    ProceedWorkedRequirements(ref body, requirements.Where(o => !o.tbl_RequirementStatus.IsLast).ToList(), startDate, endDate);
                    ProceedCompletedRequirements(ref body, requirements.Where(o => o.tbl_RequirementStatus.IsLast).ToList());
                }
            }
        }
Exemple #20
0
        /// <summary>
        /// Replaces the text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="request">The request.</param>
        /// <param name="serviceLevel">The service level.</param>
        /// <param name="responsible">The responsible.</param>
        /// <param name="contact">The contact.</param>
        /// <param name="company">The company.</param>
        /// <returns></returns>
        protected string ReplaceText(string text, tbl_Request request, tbl_ServiceLevel serviceLevel, tbl_Contact responsible, tbl_Contact contact, tbl_Company company)
        {
            var shortDescription = request.ShortDescription;

            if (PortalSettings != null)
            {
                var requestLink = string.Format(RequestLinkTemplate, request.ID);
                shortDescription = string.Format("<a href='{0}'>{1}</a>", requestLink, shortDescription);
            }
            return(text.Replace("#Request.ShortDescription#", shortDescription)
                   .Replace("#Request.CreatedAt#", request.CreatedAt.ToString("dd.MM.yyyy"))
                   .Replace("#Request.ReactionTime#", serviceLevel.ReactionTime.ToString())
                   .Replace("#Request.Responsible.UserFullName#", responsible != null ? responsible.UserFullName : string.Empty)
                   .Replace("#Request.ReactionDatePlanned#", request.ReactionDatePlanned.HasValue ? ((DateTime)request.ReactionDatePlanned).ToString("dd.MM.yyyy") : string.Empty)
                   .Replace("#Request.Contact.UserFullName#", contact != null ? contact.UserFullName : string.Empty)
                   .Replace("#Request.Company.Name#", company != null ? company.Name : string.Empty));
        }
Exemple #21
0
        /// <summary>
        /// Handles the OnClick event of the lbtnInviteFriend control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void lbtnInviteFriend_OnClick(object sender, EventArgs e)
        {
            var refferContact = DataManager.Contact.SelectById(SiteId.Value, ContactId.Value);

            if (refferContact != null)
            {
                refferContact.Email        = txtEmail.Text;
                refferContact.UserFullName = txtFullName.Text;

                CheckName(ref refferContact);

                DataManager.Contact.Update(refferContact);

                var contact = new tbl_Contact
                {
                    SiteID        = SiteId.Value,
                    Email         = txtFriendEmail.Text,
                    UserFullName  = txtFriendName.Text,
                    RefferID      = ContactId,
                    RefferURL     = string.Empty,
                    IsNameChecked = false,
                    UserIP        = string.Empty,
                    StatusID      = DataManager.Status.SelectDefault(SiteId.Value).ID
                };

                CheckName(ref contact);

                DataManager.Contact.Add(contact);

                var siteAction = new tbl_SiteAction
                {
                    SiteID = SiteId.Value,
                    SiteActionTemplateID = SiteActionTemplateId.Value,
                    ContactID            = contact.ID,
                    ActionStatusID       = (int)ActionStatus.Scheduled,
                    ActionDate           = DateTime.Now
                };

                siteAction.tbl_SiteActionTagValue.Add(new tbl_SiteActionTagValue()
                {
                    ID           = Guid.NewGuid(),
                    SiteActionID = siteAction.ID,
                    Tag          = "#InviteFriend.Comment#",
                    Value        = txtComment.Text
                });
                siteAction.tbl_SiteActionTagValue.Add(new tbl_SiteActionTagValue()
                {
                    ID           = Guid.NewGuid(),
                    SiteActionID = siteAction.ID,
                    Tag          = "#System.SenderEmail#",
                    Value        = refferContact.Email
                });

                siteAction.tbl_SiteActionTagValue.Add(new tbl_SiteActionTagValue()
                {
                    ID           = Guid.NewGuid(),
                    SiteActionID = siteAction.ID,
                    Tag          = "#System.SenderUserFullName#",
                    Value        = refferContact.UserFullName
                });

                DataManager.SiteAction.Add(siteAction);

                if (WorkflowTemplateId.HasValue && WorkflowTemplateId.Value != Guid.Empty)
                {
                    DataManager.WorkflowTemplate.WorkflowInit(contact.ID, WorkflowTemplateId.Value);
                }

                plForm.Visible    = false;
                plSuccess.Visible = true;
            }
        }
Exemple #22
0
        public void Run()
        {
            DataManager dataManager = new DataManager();

            string msg    = "";
            bool   doSend = true;

            try
            {
                // Sites
                var sites = dataManager.Sites.SelectAll().Where(a => a.IsActive);
                foreach (var site in sites)
                {
                    try
                    {
                        // Site actions
                        List <tbl_SiteAction> siteActions = null;
                        siteActions =
                            dataManager.SiteAction.SelectAll(site.ID).Where(
                                a =>
                                a.ActionDate <= DateTime.Now &&
                                (ActionStatus)a.ActionStatusID == ActionStatus.Scheduled).ToList();


                        //Поиск дубликатов
                        var duplicates =
                            siteActions.GroupBy(sa => new { sa.SiteActionTemplateID, sa.ContactID }).Where(
                                x => x.Count() > 1).Select(group => new { group.Key }).ToList();
                        foreach (var duplicate in duplicates)
                        {
                            var contactId            = duplicate.Key.ContactID;
                            var siteActionTemplateId = duplicate.Key.SiteActionTemplateID;
                            //Выбираются все дубликаты пропуская первый
                            var siteActionsToCancel =
                                siteActions.Where(
                                    sa => sa.ContactID == contactId && sa.SiteActionTemplateID == siteActionTemplateId).
                                OrderByDescending(sa => sa.ActionDate).Skip(1).ToList();
                            //Установка дубликатам статуса Отменен
                            foreach (var siteAction in siteActionsToCancel)
                            {
                                if (!siteAction.SiteActionTemplateID.HasValue ||
                                    siteAction.tbl_SiteActionTemplate.SiteActionTemplateCategoryID !=
                                    (int)SiteActionTemplateCategory.System)
                                {
                                    siteAction.ActionStatusID = (int)ActionStatus.Cancelled;
                                    dataManager.SiteAction.Update(siteAction);
                                    WorkflowProcessing.Processing(
                                        WorkflowProcessing.WorkflowElementByValue(siteAction.ID),
                                        ((int)ActionStatus.Error).ToString());
                                }
                            }
                        }

                        //Если найдены дубликаты заново выбираем события
                        if (duplicates.Count > 0)
                        {
                            siteActions =
                                dataManager.SiteAction.SelectAll(site.ID).Where(
                                    a =>
                                    a.ActionDate <= DateTime.Now &&
                                    (ActionStatus)a.ActionStatusID == ActionStatus.Scheduled).ToList();
                        }

                        var siteActionGroups = siteActions.GroupBy(o => o.SiteActionTemplateID).Select(o => new { SiteActionTemplateId = o.Key, Count = o.Count() }).ToList();

                        foreach (var siteAction in siteActions)
                        {
                            msg    = "";
                            doSend = true;

                            var siteActionTemplate = siteAction.tbl_SiteActionTemplate;
                            var body = siteActionTemplate.MessageBody;

                            if (siteActionTemplate.ParentID.HasValue)
                            {
                                var parentSiteActionTemplate =
                                    dataManager.SiteActionTemplate.SelectById((Guid)siteActionTemplate.ParentID);
                                if (parentSiteActionTemplate != null &&
                                    parentSiteActionTemplate.MessageBody.Contains("#Text#"))
                                {
                                    body = parentSiteActionTemplate.MessageBody.Replace("#Text#",
                                                                                        siteActionTemplate.MessageBody);
                                }
                            }

                            var subject = siteAction.tbl_SiteActionTemplate.MessageCaption;

                            var contact = dataManager.Contact.SelectById(site.ID, (Guid)siteAction.ContactID);

                            if (body.Contains("#Advert#"))
                            {
                                body = body.Replace("#Advert#", GetAdvertBlock());
                            }
                            else if (site.ServiceAdvertisingActionID != null)
                            {
                                switch ((EmailAction)site.ServiceAdvertisingActionID)
                                {
                                case EmailAction.DoNotSend:
                                    doSend = false;
                                    break;

                                case EmailAction.Auto:
                                    body = body + "<br/>" + GetAdvertBlock();
                                    break;
                                }
                            }

                            var mailMessage = new MailMessage();

                            if (site.IsSendFromLeadForce)
                            {
                                mailMessage.Sender = new MailAddress("*****@*****.**", "LeadForce");
                            }

                            if (siteAction.tbl_SiteActionTagValue.Any(o => o.Tag == "#System.SenderEmail#"))
                            {
                                mailMessage.From = new MailAddress(siteAction.tbl_SiteActionTagValue.FirstOrDefault(o => o.Tag == "#System.SenderEmail#").Value,
                                                                   siteAction.tbl_SiteActionTagValue.FirstOrDefault(o => o.Tag == "#System.SenderUserFullName#").Value);
                            }
                            else
                            {
                                if (siteActionTemplate.FromContactRoleID.HasValue)
                                {
                                    var contactRole = dataManager.ContactRole.SelectById(site.ID, (Guid)siteActionTemplate.FromContactRoleID);
                                    if (contactRole != null)
                                    {
                                        tbl_Contact responsibleContact = null;
                                        switch ((ContactRoleType)contactRole.RoleTypeID)
                                        {
                                        case ContactRoleType.GeneralEmail:
                                            mailMessage.From = new MailAddress(contactRole.Email, contactRole.DisplayName);
                                            break;

                                        case ContactRoleType.ContactRole:
                                            responsibleContact = GetResponsible(site.ID, contactRole.ID, (Guid)siteAction.ContactID);
                                            if (responsibleContact != null)
                                            {
                                                mailMessage.From = new MailAddress(responsibleContact.Email, responsibleContact.UserFullName);
                                            }
                                            break;

                                        case ContactRoleType.WorkflowRole:
                                            responsibleContact = GetResponsible(site.ID, contactRole.ID, (Guid)siteAction.ContactID, WorkflowProcessing.GetWorkflowIdByValue(siteAction.ID));
                                            if (responsibleContact != null)
                                            {
                                                mailMessage.From = new MailAddress(responsibleContact.Email, responsibleContact.UserFullName);
                                            }
                                            break;
                                        }
                                        if ((ContactRoleType)contactRole.RoleTypeID != ContactRoleType.GeneralEmail && responsibleContact == null)
                                        {
                                            msg    = "Отсутствует отправитель";
                                            doSend = false;
                                        }
                                    }
                                }
                                else
                                {
                                    mailMessage.From = new MailAddress(siteActionTemplate.FromEmail, siteActionTemplate.FromName);
                                }
                            }

                            mailMessage.Headers.Add("Message-ID", string.Format("<{0}@{1}>", Guid.NewGuid(), mailMessage.From.Host));
                            mailMessage.HeadersEncoding = Encoding.UTF8;

                            if (siteActionGroups.SingleOrDefault(o => o.SiteActionTemplateId == siteAction.SiteActionTemplateID).Count > 5)
                            {
                                mailMessage.Headers.Add("Precedence", "bulk");
                            }

                            if (!string.IsNullOrEmpty(siteActionTemplate.ReplyToEmail))
                            {
                                mailMessage.ReplyToList.Add(new MailAddress(siteActionTemplate.ReplyToEmail,
                                                                            siteActionTemplate.ReplyToName));
                            }

                            bool isIncorrectEmail = false;

                            switch ((ActionType)siteActionTemplate.ActionTypeID)
                            {
                            case ActionType.EmailToUser:
                                if (string.IsNullOrEmpty(contact.Email) ||
                                    !Regex.IsMatch(contact.Email.Trim(),
                                                   @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"))
                                {
                                    msg = "Неверный E-mail посетителя";
                                    isIncorrectEmail = true;
                                    doSend           = false;
                                }
                                else
                                {
                                    try
                                    {
                                        mailMessage.To.Add(new MailAddress(contact.Email));
                                    }
                                    catch (Exception)
                                    {
                                        msg = "Неверный E-mail посетителя";
                                        isIncorrectEmail = true;
                                        doSend           = false;
                                    }
                                }
                                break;

                            case ActionType.EmailToFixed:
                                var recipients = GetSiteActionTemplateRecipients(site.ID, siteAction.ID, siteActionTemplate.ID, (Guid)siteAction.ContactID);
                                if (recipients.Any())
                                {
                                    foreach (var recipient in recipients)
                                    {
                                        mailMessage.To.Add(!string.IsNullOrEmpty(recipient.DisplayName)
                                                                   ? new MailAddress(recipient.Email, recipient.DisplayName)
                                                                   : new MailAddress(recipient.Email));
                                    }
                                }
                                else
                                {
                                    msg    = "Отсутствуют получатели";
                                    doSend = false;
                                }
                                break;
                            }

                            if (siteAction.MessageTypeID.HasValue)
                            {
                                TemplateTagsReplacer templateTagsReplacer = null;

                                switch ((MessageType)siteAction.MessageTypeID)
                                {
                                case MessageType.TaskNotification:
                                    templateTagsReplacer = new TaskNotificationTagsReplacer(siteAction);
                                    if (!body.Contains(GetAdvertBlock()))
                                    {
                                        if (body.Contains("#Advert#"))
                                        {
                                            body = body.Replace("#Advert#", GetAdvertBlock());
                                        }
                                        else
                                        {
                                            body = body + "<br/>" + GetAdvertBlock();
                                        }
                                    }
                                    break;

                                case MessageType.RequestNotification:
                                    templateTagsReplacer = new RequestNotificationTagsReplacer(siteAction);
                                    break;

                                case MessageType.RequirementCommentNotification:
                                    templateTagsReplacer = new RequirementCommentNotificationTagsReplacer(siteAction);
                                    break;

                                case MessageType.RequestCommentNotification:
                                    templateTagsReplacer = new RequestCommentNotificationTagsReplacer(siteAction);
                                    break;

                                case MessageType.InvoiceCommentNotification:
                                    templateTagsReplacer = new InvoiceCommentNotificationTagsReplacer(siteAction);
                                    break;

                                case MessageType.InvoiceNotification:
                                    templateTagsReplacer = new InvoiceNotificationTagsReplacer(siteAction, ref mailMessage);
                                    break;
                                }

                                if (templateTagsReplacer != null)
                                {
                                    templateTagsReplacer.Replace(ref subject, ref body);
                                }
                            }

                            body = body.Replace("=\"/files/",
                                                "=\"" +
                                                WebCounter.BusinessLogicLayer.Configuration.Settings.LeadForceSiteUrl +
                                                "/files/");

                            var user = dataManager.User.SelectByContactId(site.ID, contact.ID);
                            if (user != null)
                            {
                                if (siteAction.ObjectID.HasValue)
                                {
                                    body = body.Replace("#Activation.Url#",
                                                        WebCounter.BusinessLogicLayer.Configuration.Settings.
                                                        LabitecLeadForcePortalActivateUserUrl(
                                                            (Guid)siteAction.ObjectID, user.ID));
                                }

                                if (body.Contains("#User.Password#"))
                                {
                                    body = body.Replace("#User.Password#", user.Password)
                                           .Replace("#User.Email#", user.Login);
                                }
                            }

                            body = body.Replace("#User.UserFullName#", contact.UserFullName ?? "")
                                   .Replace("#User.LastName#", contact.Surname ?? "")
                                   .Replace("#User.FirstName#", contact.Name ?? "")
                                   .Replace("#User.MiddleName#", contact.Patronymic ?? "")
                                   .Replace("#User.Email#", contact.Email ?? "")
                                   .Replace("#User.Phone#", contact.Phone ?? "")
                                   .Replace("#User.Score#", contact.Score.ToString());

                            subject = subject.Replace("#User.UserFullName#", contact.UserFullName ?? "")
                                      .Replace("#User.LastName#", contact.Surname ?? "")
                                      .Replace("#User.FirstName#", contact.Name ?? "")
                                      .Replace("#User.MiddleName#", contact.Patronymic ?? "")
                                      .Replace("#User.Email#", contact.Email ?? "")
                                      .Replace("#User.Phone#", contact.Phone ?? "")
                                      .Replace("#User.Score#", contact.Score.ToString());

                            var portalLink = string.Format("<a href='{0}'>{0}</a>",
                                                           dataManager.PortalSettings.SelectPortalLink(
                                                               siteAction.SiteID, false));
                            subject = subject.Replace("#Portal.Link#", portalLink);
                            body    = body.Replace("#Portal.Link#", portalLink);

                            var r       = new Regex(@"#User.[\S]+?#");
                            var results = r.Matches(body);
                            foreach (Match result in results)
                            {
                                var siteColumns = dataManager.SiteColumns.SelectByCode(site.ID,
                                                                                       result.Value.Replace("#User.", "")
                                                                                       .Replace("#", ""));
                                if (siteColumns != null)
                                {
                                    var contactColumnValue = dataManager.ContactColumnValues.Select(contact.ID,
                                                                                                    siteColumns.ID);
                                    if (contactColumnValue != null)
                                    {
                                        switch ((ColumnType)contactColumnValue.tbl_SiteColumns.TypeID)
                                        {
                                        case ColumnType.String:
                                        case ColumnType.Number:
                                        case ColumnType.Text:
                                            body = body.Replace(result.Value,
                                                                contactColumnValue.StringValue.Replace("[BR]", "\n"));
                                            subject = subject.Replace(result.Value,
                                                                      contactColumnValue.StringValue.Replace(
                                                                          "[BR]", ""));
                                            break;

                                        case ColumnType.Date:
                                            body = body.Replace(result.Value,
                                                                ((DateTime)contactColumnValue.DateValue).ToString(
                                                                    "dd.MM.yyyy HH:mm"));
                                            subject = subject.Replace(result.Value,
                                                                      ((DateTime)contactColumnValue.DateValue).
                                                                      ToString("dd.MM.yyyy HH:mm"));
                                            break;

                                        case ColumnType.Enum:
                                            body = body.Replace(result.Value,
                                                                contactColumnValue.tbl_SiteColumnValues.Value);
                                            subject = subject.Replace(result.Value,
                                                                      contactColumnValue.tbl_SiteColumnValues.Value);
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        body    = body.Replace(result.Value, "");
                                        subject = subject.Replace(result.Value, "");
                                    }
                                }
                            }

                            MatchCollection matches;

                            if (siteActionTemplate.ReplaceLinksID != (int)ReplaceLinks.None)
                            {
                                //matches = Regex.Matches(body, "<a(.*)href=\"(?<href>\\S*)\"(.*)>(?<name>.*)</a>", RegexOptions.IgnoreCase);
                                matches = Regex.Matches(body, @"<a.*?href=[""'](?<href>.*?)[""'].*?>(?<name>.*?)</a>",
                                                        RegexOptions.IgnoreCase);
                                foreach (Match match in matches)
                                {
                                    if (match.Groups["href"].Value.Contains("#Link."))
                                    {
                                        continue;
                                    }

                                    var siteActionLink = dataManager.SiteActionLink.Select(contact.ID, siteAction.ID,
                                                                                           siteAction.
                                                                                           tbl_SiteActionTemplate.ID,
                                                                                           match.Groups["href"].Value);
                                    if (siteActionLink == null)
                                    {
                                        siteActionLink = new tbl_SiteActionLink
                                        {
                                            ContactID            = contact.ID,
                                            SiteActionID         = siteAction.ID,
                                            SiteActionTemplateID = siteActionTemplate.ID,
                                            LinkURL = match.Groups["href"].Value
                                        };
                                        dataManager.SiteActionLink.Add(siteActionLink);
                                    }
                                    //match.Groups[0].ToString()
                                    //body = Regex.Replace(body, string.Format("<a(.*)href=\"{0}\"(.*)>{1}</a>", Regex.Escape(match.Groups["href"].Value), Regex.Escape(match.Groups["name"].Value)), string.Format("<a href=\"{0}/linkService.aspx?ID={1}\" target=\"_blank\">{2}</a>", WebConfigurationManager.AppSettings["webServiceUrl"], siteActionLink.ID, match.Groups["name"].Value), RegexOptions.IgnoreCase);
                                    if (siteActionTemplate.ReplaceLinksID == (int)ReplaceLinks.ThroughService)
                                    {
                                        body = body.Replace(match.Groups[0].ToString(),
                                                            string.Format(
                                                                "<a href=\"{0}/linkService.aspx?ID={1}\" target=\"_blank\">{2}</a>",
                                                                WebConfigurationManager.AppSettings["webServiceUrl"],
                                                                siteActionLink.ID, match.Groups["name"].Value));
                                    }
                                    else if (siteActionTemplate.ReplaceLinksID == (int)ReplaceLinks.GoogleLinks)
                                    {
                                        const string utmSource = "LeadForce";
                                        const string utmMedium = "email";
                                        var          utmTerm   = match.Groups["name"].Value;
                                        utmTerm = Regex.Replace(utmTerm, @"<[^>]*>", string.Empty);
                                        var utmContent = siteActionLink.ID.ToString();
                                        var massMail   =
                                            dataManager.MassMail.SelectBySiteActionTemplateId(siteAction.SiteID,
                                                                                              siteActionTemplate.ID);
                                        var utmCampaign = massMail != null ? massMail.Name : subject;
                                        var queryParams =
                                            string.Format(
                                                "utm_source={0}&utm_medium={1}&utm_term={2}&utm_content={3}&utm_campaign={4}",
                                                utmSource, utmMedium, utmTerm, utmContent, utmCampaign);

                                        var url = match.Groups["href"].Value;

                                        try
                                        {
                                            Uri outUrl = null;
                                            if (Uri.TryCreate(url, UriKind.Absolute, out outUrl))
                                            {
                                                if (string.IsNullOrEmpty(outUrl.Query))
                                                {
                                                    url += "?" + queryParams;
                                                }
                                                else
                                                {
                                                    url += "&" + queryParams;
                                                }
                                            }
                                            else
                                            {
                                                url += "?" + queryParams;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Log.Error("Не верный формат ссылки", ex);
                                            url += "?" + queryParams;
                                        }

                                        body = body.Replace(match.Groups[0].ToString(),
                                                            string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>",
                                                                          url, match.Groups["name"].Value));
                                    }
                                }
                            }

                            matches = Regex.Matches(body, @"#Link.(?<code>[\S]+)#", RegexOptions.IgnoreCase);
                            foreach (Match match in matches)
                            {
                                var siteActionLink = dataManager.SiteActionLink.Select(contact.ID, siteAction.ID,
                                                                                       siteAction.tbl_SiteActionTemplate.ID,
                                                                                       dataManager.Links.Select(site.ID, match.Groups["code"].Value).ID);
                                if (siteActionLink == null)
                                {
                                    siteActionLink = new tbl_SiteActionLink
                                    {
                                        ContactID            = contact.ID,
                                        SiteActionID         = siteAction.ID,
                                        SiteActionTemplateID = siteAction.tbl_SiteActionTemplate.ID,
                                        SiteActivityRuleID   = dataManager.Links.Select(site.ID, match.Groups["code"].Value).ID
                                    };
                                    dataManager.SiteActionLink.Add(siteActionLink);
                                }

                                body = Regex.Replace(body,
                                                     string.Format("#Link.{0}#",
                                                                   Regex.Escape(match.Groups["code"].Value)),
                                                     string.Format("{0}/linkService.aspx?ID={1}",
                                                                   WebConfigurationManager.AppSettings["webServiceUrl"],
                                                                   siteActionLink.ID), RegexOptions.IgnoreCase);
                            }

                            if (body.Contains("#Unsubscribe#") || body.Contains("#User.Unsubscribe#") || body.Contains("#User.UnsubscribeLink#"))
                            {
                                if (body.Contains("#Unsubscribe#") || body.Contains("#User.Unsubscribe#"))
                                {
                                    body = body.Replace("#Unsubscribe#", GetUnsubscribeBlock(contact.ID, site.ID));
                                    body = body.Replace("#User.Unsubscribe#", GetUnsubscribeBlock(contact.ID, site.ID));
                                }
                                if (body.Contains("#User.UnsubscribeLink#"))
                                {
                                    body = body.Replace("#User.UnsubscribeLink#", GetUnsubscribeLink(contact.ID, site.ID));
                                }
                            }
                            else
                            {
                                if (!site.UnsubscribeActionID.HasValue)
                                {
                                    body = body + "<br/>" + GetUnsubscribeBlock(contact.ID, site.ID);
                                }
                                else
                                {
                                    switch ((EmailAction)site.UnsubscribeActionID)
                                    {
                                    case EmailAction.DoNotSend:
                                        doSend = false;
                                        break;

                                    case EmailAction.Auto:
                                        body = body + "<br/>" + GetUnsubscribeBlock(contact.ID, site.ID);
                                        break;
                                    }
                                }
                            }
                            foreach (var siteActionTagValue in siteAction.tbl_SiteActionTagValue)
                            {
                                subject = subject.Replace(siteActionTagValue.Tag, siteActionTagValue.Value);
                                body    = body.Replace(siteActionTagValue.Tag, siteActionTagValue.Value);
                            }
                            //mailMessage.Subject = siteAction.tbl_SiteActionTemplate.MessageCaption;
                            //byte[] bytes = Encoding.Default.GetBytes(subject);
                            //subject = Encoding.UTF8.GetString(bytes);
                            mailMessage.Subject         = subject.Replace(Environment.NewLine, string.Empty);
                            mailMessage.SubjectEncoding = Encoding.GetEncoding(1251);
                            mailMessage.Body            = body;
                            mailMessage.IsBodyHtml      = true;

                            try
                            {
                                siteAction.MessageTitle = mailMessage.Subject;
                                siteAction.MessageText  = mailMessage.Body;

                                if ((ActionType)siteActionTemplate.ActionTypeID == ActionType.EmailToUser)
                                {
                                    var emailStats = dataManager.EmailStats.SelectByEmail(contact.Email);

                                    //Если у контакта стоит статус email "Не работает" или "Запрещен" или не корректный email не отсылать почту
                                    if (isIncorrectEmail || contact.EmailStatusID == (int)EmailStatus.DoesNotWork ||
                                        contact.EmailStatusID == (int)EmailStatus.Banned ||
                                        (emailStats != null && (emailStats.ReturnCount > 5 || emailStats.tbl_EmailStatsUnsubscribe.Any(o => o.SiteID == contact.SiteID))))
                                    {
                                        siteAction.ActionStatusID = (int)ActionStatus.InvalidEmail;
                                        if (contact.EmailStatusID.HasValue)
                                        {
                                            switch ((EmailStatus)contact.EmailStatusID)
                                            {
                                            case EmailStatus.DoesNotWork:
                                                siteAction.Comments = "E-mail контакта со статусом \"Не работает\"";
                                                break;

                                            case EmailStatus.Banned:
                                                siteAction.Comments = "E-mail контакта со статусом \"Запрещен\"";
                                                break;

                                            default:
                                                siteAction.Comments = msg;
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            siteAction.Comments = msg;
                                        }

                                        if (emailStats != null && (emailStats.ReturnCount > 5 || emailStats.tbl_EmailStatsUnsubscribe.Any(o => o.SiteID == contact.SiteID)))
                                        {
                                            if (emailStats.ReturnCount > 5)
                                            {
                                                siteAction.Comments = "Большое количество возвратов. Нужно проверить корректность e-mail.";
                                            }
                                            if (emailStats.tbl_EmailStatsUnsubscribe.Any(o => o.SiteID == contact.SiteID))
                                            {
                                                siteAction.Comments = "Контакт отписан.";
                                            }
                                        }

                                        dataManager.SiteAction.Update(siteAction);
                                        WorkflowProcessing.Processing(
                                            WorkflowProcessing.WorkflowElementByValue(siteAction.ID),
                                            ((int)ActionStatus.Error).ToString());
                                        continue;
                                    }
                                }

                                if (doSend)
                                {
                                    var smtpClient = new SmtpClient();
                                    if (!string.IsNullOrEmpty(site.SmtpHost))
                                    {
                                        if (site.SmtpPort != null)
                                        {
                                            smtpClient = new SmtpClient(site.SmtpHost, (int)site.SmtpPort);
                                        }
                                        else
                                        {
                                            smtpClient = new SmtpClient(site.SmtpHost);
                                        }
                                        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                                        //smtpClient.EnableSsl = true;
                                        smtpClient.Credentials = new NetworkCredential(site.SmtpUsername,
                                                                                       site.SmtpPassword);
                                    }
                                    smtpClient.Send(mailMessage);

                                    Thread.Sleep(1000);

                                    dataManager.SiteActionTagValue.Delete(siteAction.ID);

                                    siteAction.ActionStatusID = (int)ActionStatus.Done;
                                    var sendedTo = string.Empty;
                                    foreach (var item in mailMessage.To)
                                    {
                                        sendedTo = sendedTo + item.Address + ", ";
                                    }
                                    sendedTo            = sendedTo.TrimEnd().TrimEnd(',');
                                    siteAction.Comments = string.Format("Отправлено на {0}", sendedTo);
                                    //siteAction.Comments = string.Format("Отправлено на {0}", mailMessage.To[0].Address);
                                    dataManager.SiteAction.Update(siteAction);
                                    WorkflowProcessing.Processing(
                                        WorkflowProcessing.WorkflowElementByValue(siteAction.ID),
                                        ((int)ActionStatus.Done).ToString());
                                }
                                else
                                {
                                    siteAction.ActionStatusID = (int)ActionStatus.Error;
                                    siteAction.Comments       = msg;
                                    dataManager.SiteAction.Update(siteAction);
                                    WorkflowProcessing.Processing(
                                        WorkflowProcessing.WorkflowElementByValue(siteAction.ID),
                                        ((int)ActionStatus.Error).ToString());
                                }
                            }
                            catch (Exception ex)
                            {
                                siteAction.ActionStatusID = (int)ActionStatus.Error;
                                siteAction.Comments       = ex.ToString();
                                dataManager.SiteAction.Update(siteAction);
                                WorkflowProcessing.Processing(WorkflowProcessing.WorkflowElementByValue(siteAction.ID),
                                                              ((int)ActionStatus.Error).ToString());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(string.Format("Scheduler ERROR: {0}", site.ID), ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Scheduler ERROR: ", ex);
            }
        }
Exemple #23
0
 /// <summary>
 /// Updates the specified site user.
 /// </summary>
 /// <param name="contact">The site user.</param>
 public void Update(tbl_Contact contact)
 {
     _dataContext.SaveChanges();
 }
Exemple #24
0
        /// <summary>
        /// Handles the OnClick event of the lbtnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void lbtnSave_OnClick(object sender, EventArgs e)
        {
            var site = DataManager.Sites.SelectById(_siteId) ?? new tbl_Sites();

            site.Name = txtName.Text;
            site.LinkProcessingURL = txtLinkProcessingURL.Text;
            site.IsActive          = chxIsActive.Checked;
            site.IsTemplate        = chxIsTemplate.Checked;
            site.SmtpHost          = txtSmtpHost.Text;
            site.SmtpUsername      = txtSmtpUsername.Text;
            site.SmtpPassword      = txtSmtpPassword.Text;

            int smtpPort;

            if (int.TryParse(txtSmtpPort.Text, out smtpPort))
            {
                site.SmtpPort = smtpPort;
            }
            else
            {
                site.SmtpPort = null;
            }

            site.SystemEmail                 = txtSystemEmail.Text;
            site.IsAllowUseSystemEmail       = chxIsAllowUseSystemEmail.Checked;
            site.IsSendEmailToSubscribedUser = chxIsSendEmailToSubscribedUser.Checked;
            site.IsSendFromLeadForce         = chxIsSendFromLeadForce.Checked;

            if (rblUnsubscribeActions.SelectedValue != string.Empty)
            {
                site.UnsubscribeActionID = int.Parse(rblUnsubscribeActions.SelectedValue);
            }
            else
            {
                site.UnsubscribeActionID = null;
            }

            if (rblServiceAdvertisingActions.SelectedValue != string.Empty)
            {
                site.ServiceAdvertisingActionID = int.Parse(rblServiceAdvertisingActions.SelectedValue);
            }
            else
            {
                site.ServiceAdvertisingActionID = null;
            }

            int maxFileSize;

            if (int.TryParse(txtMaxFileSize.Text, out maxFileSize))
            {
                site.MaxFileSize = maxFileSize;
            }

            int fileQuota;

            if (int.TryParse(txtFileQuota.Text, out fileQuota))
            {
                site.FileQuota = fileQuota;
            }

            int sessionTimeout;

            if (int.TryParse(txtSessionTimeout.Text, out sessionTimeout))
            {
                site.SessionTimeout = sessionTimeout;
            }

            int userSessionTimeout;

            if (int.TryParse(txtUserSessionTimeout.Text, out userSessionTimeout))
            {
                site.UserSessionTimeout = userSessionTimeout;
            }

            if (rcbAccessProfile.SelectedValue != Guid.Empty.ToString())
            {
                site.AccessProfileID = Guid.Parse(rcbAccessProfile.SelectedValue);
            }
            else
            {
                site.AccessProfileID = null;
            }

            site.IsBlockAccessFromDomainsOutsideOfList = chxIsBlockAccessFromDomainsOutsideOfList.Checked;
            site.MainUserID      = ucMainUser.SelectedIdNullable;
            site.ActiveUntilDate = rdpActiveUntilDate.SelectedDate;
            site.PriceListID     = ucPriceList.SelectedIdNullable;
            site.PayerCompanyID  = ucPayerCompany.SelectedIdNullable;

            if (site.ID == Guid.Empty)
            {
                if (site.AccessProfileID != null)
                {
                    var accessProfile = DataManager.AccessProfile.SelectById(site.AccessProfileID.Value);
                    if (accessProfile != null && accessProfile.DomainsCount > 0)
                    {
                        site.IsBlockAccessFromDomainsOutsideOfList = true;
                    }
                }

                site.ID = Guid.NewGuid();
                site    = DataManager.Sites.Add(site);

                var contact = new tbl_Contact
                {
                    SiteID        = site.ID,
                    Email         = txtEmail.Text,
                    UserFullName  = txtEmail.Text,
                    RefferID      = null,
                    RefferURL     = string.Empty,
                    IsNameChecked = false,
                    UserIP        = string.Empty,
                    StatusID      = DataManager.Status.SelectDefault(site.ID).ID
                };
                DataManager.Contact.Add(contact);

                var user = new tbl_User
                {
                    SiteID        = site.ID,
                    Login         = txtEmail.Text,
                    Password      = txtPassword.Text,
                    IsActive      = true,
                    AccessLevelID = 1,
                    ContactID     = contact.ID
                };

                DataManager.User.Add(user);
                site.MainUserID = user.ID;
                DataManager.Sites.Update(site);
            }
            else
            {
                DataManager.Sites.Update(site);
            }

            tagsSite.SaveTags(site.ID);

            Response.Redirect(UrlsData.AP_Sites());
        }
Exemple #25
0
 public void add(tbl_Contact item)
 {
     rep.add(item);
 }
        /// <summary>
        /// Adds the request.
        /// </summary>
        /// <param name="sourceMonitoring">The source monitoring.</param>
        /// <param name="siteActionId">The site action id.</param>
        /// <param name="shortDescription">The short description.</param>
        /// <param name="longDescription">The long description.</param>
        /// <param name="sender">The sender.</param>
        private void AddRequest(tbl_SourceMonitoring sourceMonitoring, Guid siteActionId, string shortDescription, string longDescription, tbl_Contact sender)
        {
            if (sender == null)
            {
                return;
            }

            _dataManager.Request.Add(sourceMonitoring.SiteID, siteActionId,
                                     sourceMonitoring.RequestSourceTypeID, shortDescription, longDescription, sender.ID, null);
        }
Exemple #27
0
 public void update(tbl_Contact item)
 {
     rep.update(item);
 }
        /// <summary>
        /// Proceeds the external form.
        /// </summary>
        /// <param name="siteId">The site id.</param>
        /// <param name="siteActivityRuleExternalFormId">The site activity rule external form id.</param>
        /// <param name="code">The code.</param>
        /// <param name="contactId">The contact id.</param>
        /// <param name="values">The values.</param>
        /// <param name="key">The key.</param>
        /// <param name="actionDate">The action date.</param>
        public static void ProceedExternalForm(Guid siteId, Guid siteActivityRuleExternalFormId, string code, Guid?contactId, IEnumerable <KeyValuePair <string, string> > values, string key, DateTime actionDate)
        {
            //
            // !!! Если contactId передаётся HasValue - внешняя форма; если contactId is null - форма Wufoo
            //
            var dataManager = new DataManager();

            var fields = dataManager.SiteActivityRuleExternalFormFields.SelectByExternalFormId(siteActivityRuleExternalFormId).Where(a => a.SiteColumnID != null || a.SysField != null).ToList();

            tbl_Contact contact = null;

            string ip = string.Empty;

            if (contactId.HasValue)
            {
                contact = dataManager.Contact.SelectById(siteId, contactId.Value);
            }
            else
            {
                if (!string.IsNullOrEmpty(key))
                {
                    var importKey = dataManager.ImportKey.SelectByKey(key, "tbl_Contact");
                    if (importKey != null)
                    {
                        return;
                    }
                }

                ip = values.SingleOrDefault(o => o.Key == "IP").Value;

                var contactActivityByIP = dataManager.ContactActivity.SelectByIP(siteId, ip, ActivityType.ViewPage, actionDate.AddMinutes(-10), actionDate.AddMinutes(10)).FirstOrDefault();

                if (contactActivityByIP == null)
                {
                    var status = dataManager.Status.SelectDefault(siteId) ??
                                 dataManager.Status.SelectAll(siteId).FirstOrDefault();

                    contact = new tbl_Contact
                    {
                        SiteID               = siteId,
                        CreatedAt            = actionDate,
                        RefferURL            = string.Empty,
                        UserIP               = ip,
                        UserFullName         = string.Empty,
                        Email                = string.Empty,
                        StatusID             = status.ID,
                        Score                = 0,
                        BehaviorScore        = 0,
                        CharacteristicsScore = 0,
                        IsNameChecked        = false,
                        LastActivityAt       = actionDate
                    };
                    dataManager.Contact.Add(contact);
                }
                else
                {
                    contact = dataManager.Contact.SelectById(siteId, contactActivityByIP.ContactID);
                }

                dataManager.ImportKey.Add(new tbl_ImportKey
                {
                    ImportID    = siteActivityRuleExternalFormId,
                    LeadForceID = contact.ID,
                    TableName   = "tbl_Contact",
                    Key         = key
                });
            }

            var keyValuesPairs = new List <KeyValuePair <string, string> >();

            foreach (var field in fields)
            {
                keyValuesPairs.Add(field.SysField != null
                                       ? new KeyValuePair <string, string>(field.SysField, values.SingleOrDefault(o => o.Key == field.Name).Value)
                                       : new KeyValuePair <string, string>(field.SiteColumnID.ToString(), values.SingleOrDefault(o => o.Key == field.Name).Value));
            }

            var contactData = new ContactData(siteId);

            contact = contactData.SaveForm(contact.ID, keyValuesPairs);


            /*foreach (var field in fields)
             * {
             *  tbl_ContactColumnValues contactColumnValue = null;
             *  if (field.SiteColumnID != null)
             *  {
             *      contactColumnValue = dataManager.ContactColumnValues.Select(contact.ID, (Guid)field.SiteColumnID);
             *      if (contactColumnValue == null)
             *      {
             *          contactColumnValue = new tbl_ContactColumnValues();
             *          contactColumnValue.ContactID = contact.ID;
             *          contactColumnValue.SiteColumnID = (Guid)field.SiteColumnID;
             *      }
             *  }
             *
             *
             *  switch ((FormFieldType)field.FieldType)
             *  {
             *      case FormFieldType.Input:
             *      case FormFieldType.Textarea:
             *          if (field.SysField != null)
             *          {
             *              switch (field.SysField)
             *              {
             *                  case "sys_fullname":
             *                      var nameChecker = new NameChecker(ConfigurationManager.AppSettings["ADONETConnectionString"]);
             *                      var nameCheck = nameChecker.CheckName(values.SingleOrDefault(o => o.Key == field.Name).Value, NameCheckerFormat.FIO, Correction.Correct);
             *                      if (!string.IsNullOrEmpty(nameCheck))
             *                      {
             *                          contact.UserFullName = nameCheck;
             *                          contact.Surname = nameChecker.Surname;
             *                          contact.Name = nameChecker.Name;
             *                          contact.Patronymic = nameChecker.Patronymic;
             *                          contact.IsNameChecked = nameChecker.IsNameCorrect;
             *                          if (nameChecker.Gender.HasValue)
             *                              contact.Gender = (int)nameChecker.Gender.Value;
             *                      }
             *                      else
             *                          contact.UserFullName = values.SingleOrDefault(o => o.Key == field.Name).Value;
             *                      break;
             *                  case "sys_email":
             *                      contact.Email = values.SingleOrDefault(o => o.Key == field.Name).Value;
             *                      break;
             *                  case "sys_phone":
             *                      contact.Phone = values.SingleOrDefault(o => o.Key == field.Name).Value;
             *                      break;
             *                  case "sys_jobtitle":
             *                      contact.JobTitle = values.SingleOrDefault(o => o.Key == field.Name).Value;
             *                      break;
             *                  case "sys_keywords":
             *                      keywords = values.SingleOrDefault(o => o.Key == field.Name).Value;
             *                      break;
             *                  case "sys_refferurl":
             *                      contact.RefferURL = values.SingleOrDefault(o => o.Key == field.Name).Value;
             *                      break;
             *                  case "sys_advertisingplatform":
             *                      if (!string.IsNullOrEmpty(values.SingleOrDefault(o => o.Key == field.Name).Value))
             *                          contact.AdvertisingPlatformID = dataManager.AdvertisingPlatform.SelectByTitleAndCreate(contact.SiteID, values.SingleOrDefault(o => o.Key == field.Name).Value).ID;
             *                      break;
             *                  case "sys_advertisingtype":
             *                      if (!string.IsNullOrEmpty(values.SingleOrDefault(o => o.Key == field.Name).Value))
             *                          contact.AdvertisingTypeID = dataManager.AdvertisingType.SelectByTitleAndCreate(contact.SiteID, values.SingleOrDefault(o => o.Key == field.Name).Value).ID;
             *                      break;
             *                  case "sys_advertisingcampaign":
             *                      if (!string.IsNullOrEmpty(values.SingleOrDefault(o => o.Key == field.Name).Value))
             *                          contact.AdvertisingCampaignID = dataManager.AdvertisingCampaign.SelectByTitleAndCreate(contact.SiteID, values.SingleOrDefault(o => o.Key == field.Name).Value).ID;
             *                      break;
             *                  case "sys_comment":
             *                      contact.Comment = values.SingleOrDefault(o => o.Key == field.Name).Value;
             *                      break;
             *                  case "sys_surname":
             *                      contact.Surname = values.SingleOrDefault(o => o.Key == field.Name).Value;
             *                      contact.UserFullName = string.Format("{0} {1} {2}", contact.Surname, contact.Name, contact.Patronymic);
             *                      break;
             *                  case "sys_name":
             *                      contact.Name = values.SingleOrDefault(o => o.Key == field.Name).Value;
             *                      contact.UserFullName = string.Format("{0} {1} {2}", contact.Surname, contact.Name, contact.Patronymic);
             *                      break;
             *                  case "sys_patronymic":
             *                      contact.Patronymic = values.SingleOrDefault(o => o.Key == field.Name).Value;
             *                      contact.UserFullName = string.Format("{0} {1} {2}", contact.Surname, contact.Name, contact.Patronymic);
             *                      break;
             *              }
             *          }
             *          else
             *          {
             *              if (contactColumnValue != null)
             *                  contactColumnValue.StringValue = values.SingleOrDefault(o => o.Key == field.Name).Value;
             *          }
             *          break;
             *      case FormFieldType.Select:
             *          var siteColumnValues = dataManager.SiteColumnValues.SelectAll((Guid)field.SiteColumnID);
             *          var columnValue = siteColumnValues.Where(a => a.Value.ToLower() == values.SingleOrDefault(o => o.Key == field.Name).Value.ToLower()).FirstOrDefault();
             *          if (columnValue == null)
             *          {
             *              var newColumnValue = new tbl_SiteColumnValues
             *              {
             *                  SiteColumnID = (Guid)field.SiteColumnID,
             *                  Value = values.SingleOrDefault(o => o.Key == field.Name).Value
             *              };
             *              columnValue = dataManager.SiteColumnValues.Add(newColumnValue);
             *          }
             *
             *          if (contactColumnValue != null)
             *              contactColumnValue.SiteColumnValueID = columnValue.ID;
             *          break;
             *  }
             *
             *  if (contactColumnValue != null)
             *  {
             *      if (contactColumnValue.ID == Guid.Empty)
             *          dataManager.ContactColumnValues.Add(contactColumnValue);
             *      else
             *          dataManager.ContactColumnValues.Update(contactColumnValue);
             *  }
             *  //dataManager.Contact.Update(contact);
             * }
             *
             * dataManager.Contact.Update(contact);*/

            CounterServiceHelper.AddContactActivity(siteId, contact.ID, ActivityType.FillForm, actionDate, code, ip);

            if (!contactId.HasValue)
            {
                var contactSession = dataManager.ContactSessions.SelectFirstSession(contact.SiteID, contact.ID);
                if (contactSession != null)
                {
                    //contactSession.Keywords = keywords;
                    if (values.Any(o => o.Key == "sys_keywords"))
                    {
                        contactSession.Keywords = values.SingleOrDefault(o => o.Key == "sys_keywords").Value;
                    }
                    contactSession.AdvertisingCampaignID = contact.AdvertisingCampaignID;
                    contactSession.AdvertisingPlatformID = contact.AdvertisingPlatformID;
                    contactSession.AdvertisingTypeID     = contact.AdvertisingTypeID;
                    contactSession.RefferURL             = contact.RefferURL;
                    contactSession.UserIP = contact.UserIP;
                    dataManager.ContactSessions.Update(contactSession);
                }
            }
        }
        /// <summary>
        /// Proceeds the POP3 source.
        /// </summary>
        /// <param name="sourceMonitoring">The source monitoring.</param>
        private void ProceedPOP3Source(tbl_SourceMonitoring sourceMonitoring)
        {
            using (var client = new Pop3Client())
            {
                client.Connect(sourceMonitoring.PopHost, (int)sourceMonitoring.PopPort, sourceMonitoring.IsSsl);
                client.Authenticate(sourceMonitoring.PopUserName, sourceMonitoring.PopPassword, AuthenticationMethod.UsernameAndPassword);
                var messageCount = client.GetMessageCount();

                //Log.Debug(string.Format("Мониторинг ID: {0} количество сообщений {1}", sourceMonitoring.ID, messageCount));

                for (int messageNumber = 1; messageNumber <= messageCount; messageNumber++)
                {
                    try
                    {
                        MessageHeader headers = client.GetMessageHeaders(messageNumber);

                        //Log.Debug(string.Format("Мониторинг ID: {0} дата сообщения {1}", sourceMonitoring.ID, headers.DateSent));

                        if (!_dataManager.SiteAction.IsExistPOPMessage(headers.MessageId) && !_dataManager.EmailToAnalysis.IsExistPOPMessage(headers.MessageId) && (!sourceMonitoring.StartDate.HasValue || headers.DateSent >= sourceMonitoring.StartDate))
                        {
                            //Log.Debug(string.Format("Мониторинг ID: {0} тема {1}", sourceMonitoring.ID, headers.Subject));

                            var isValidMessage = true;

                            var from    = headers.From;
                            var subject = headers.Subject ?? string.Empty;

                            //Фильтр сообщений по полям
                            var sourceMonitoringFilters = sourceMonitoring.tbl_SourceMonitoringFilter.ToList();
                            foreach (var sourceMonitoringFilter in sourceMonitoringFilters)
                            {
                                var regex = new Regex(sourceMonitoringFilter.Mask, RegexOptions.IgnoreCase);

                                switch ((SourceEmailProperty)sourceMonitoringFilter.SourcePropertyID)
                                {
                                case SourceEmailProperty.FromEmail:
                                    isValidMessage = !regex.IsMatch(from.Address);
                                    break;

                                case SourceEmailProperty.FromName:
                                    isValidMessage = !regex.IsMatch(from.DisplayName);
                                    break;

                                case SourceEmailProperty.Title:
                                    isValidMessage = !regex.IsMatch(subject);
                                    break;
                                }

                                if (!isValidMessage)
                                {
                                    break;
                                }
                            }

                            var message     = client.GetMessage(messageNumber);
                            var messageText = string.Empty;

                            if (message.FindFirstHtmlVersion() != null)
                            {
                                messageText = message.FindFirstHtmlVersion().GetBodyAsText();
                            }
                            else if (message.FindFirstPlainTextVersion() != null)
                            {
                                messageText = message.FindFirstPlainTextVersion().GetBodyAsText();
                            }

                            foreach (var sourceMonitoringFilter in sourceMonitoringFilters.Where(smf => (SourceEmailProperty)smf.SourcePropertyID == SourceEmailProperty.Text))
                            {
                                isValidMessage = !new Regex(sourceMonitoringFilter.Mask, RegexOptions.IgnoreCase).IsMatch(messageText);
                                if (!isValidMessage)
                                {
                                    break;
                                }
                            }

                            tbl_Contact sender = _dataManager.Contact.SelectByEmail(sourceMonitoring.SiteID, from.Address);
                            //Обработка возвратов
                            var isReturn = false;
                            if (POP3MonitoringProcessingOfReturnsFromFilterCheck(from, messageText))
                            {
                                sender   = null;
                                isReturn = true;
                                var regex       = new Regex(@"(?<email>(\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*))", RegexOptions.IgnoreCase);
                                var match       = regex.Match(messageText);
                                var returnEmail = string.Empty;
                                if (match.Success)
                                {
                                    returnEmail = match.Groups["email"].Value;

                                    sender = _dataManager.Contact.SelectByEmail(sourceMonitoring.SiteID, returnEmail);
                                    if (sender == null)
                                    {
                                        isValidMessage = false;
                                    }

                                    var emailStats = _dataManager.EmailStats.SelectByEmail(returnEmail);
                                    if (emailStats != null)
                                    {
                                        emailStats.ReturnCount++;
                                        _dataManager.EmailStats.Update(emailStats);
                                    }
                                    else
                                    {
                                        _dataManager.EmailStats.Add(new tbl_EmailStats {
                                            ReturnCount = 1, Email = returnEmail
                                        });
                                    }
                                }
                                else
                                {
                                    var emailToAnalysis = new tbl_EmailToAnalysis
                                    {
                                        SourceMonitoringID = sourceMonitoring.ID,
                                        From         = headers.From.Address,
                                        Name         = headers.From.DisplayName,
                                        MessageText  = messageText,
                                        Subject      = subject,
                                        POPMessageID = headers.MessageId
                                    };
                                    _dataManager.EmailToAnalysis.Add(emailToAnalysis);
                                    isValidMessage = false;
                                }

                                if ((ProcessingOfReturns)sourceMonitoring.ProcessingOfReturnsID == ProcessingOfReturns.ChangeEmailStatus ||
                                    (ProcessingOfReturns)sourceMonitoring.ProcessingOfReturnsID == ProcessingOfReturns.Download)
                                {
                                    if (!string.IsNullOrEmpty(returnEmail) && sender == null && sourceMonitoring.PopUserName == "*****@*****.**")
                                    {
                                        var siteAction = _dataManager.SiteAction.SelectByEmail(returnEmail).FirstOrDefault();
                                        if (siteAction != null)
                                        {
                                            sender = _dataManager.Contact.SelectById(siteAction.SiteID, siteAction.ContactID.Value);
                                        }
                                    }
                                    if (sender != null)
                                    {
                                        if ((ProcessingOfReturns)sourceMonitoring.ProcessingOfReturnsID == ProcessingOfReturns.ChangeEmailStatus)
                                        {
                                            sender.EmailStatusID = (int)EmailStatus.DoesNotWork;
                                            _dataManager.Contact.Update(sender);
                                        }

                                        var siteAction = _dataManager.SiteAction.SelectByContactId(sender.ID).FirstOrDefault();
                                        if (siteAction != null)
                                        {
                                            siteAction.ActionStatusID = (int)ActionStatus.InvalidEmail;
                                            siteAction.Comments      += " 550 user not found";
                                            _dataManager.SiteAction.Update(siteAction);
                                        }

                                        _dataManager.SiteAction.Add(new tbl_SiteAction
                                        {
                                            SiteID             = sender.SiteID,
                                            ActionStatusID     = (int)ActionStatus.Done,
                                            ActionDate         = DateTime.Now,
                                            MessageTitle       = subject,
                                            SourceMonitoringID = sourceMonitoring.ID,
                                            DirectionID        = (int)Direction.In,
                                            SenderID           = (sender == null ? null : (Guid?)sender.ID),
                                            MessageText        = messageText,
                                            Comments           = "Получено от " + sender.Email,
                                            IsHidden           = true,
                                            POPMessageID       = headers.MessageId
                                        });

                                        //Формируется действие с типом Возврат сообщения
                                        _dataManager.ContactActivity.Add(new tbl_ContactActivity
                                        {
                                            SiteID             = sender.SiteID,
                                            ContactID          = sender.ID,
                                            ActivityTypeID     = (int)ActivityType.ReturnMessage,
                                            ActivityCode       = "returnMessage",
                                            ContactSessionID   = null,
                                            SourceMonitoringID = sourceMonitoring.ID
                                        });
                                    }
                                }
                            }

                            //Обработка отправителя по правилу: "Загружать по известным контактам"
                            if (!isReturn && ((SenderProcessing)sourceMonitoring.SenderProcessingID == SenderProcessing.LoadOfKnownContacts) && sender == null)
                            {
                                isValidMessage = false;
                            }

                            if (isValidMessage)
                            {
                                //Обработка автоответов
                                var isAutoReply = false;
                                if (POP3MonitoringProcessingOfAutorepliesFilters(subject, messageText))
                                {
                                    isAutoReply = true;
                                    switch ((ProcessingOfAutoReplies)sourceMonitoring.ProcessingOfAutoRepliesID)
                                    {
                                    case ProcessingOfAutoReplies.Skip:
                                        isValidMessage = false;
                                        break;
                                    }
                                }

                                if (isValidMessage && !isReturn)
                                {
                                    //Обработка отправителя по правилу: "Создавать новый контакт"
                                    if ((SenderProcessing)sourceMonitoring.SenderProcessingID == SenderProcessing.CreateNewContact && sender == null)
                                    {
                                        sender = CreateSender(sourceMonitoring.SiteID, headers.From);

                                        if (sender.Email.Split('@').Length == 2)
                                        {
                                            var company = _dataManager.Company.SearchByDomain(sourceMonitoring.SiteID, sender.Email.Split('@')[1]);
                                            if (company != null)
                                            {
                                                sender.CompanyID = company.ID;
                                            }
                                        }

                                        sender = _dataManager.Contact.Add(sender);
                                    }

                                    var addSiteAction = true;

                                    if ((SenderProcessing)sourceMonitoring.SenderProcessingID == SenderProcessing.ServiceLevelContacts)
                                    {
                                        if (sender == null)
                                        {
                                            addSiteAction = false;
                                        }
                                        else
                                        {
                                            var serviceLevelContact = _dataManager.ServiceLevelContact.SelectByContactId(sender.ID);
                                            if (serviceLevelContact != null)
                                            {
                                                addSiteAction = serviceLevelContact.IsAutomateDownload;
                                            }
                                            else
                                            {
                                                addSiteAction = false;
                                            }
                                        }
                                    }

                                    if (addSiteAction)
                                    {
                                        var siteAction = new tbl_SiteAction
                                        {
                                            SiteID             = sourceMonitoring.SiteID,
                                            ActionStatusID     = (int)ActionStatus.Done,
                                            ActionDate         = DateTime.Now,
                                            MessageTitle       = subject,
                                            SourceMonitoringID = sourceMonitoring.ID,
                                            DirectionID        = (int)Direction.In,
                                            SenderID           = (sender == null ? null : (Guid?)sender.ID),
                                            MessageText        = messageText,
                                            Comments           = "Получено от " + sender.Email,
                                            IsHidden           = false,
                                            POPMessageID       = headers.MessageId
                                        };

                                        _dataManager.SiteAction.Add(siteAction);

                                        messageText = ProceedAttachments(siteAction, message.FindAllAttachments());

                                        //Формируется действие с типом Входящее сообщение
                                        _dataManager.ContactActivity.Add(new tbl_ContactActivity
                                        {
                                            SiteID         = sourceMonitoring.SiteID,
                                            ContactID      = sender.ID,
                                            ActivityTypeID =
                                                (int)ActivityType.InboxMessage,
                                            ActivityCode       = subject,
                                            ContactSessionID   = null,
                                            SourceMonitoringID =
                                                sourceMonitoring.ID
                                        });

                                        if (sourceMonitoring.RequestSourceTypeID.HasValue)
                                        {
                                            var shortDescription = string.Format("{0} (email от {1})", subject,
                                                                                 headers.DateSent.ToString("dd.MM.yyyy hh:mm"));
                                            AddRequest(sourceMonitoring, siteAction.ID, shortDescription, messageText, sender);
                                        }
                                    }
                                }

                                if (!sourceMonitoring.IsLeaveOnServer &&
                                    sourceMonitoring.DaysToDelete != null &&
                                    headers.DateSent < DateTime.Now.AddDays((int)sourceMonitoring.DaysToDelete) ||
                                    (isReturn && sourceMonitoring.IsRemoveReturns) ||
                                    (isAutoReply && sourceMonitoring.IsRemoveAutoReplies))
                                {
                                    client.DeleteMessage(messageNumber);
                                }
                            }

                            //Отрабатываются возможные события.

                            /*if (sender != null)
                             *  CounterServiceHelper.CheckEvent(sourceMonitoring.SiteID, sender.ID);*/
                        }
                        else if (sourceMonitoring.StartDate.HasValue && headers.DateSent < sourceMonitoring.StartDate)
                        {
                            var tmpMessage = client.GetMessage(messageNumber);
                            //Log.Debug(string.Format("Мониторинг ID: {0} загрузка сообщения {1}", sourceMonitoring.ID, headers.Subject));
                        }

                        if (!sourceMonitoring.IsLeaveOnServer && sourceMonitoring.DaysToDelete != null && headers.DateSent < DateTime.Now.AddDays((int)sourceMonitoring.DaysToDelete))
                        {
                            client.DeleteMessage(messageNumber);
                        }
                    }
                    catch (IOException ioex)
                    {
                        Log.Warn(string.Format("Ошибка обработки сообщения {0}, POP3 мониторинг ID : {1}", messageNumber, sourceMonitoring.ID), ioex);
                    }
                    catch (FormatException fex)
                    {
                        Log.Warn(string.Format("Ошибка обработки сообщения {0}, POP3 мониторинг ID : {1}", messageNumber, sourceMonitoring.ID), fex);
                    }
                    catch (OpenPop.Pop3.Exceptions.PopServerException pex)
                    {
                        client.Disconnect();
                        client.Connect(sourceMonitoring.PopHost, (int)sourceMonitoring.PopPort, sourceMonitoring.IsSsl);
                        client.Authenticate(sourceMonitoring.PopUserName, sourceMonitoring.PopPassword, AuthenticationMethod.UsernameAndPassword);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(string.Format("Ошибка обработки сообщения {0}, POP3 мониторинг ID : {1}", messageNumber, sourceMonitoring.ID), ex);
                    }

                    Thread.Sleep(500);
                }

                client.Disconnect();
            }
        }