Exemplo n.º 1
0
        public static void UpdateMailBox(IUserMailbox obj)
        {
            var uid = GetUid(obj.EmailLogin);

            if (obj.Uid != uid)
            {
                obj.Uid = uid;
            }
            if (obj.EmailParticipant == null)
            {
                obj.EmailParticipant             = InterfaceActivator.Create <IEmailMessageParticipantUser>();
                obj.EmailParticipant.Mailbox     = obj;
                obj.EmailParticipant.EmailString = obj.EmailLogin;
                obj.EmailParticipant.User        = obj.Owner;
            }
            else
            {
                if (obj.EmailParticipant.EmailString != obj.EmailLogin)
                {
                    obj.EmailParticipant.Name        = obj.EmailLogin;
                    obj.EmailParticipant.EmailString = obj.EmailLogin;
                }
            }

            if (obj.EmailPassword != DefaultPassword)
            {
                obj.PasswordEncoded = EncryptionHelper.EncryptPwd(obj.EmailPassword);
                obj.EmailPassword   = DefaultPassword;
            }
        }
Exemplo n.º 2
0
        //TODO сделать лицензирование
        public void SendToUpdate()
        {
            var securityService = Locator.GetService <ISecurityService>();

            securityService.RunByUser(
                EleWise.ELMA.Security.Managers.UserManager.Instance.Load(SecurityConstants.AdminUserUid),
                () =>
            {
                var size   = 100;
                var index  = 0;
                var filter = InterfaceActivator.Create <IUserMailboxFilter>();
                filter.DisableAutoFilter = true;
                filter.DisableSecurity   = true;
                var mailboxes            = Find(new FetchOptions()
                {
                    FirstResult = index,
                    MaxResults  = size
                });
                while (mailboxes.Any())
                {
                    index += size;
                    foreach (var userMailbox in mailboxes)
                    {
                        SendToUpdate(userMailbox);
                    }

                    if (mailboxes.Count < size)
                    {
                        break;
                    }
                }
            });
        }
Exemplo n.º 3
0
 public JobResult Do(DateTime dateToRun)
 {
     try
     {
         Locator.GetServiceNotNull <ISecurityService>().RunWithElevatedPrivilegies(() =>
         {
             var mailReadersService = Locator.GetServiceNotNull <IMailReadersService>();
             var mailRequest        = InterfaceActivator.Create <IMailRequestI>();
             mailRequest.Name       = $"Новый запрос на прочтение почты";
             mailRequest.Pisjma.AddAll(mailReadersService.GetUnreadMailMessages(mailRequest));
             mailReadersService.RunProcessesMailMassages(mailRequest);
         });
         return(new JobResult
         {
             Status = JobStatus.Success,
             Information = SR.T("Успешно выполнено"),
             NoSaveResult = true
         });
     }
     catch (Exception ex)
     {
         return(new JobResult
         {
             Status = JobStatus.Fail,
             ErrorDescription = ex.StackTrace,
             Information = SR.T($"Ошибка выполнения - {ex.Message}"),
             NoSaveResult = false
         });
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Отправление сообщения пользователю
        /// </summary>
        /// <param name="user">Кому направляется</param>
        /// <param name="subj">Тема</param>
        /// <param name="mes">Текст сообщения</param>
        public void SendMessage(User user, string subj, string mes)
        {
            //создание нового сообщения:
            var m = InterfaceActivator.Create <ChannelMessage>();

            //добавление в список получателей пользователя, который хранится в переменной context.Poljzovatelj типа Пользователь
            m.Recipients.Add(user);
            m.Subject     = subj;
            m.MessageType = ChannelMessageType.Post;
            //указание автора сообщения
            m.CreationAuthor = system;
            //указание даты создания сообщения:
            m.CreationDate = DateTime.Now;
            //содержание сообщения:
            m.FullMessage = mes;
            //создание статуса сообщения (новое или прочитанное)
            var s = InterfaceActivator.Create <RecipientMessageStatus>();

            s.Message   = m;
            s.Recipient = user;
            //статус сообщения: новое
            s.Status = MessageStatus.New;
            s.Save();
            //добавление статуса в сообщение
            m.Statuses.Add(s);
            //сохранение сообщения
            m.Save();
        }
Exemplo n.º 5
0
        public void CreateMessage(long incidentId)
        {
            var incident = EntityManager <IIncident> .Instance.LoadOrNull(incidentId);

            if (incident != null)
            {
                var message = InterfaceActivator.Create <IChannelMessage>();

                // Получение списка получателей из настроек модуля
                var settings = Locator.GetService <MailSnifferSettingsModule>().Settings;
                message.Recipients.AddAll(settings.NotifyUsers);

                message.Subject        = SR.T("Зафиксирован инцидент со статусом {0}", incident.Status);
                message.MessageType    = ChannelMessageType.Post;
                message.CreationAuthor = UserManager.Load(SecurityConstants.SystemUserUid);
                message.CreationDate   = DateTime.Now;
                message.FullMessage    = SR.T("{0} {1} был зафиксирован инцидент со статусом {2}. Ознакомьтесь с содержимым во вложении."
                                              , incident.CreationDate.Value.ToShortDateString()
                                              , incident.CreationDate.Value.ToShortTimeString()
                                              , incident.Status);
                //message.Attachments.Add(AttachmentManager.Instance.Create(incident.ThreadFile));

                // Создание статуса сообщения (новое или прочитанное)
                foreach (var recipient in message.Recipients)
                {
                    var status = InterfaceActivator.Create <IRecipientMessageStatus>();
                    status.Message   = message;
                    status.Recipient = recipient;
                    status.Status    = MessageStatus.New;
                    status.Save();
                    message.Statuses.Add(status);
                }
                message.Save();
            }
        }
Exemplo n.º 6
0
        public void GenerateAttachmentsFromFile(IIncident incident)
        {
            var files = new List <BinaryFile>();

            if (incident != null && incident.AttachmentList.Any())
            {
                foreach (var attachment in incident.AttachmentList)
                {
                    var fileList = GetAttachments(attachment.File);
                    if (fileList.Any())
                    {
                        files.AddRange(fileList);
                    }
                }
            }

            foreach (var file in files)
            {
                var attachment = InterfaceActivator.Create <IAttachment>();
                attachment.File           = file;
                attachment.CreationDate   = DateTime.Now;
                attachment.CreationAuthor = UserManager.Instance.GetCurrentUser();
                attachment.Save();

                incident.MailAttachments.Add(attachment);
            }

            incident.Save();
        }
        protected virtual List <IEntity> LoadEntities(Type cardType, Func <ICriteria, ICriteria> criteriaAction, List <Guid> typeUidFilter)
        {
            var serviceNotNull = Locator.GetServiceNotNull <EmailFullTextSearchSettingsModule>();

            if (serviceNotNull.Settings == null || !serviceNotNull.Settings.IndexingEmail)
            {
                return(new List <IEntity>());
            }

            if (cardType == null || typeof(IEmailMessageFullTextSearchObject) != cardType)
            {
                return(new List <IEntity>());
            }
            var list = new List <IEntity>();

            SecurityService.RunBySystemUser(delegate
            {
                SecurityService.RunWithElevatedPrivilegies(delegate
                {
                    var session = SessionProvider.GetSession("");
                    var source  = criteriaAction(session.CreateCriteria(InterfaceActivator.TypeOf <IEmailMessage>()).AddOrder(Order.Asc("Id")).SetMaxResults(GetPageSize())).List().Cast <IEntity>();
                    (from d in source
                     where d != null
                     select d).ForEach(list.Add);
                });
            });
            return(list);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Сохранение записи
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult Save(CatalogItemModel model)
        {
            /*
             * Нужно выводить информацию при ошибках в серверной валидации. Сейчас почему-то не выводится. Поэтому серверная валидация убрана.
             * if (!ModelState.IsValid)
             * {
             *  if (model.InPopUp)
             *  {
             *      return Json(new { error = SR.T("Не заполнены все обязательные поля") }, JsonRequestBehavior.AllowGet);
             *  }
             *  Notifier.Information(SR.T("Не заполнены все обязательные поля"));
             *  var template = "Add";
             *  return View(template, model);
             * }
             */
            var entityType = IMetadataRuntimeService.GetTypeByUid(model.TypeUid);
            var manager    = ModelHelper.GetEntityManager(entityType);

            try
            {
                manager.Save(model.Entity);
            }
            catch (Exception ex)
            {
                Locator.GetServiceNotNull <IUnitOfWorkManager>().RollbackCurrent("");
                Notifier.Error(ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message) ? ex.InnerException.Message : ex.Message);
                return(!IsCreatorRequest() ? View("Add", model) : CreatorJson(model.Entity, ex.Message));
            }
            if (IsCreatorRequest())
            {
                return(CreatorJson(model.Entity));
            }
            if (model.InPopUp)
            {
                return(Json(new { model.Continue }, JsonRequestBehavior.AllowGet));
            }
            if (!string.IsNullOrEmpty(model.BackUrl))
            {
                var filter      = InterfaceActivator.Create <IDeptTrans_CatalogFilter>();
                var entityType1 = new ReferenceOnEntityType {
                    TypeUid = model.TypeUid
                };
                filter.Spravochnik = entityType1;
                //filter.TypeUidSpravochnika = model.TypeUid;
                var listMyEntity = EntityManager <IDeptTrans_Catalog> .Instance.Find(filter, null);

                if (listMyEntity.Any())
                {
                    var newUrl = GenerateViewItemUrl(model.TypeUid, model.Entity.GetId(), null, null);
                    return(Redirect(newUrl));
                }
                else
                {
                    return(Redirect(model.BackUrl));
                }
            }
            return(RedirectToAction("View", new { area = CommonAreaRegistration.AREA_NAME, uid = model.TypeUid }));
        }
Exemplo n.º 9
0
        public ICollection <BinaryFile> GetAttachments(BinaryFile file)
        {
            var files = new List <BinaryFile>();

            var filePath = file.ContentFilePath;
            var bytes    = File.ReadAllBytes(filePath);
            var iso      = Encoding.GetEncoding("ISO-8859-1");
            var content  = iso.GetString(bytes);

            //var content = WebDocumentManager.Instance.GetContentFromFile(file);
            if (content.Contains(AttachmentContentName))
            {
                content = content.Remove(0, content.IndexOf(AttachmentContentName));
                var index       = content.IndexOf("\r\n\r\n");
                var contentInfo = content.Substring(0, index);
                var match       = new Regex("filename=\"(?<encodedFileName>[^\"]+)\"").Match(contentInfo);
                var fileName    = "";
                if (match.Groups["encodedFileName"].Success)
                {
                    var encodedFileName = match.Groups["encodedFileName"].Value;
                    fileName = HttpUtility.UrlDecode(Encoding.UTF8.GetString(iso.GetBytes(encodedFileName)));
                }
                else
                {
                    fileName = string.Format("MailAttachment_{0}_{1}.txt", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString());
                }

                content = content.Remove(0, index + 4);
                index   = content.IndexOf("------WebKitFormBoundary");
                var attachmentContent = content.Remove(index);

                var fullFileName = @"C:\TEMP\" + fileName;
                var fileInfo     = new FileInfo(fullFileName);
                if (!fileInfo.Exists)
                {
                    fileInfo.Create().Dispose();
                }

                using (var fileStream = fileInfo.OpenWrite())
                {
                    //var encoding = Encoding.GetEncoding(1251);
                    //fileStream.Write(encoding.GetBytes(attachmentContent), 0, attachmentContent.Length);
                    fileStream.Write(iso.GetBytes(attachmentContent), 0, attachmentContent.Length);
                }
                var attachmentFile = InterfaceActivator.Create <BinaryFile>();
                attachmentFile.Name       = fileName;
                attachmentFile.CreateDate = DateTime.Now;
                attachmentFile.InitializeContentFilePath();
                File.Copy(fullFileName, attachmentFile.ContentFilePath);
                Locator.GetServiceNotNull <IFileManager>().SaveFile(attachmentFile);
                files.Add(attachmentFile);
            }

            return(files);
        }
Exemplo n.º 10
0
        private static void UpdateByContact(EleWise.ELMA.CRM.Models.IContact contact, Contact newContact, string email)
        {
            if (IsBad(contact.Firstname) &&
                !IsBad(newContact.FirstName))
            {
                contact.Firstname = newContact.FirstName;
            }

            if (IsBad(contact.Middlename) &&
                !IsBad(newContact.MiddleName))
            {
                contact.Middlename = newContact.MiddleName;
            }

            if (IsBad(contact.Surname) &&
                !IsBad(newContact.LastName))
            {
                contact.Surname = newContact.LastName;
            }

            if (IsBad(contact.Position) &&
                !IsBad(newContact.Position))
            {
                contact.Position = newContact.Position;
            }

            if (string.IsNullOrWhiteSpace(contact.Site) &&
                !string.IsNullOrWhiteSpace(newContact.Site))
            {
                contact.Site = newContact.Site;
            }

            //TODO переназвать
            if (IsBad(contact.Department) &&
                !IsBad(newContact.Description))
            {
                contact.Department = newContact.Description;
            }

            if (newContact.Phones?.Any() ?? false)
            {
                var newPhones =
                    newContact.Phones?.Where(
                        p => contact.Phone.All(c => c.PhoneString != p.PhoneString)).ToList();
                foreach (var newPhone in newPhones)
                {
                    var phone = InterfaceActivator.Create <IPhone>();
                    phone.PhoneString = newPhone.PhoneString;
                    contact.Phone.Add(phone);
                }
            }
        }
        internal static IEmailMessageParticipant CreateParticipant(ContactSummary contactSummary, IContact currentContact)
        {
            var emailMessageParticipant = InterfaceActivator.Create <IEmailMessageParticipantContact>();

            emailMessageParticipant.Contact     = currentContact;
            emailMessageParticipant.EmailString = contactSummary.Email;
            emailMessageParticipant.Save();
            if (Logger.IsDebugEnabled())
            {
                Logger.Log(LogLevel.Debug, $"Created ParticipantContact: {emailMessageParticipant.EmailString}");
            }

            return(emailMessageParticipant);
        }
        public override SortList GetDefaultSortExpression()
        {
            var propMd    = InterfaceActivator.LoadPropertyMetadata((IEmailMessage m) => m.DateUtc) as EntityPropertyMetadata;
            var sortField = FullTextSearchDescriptorService.GetSortField(propMd);

            if (sortField == null)
            {
                throw new FullTextFilterException(SR.T("{1}: Поле \"{0}\" не поддерживает сортировку", "SortTypeId", "Dynamic Indexing Error"));
            }
            sortField.Direction = ListSortDirection.Descending;
            var sortList = new SortList {
                sortField
            };

            return(sortList);
        }
Exemplo n.º 13
0
        public IIncident FindNearOrCreateIncident(string ip)
        {
            var beginDate = DateTime.Now.Subtract(new TimeSpan(0, 0, 10));

            var criteria = Session.CreateCriteria <IIncident>();

            criteria.Add(Restrictions.Eq("IPAdress", ip));
            criteria.Add(Restrictions.Ge("CreationDate", beginDate));
            var incident = criteria.UniqueResult <IIncident>();

            if (incident != null)
            {
                return(incident);
            }
            else
            {
                return(InterfaceActivator.Create <IIncident>());
            }
        }
Exemplo n.º 14
0
        private static List <IEmailMessageParticipant> EmailMessageParticipants(IUserMailbox userMailbox, IMessagePart emailMessage, IEmailMessage message)
        {
            var contactSummaries = emailMessage.From.ToList();

            contactSummaries.AddRange(emailMessage.To);
            var emailList = contactSummaries.Select(c => c.Email).ToList();

            var emailMessageParticipantManager = EmailMessageParticipantManager.Instance;
            var participants = emailMessageParticipantManager.GetParticipants(emailList).ToList();

            var notExistingParticipants =
                contactSummaries
                .Where(c =>
                       participants.All(e => e.EmailString != c.Email)).ToList();

            if (notExistingParticipants.Any())
            {
                var securityService = Locator.GetServiceNotNull <ISecurityService>();
                securityService.RunByUser(userMailbox.Owner, () =>
                {
                    var newParticipants = emailMessageParticipantManager.CreateParticipants(notExistingParticipants);
                    participants.AddRange(newParticipants);
                });
            }
            var existContactParticipants = participants
                                           .Where(c => c.TypeUid == InterfaceActivator.UID <IEmailMessageParticipantContact>())
                                           .Select(c => c.CastAsRealType() is IEmailMessageParticipantContact participantContact
                    ? participantContact
                    : null)
                                           .Where(c => c != null).ToList();

            var contacts =
                existContactParticipants.Select(c => c.Contact)
                .Where(c => c != null).ToList();
            var contractors =
                contacts.Select(c => c.Contractor)
                .Where(c => c != null).ToList();

            message.Contacts.AddAll(contacts);
            message.Contractors.AddAll(contractors);

            return(participants);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Sends this error as a notification email to the address in web.config as Error.Notification.Receiver.
        /// </summary>
        public static IEmailMessage SendAsNotification(this Exception error, string toNotify)
        {
            if (toNotify.IsEmpty())
            {
                return(null);
            }

            var email = InterfaceActivator.CreateInstance <IEmailMessage>();

            email.To      = toNotify;
            email.Subject = "Error In Application";
            email.Body    = $"URL: {Context.Current.Request()?.ToAbsoluteUri()}{Environment.NewLine}" +
                            $"IP: {Context.Current.Http()?.Connection?.RemoteIpAddress}{Environment.NewLine}" +
                            $"User: {Context.Current.User().GetId()}{Environment.NewLine}" +
                            error.ToLogString(error.Message);

            Context.Current.Database().Save(email);

            return(email);
        }
Exemplo n.º 16
0
        public bool EventCreate(EventCreatorModel model)
        {
            var      date        = model.Date;
            var      timeFrom    = model.TimeFrom;
            var      timeTo      = model.TimeTo;
            var      subject     = model.Subject;
            var      description = model.Description;
            DateTime DateTimeFrom;
            DateTime DateTimeTo;

            if (!parseDateTime(date, timeFrom, timeTo, out DateTimeFrom, out DateTimeTo))
            {
                return(false);
            }

            try
            {
                var curUser = AuthenticationService.GetCurrentUser <IUser>();

                var calEvent     = InterfaceActivator.Create <ICalendarEvent>();
                var calEventUser = InterfaceActivator.Create <ICalendarEventUser>();
                calEventUser.User = curUser;
                calEventUser.Save();
                calEvent.EventUsers.Add(calEventUser);

                calEvent.StartDate      = DateTimeFrom;
                calEvent.EndDate        = DateTimeTo;
                calEvent.Subject        = subject;
                calEvent.Description    = description;
                calEvent.CreationDate   = DateTime.Now;
                calEvent.CreationAuthor = curUser;
                calEvent.Save();
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 17
0
        internal void UpdateDomains(List <string> domains)
        {
            var uids       = domains.Select(c => new { domain = c, uid = GetUid(c) }).ToList();
            var uidsString = string.Join(",", uids.Select(c => $"'{c.uid}'"));

            var session = _sessionProvider.GetSession("");

            var hqlQuery =
                session.CreateQuery(
                    "select publicdomain.Uid FROM PublicDomain publicdomain " +
                    $"where publicdomain.Uid in ({uidsString})");

            hqlQuery.SetMaxResults(domains.Count);
            var existingDomains = hqlQuery.List <Guid>();
            var newDomains      = uids.Where(c => !existingDomains.Contains(c.uid));

            foreach (var newDomain in newDomains)
            {
                var publicDomain = InterfaceActivator.Create <IPublicDomain>();
                publicDomain.Name = newDomain.domain;
                publicDomain.Save();
            }
        }
        internal static IContractorExt CreateContractor(string domain)
        {
            var publicDomains = PublicDomainManager.Instance.GetPublicDomains();

            if (string.IsNullOrWhiteSpace(domain) || publicDomains.Contains(domain))
            {
                return(null);
            }

            //Теоретчиески у всез у кого домены - все юрики
            var contractorLegal = InterfaceActivator.Create <IContractorLegal>();

            var mailboxDomain = InterfaceActivator.Create <IMailboxDomain>();

            mailboxDomain.Name       = domain;
            mailboxDomain.Contractor = contractorLegal;
            mailboxDomain.Save();
            contractorLegal.Name          = domain;
            contractorLegal.LegalAddress  = InterfaceActivator.Create <IAddress>();
            contractorLegal.PostalAddress = InterfaceActivator.Create <IAddress>();
            contractorLegal.Responsible   = UserManager.Instance.GetCurrentUser();
            var contractorExt = (contractorLegal as IContractorExt);

            if (contractorExt != null)
            {
                contractorExt.Domains.Add(mailboxDomain);
                ContractorManager.Instance.SaveWithCategoryRules(contractorLegal);

                if (Logger.IsDebugEnabled())
                {
                    Logger.Log(LogLevel.Debug, $"Created ContractorLegal: {domain}");
                }
            }

            return(contractorExt);
        }
Exemplo n.º 19
0
        public IEmailMessage Save(EmailMessage emailMessage)
        {
            //TODO письма без тела - бесполезные пока нет загрузки файлов
            if (string.IsNullOrWhiteSpace(emailMessage.Body))
            {
                return(null);
            }
            var message = EmailMessageManager.Instance.Load(emailMessage.Hash);

            if (message != null)
            {
                return(message);
            }
            message = InterfaceActivator.Create <IEmailMessage>();
            var userMailboxs = GetOwners(emailMessage.Owners);

            message.Owners.AddAll(userMailboxs);
            message.DateUtc            = emailMessage.DateUtc;
            message.Hash               = emailMessage.Hash;
            message.MainHeader         = ConvertHeader(emailMessage.MainHeader);
            message.Text               = emailMessage.Text;
            message.Body               = ConvertBody(emailMessage.Body);
            message.IsBodyHtml         = emailMessage.IsBodyHtml;
            message.Subject            = emailMessage.Subject;
            message.SubjectWithoutTags = emailMessage.SubjectWithoutTags;
            message.Direction          = (EmailDirection)(int)emailMessage.Direction;
            if (Logger.IsDebugEnabled())
            {
                Logger.Log(LogLevel.Debug, $"{message.DateUtc?.ToLocalTime():g} :{ message.Direction} : { message.Subject}");
            }
            FillParticipants(userMailboxs.FirstOrDefault(), emailMessage, message);

            message.Tags = ConvertTags(emailMessage.Tags);
            message.Save();
            return(message);
        }
        public override Type GetSupportedCardTypeByTypeUid(Guid objectTypeUid)
        {
            var emailFullTextSearchSettingsModule = SettingModule as EmailFullTextSearchSettingsModule;

            if (emailFullTextSearchSettingsModule?.Settings == null || !emailFullTextSearchSettingsModule.Settings.IndexingEmail)
            {
                return(null);
            }
            var classMetadata = (ClassMetadata)MetadataLoader.LoadMetadata(objectTypeUid);
            var emailUid      = InterfaceActivator.UID <IEmailMessage>();

            if (classMetadata != null && (classMetadata.Uid == emailUid || MetadataLoader.GetBaseClasses(classMetadata).Any(delegate(ClassMetadata m)
            {
                if (m != null)
                {
                    return(m.Uid == emailUid);
                }
                return(false);
            })))
            {
                return(typeof(IEmailMessageFullTextSearchObject));
            }
            return(null);
        }
Exemplo n.º 21
0
        public EmailMessagesPage Contact(long id, string searchString, int skip, int size)
        {
            if (size > 1000)
            {
                size = 1000;
            }

            if (size > 1000)
            {
                size = 1000;
            }
            //TODO
            //var session = _sessionProvider.GetSession("");
            var filter  = InterfaceActivator.Create <IEmailMessageFilter>();
            var contact = ContactManager.Instance.Load(id);

            filter.Contacts.Add(contact);
            filter.SearchString    = searchString;
            filter.DisableSecurity = true;
            var count = Count(filter);// ContractorCount(id, searchString);

            if (skip < count)
            {
                /*
                 * var hqlQuery =
                 *  session.CreateQuery(
                 *      "select em " +
                 *      "from  EmailMessage as em " +
                 *      "left join em.To emto " +
                 *      "left join em.From emfrom " +
                 *      "where " +
                 *      "em.IsDeleted <> 1 AND " +
                 *      "(em.Subject LIKE :searchString OR " +
                 *      "em.Body LIKE :searchString ) AND" +
                 *      "(emto.Id in (select empcto.Id from EmailMessageParticipantContact as empcto  left join  empcto.Contact contact left join contact.Contractor contractor where contractor.Id = :id) OR  " +
                 *      "emfrom.Id in (select empcto.Id from EmailMessageParticipantContact as empcto  left join  empcto.Contact contact left join contact.Contractor contractor where contractor.Id = :id)) " +
                 *      "ORDER BY em.DateUtc DESC");
                 * hqlQuery.SetParameter("id", id);
                 * hqlQuery.SetParameter("searchString", $"%{searchString}%");
                 * hqlQuery.SetFirstResult(skip);
                 * hqlQuery.SetMaxResults(size);
                 * var emailMessages = hqlQuery.List<IEmailMessage>();
                 */

                return(new EmailMessagesPage()
                {
                    Messages = Find(filter, new FetchOptions(skip, size)).Select(Simplify).ToArray(),
                    Size = size,
                    Skip = skip,
                    Count = count
                });
            }
            else
            {
                return(new EmailMessagesPage()
                {
                    Skip = skip,
                    Size = size,
                    Count = count,
                    Messages = new Message[0]
                });
            }
        }
Exemplo n.º 22
0
        public long CreateIncident(Guid guidFile, bool streamIsBlocked, string userIp, string fileName)
        {
            var incident = IncidentManager.Instance.FindNearOrCreateIncident(userIp);

            if (incident.Id == 0)
            {
                incident.Save();
                var user = UserManager.Instance.Find(u => (u as IUserExt) != null && (u as IUserExt).IPAdress == userIp).FirstOrDefault();
                incident.IPAdress     = userIp;
                incident.User         = user;
                incident.CreationDate = DateTime.Now;
                incident.Name         = SR.T("Инцидент от {0} {1}", incident.CreationDate.Value.ToShortDateString(), incident.CreationDate.Value.ToLongTimeString());
            }

            incident.LastIncidentDate = DateTime.Now;

            var file = BinaryFileDescriptor.Download(guidFile);

            var attachment = InterfaceActivator.Create <IAttachment>();

            attachment.File           = file;
            attachment.CreationDate   = DateTime.Now;
            attachment.CreationAuthor = UserManager.Instance.GetCurrentUser();

            incident.AttachmentList.Add(attachment);

            var service = Locator.GetService <IncidentService>();
            var descriptionStringBuilder = new StringBuilder();

            descriptionStringBuilder.AppendLine(SR.T("Проверка почтового потока:"));

            descriptionStringBuilder.AppendLine(SR.T("Совпадения по предупреждающему фильтру:"));
            var warningResult = service.CheckFileOnWarningFilter(file);

            descriptionStringBuilder.AppendLine(warningResult.Any() ? string.Join(Environment.NewLine, warningResult.Select(w => " - " + w)) : SR.T("Не найдено"));

            descriptionStringBuilder.AppendLine(SR.T("Совпадения по стоп фильтру:"));
            var stopResult = service.CheckFileOnStopFilter(file);

            descriptionStringBuilder.AppendLine(stopResult.Any() ? string.Join(Environment.NewLine, stopResult.Select(w => " - " + w)) : SR.T("Не найдено"));

            bool mailAttachmentIsWarning = false, mailAttachmentIsBlocked = false;
            var  mailAttachments = service.GetAttachments(file);

            foreach (var mailAttachmentFile in mailAttachments)
            {
                var mailAttachment = InterfaceActivator.Create <IAttachment>();
                mailAttachment.File           = mailAttachmentFile;
                mailAttachment.CreationDate   = DateTime.Now;
                mailAttachment.CreationAuthor = UserManager.Instance.GetCurrentUser();
                mailAttachment.Save();

                incident.MailAttachments.Add(mailAttachment);
                descriptionStringBuilder.AppendLine(SR.T("Проверка вложений:"));

                descriptionStringBuilder.AppendLine(SR.T("Совпадения по предупреждающему фильтру:"));
                var mailAttachmentWarningResult = service.CheckFileOnWarningFilter(mailAttachmentFile);
                descriptionStringBuilder.AppendLine(mailAttachmentWarningResult.Any() ? string.Join(Environment.NewLine, mailAttachmentWarningResult.Select(w => " - " + w)) : SR.T("Не найдено"));
                mailAttachmentIsWarning |= mailAttachmentWarningResult.Any();

                descriptionStringBuilder.AppendLine(SR.T("Совпадения по стоп фильтру:"));
                var mailAttachmentStopResult = service.CheckFileOnStopFilter(mailAttachmentFile);
                descriptionStringBuilder.AppendLine(mailAttachmentStopResult.Any() ? string.Join(Environment.NewLine, mailAttachmentStopResult.Select(w => " - " + w)) : SR.T("Не найдено"));
                mailAttachmentIsBlocked |= mailAttachmentStopResult.Any();
            }

            if (incident.Status != SniffState.Stop)
            {
                if (stopResult.Any() || mailAttachmentIsBlocked)
                {
                    incident.Status = SniffState.Stop;
                }
                else
                {
                    if (incident.Status != SniffState.Warning)
                    {
                        incident.Status = (warningResult.Any() || mailAttachmentIsWarning) ? SniffState.Warning : SniffState.Ok;
                    }
                    incident.Status = streamIsBlocked ? SniffState.Stop : SniffState.Warning;
                }
            }

            incident.Description = descriptionStringBuilder.ToString();
            incident.Save();

            //service.CreateMessage(incident.Id);
            if (!service.CheckStartedProcesses(incident))
            {
                service.StartProcess(incident);
            }
            return(incident.Id);
        }
        internal static IContact CreateContact(ContactSummary notExistingContactSummary)
        {
            var contact = InterfaceActivator.Create <IContact>();

            contact.Name = notExistingContactSummary.Fio;
            var email = InterfaceActivator.Create <IEmail>();

            email.EmailString           = notExistingContactSummary.Email;
            contact.RegistrationAddress = InterfaceActivator.Create <IAddress>();
            contact.ResidenceAddress    = InterfaceActivator.Create <IAddress>();
            contact.Email.Add(email);

            var fio        = RuleOrNull(notExistingContactSummary.Fio);
            var newContact = notExistingContactSummary.Contact;

            if (newContact != null)
            {
                contact.Surname    = newContact.LastName;
                contact.Firstname  = newContact.FirstName;
                contact.Middlename = newContact.MiddleName;
            }
            else if (fio != null)
            {
                var names = fio.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                switch (names.Length)
                {
                case 1:
                    contact.Firstname = RuleOrNull(fio);
                    break;

                case 2:
                    contact.Firstname = RuleOrNull(names[0]);
                    contact.Surname   = RuleOrNull(names[1]);
                    break;

                case 3:
                    contact.Surname    = RuleOrNull(names[0]);
                    contact.Firstname  = RuleOrNull(names[1]);
                    contact.Middlename = RuleOrNull(names[2]);
                    break;

                default:
                    contact.Firstname = RuleOrNull(fio);
                    break;
                }
            }
            else
            {
                contact.Firstname = notExistingContactSummary.Email;
            }



            if (Logger.IsDebugEnabled())
            {
                Logger.Log(LogLevel.Debug, $"Created Contact: {notExistingContactSummary.Email}");
            }


            return(contact);
        }