Example #1
0
        public Dictionary <int, List <File> > GetFiles(int[] eventID)
        {
            if (eventID == null || eventID.Length == 0)
            {
                throw new ArgumentException("eventID");
            }

            using (var tagdao = FilesIntegration.GetTagDao())
                using (var filedao = FilesIntegration.GetFileDao())
                {
                    var findedTags = tagdao.GetTags(eventID.Select(item => String.Concat("RelationshipEvent_", item)).ToArray(),
                                                    TagType.System).Where(t => t.EntryType == FileEntryType.File);

                    var filesID = findedTags.Select(t => t.EntryId).ToList();

                    var files = 0 < filesID.Count ? filedao.GetFiles(filesID) : new List <File>();

                    var filesTemp = new Dictionary <object, File>();

                    files.ForEach(item =>
                    {
                        if (!filesTemp.ContainsKey(item.ID))
                        {
                            filesTemp.Add(item.ID, item);
                        }
                    });

                    return(findedTags.Where(x => filesTemp.ContainsKey(x.EntryId)).GroupBy(x => x.TagName).ToDictionary(x => Convert.ToInt32(x.Key.Split(new[] { '_' })[1]),
                                                                                                                        x => x.Select(item => filesTemp[item.EntryId]).ToList()));
                }
        }
Example #2
0
 public IEnumerable <File> GetFiles(IEnumerable <object> id)
 {
     using (var dao = FilesIntegration.GetFileDao())
     {
         return(dao.GetFiles(id));
     }
 }
Example #3
0
 public void MoveToTrash(object id)
 {
     using (var dao = FilesIntegration.GetFileDao())
     {
         dao.MoveFile(id, Global.FolderTrash);
     }
 }
Example #4
0
 public File SaveFile(File file, Stream stream)
 {
     using (var dao = FilesIntegration.GetFileDao())
     {
         return(dao.SaveFile(file, stream));
     }
 }
        public IEnumerable <File> GetFiles(ProjectEntity entity)
        {
            if (entity == null)
            {
                return(new List <File>());
            }

            if (!ProjectSecurity.CanReadFiles(entity.Project))
            {
                return(new List <File>());
            }

            using (var tagdao = FilesIntegration.GetTagDao())
                using (var filedao = FilesIntegration.GetFileDao())
                {
                    var ids   = tagdao.GetTags(entity.GetType().Name + entity.ID, TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray();
                    var files = 0 < ids.Length ? filedao.GetFiles(ids) : new List <File>();

                    var rootId = FileEngine.GetRoot(entity.Project.ID);

                    //delete tags when file moved from project folder
                    files.Where(file => !file.RootFolderId.Equals(rootId)).ToList()
                    .ForEach(file =>
                    {
                        DetachFile(entity, file.ID);
                        files.Remove(file);
                    });

                    files.ForEach(r => r.Access = FileEngine.GetFileShare(r, entity.Project.ID));
                    FileEngine.SetThumbUrls(files);
                    return(files);
                }
        }
Example #6
0
 public void DeleteFile(int id)
 {
     using (var dao = FilesIntegration.GetFileDao())
     {
         dao.DeleteFile(id);
         dao.DeleteFolder(id);
     }
 }
Example #7
0
        public void DeleteBatchDeals(List <Deal> deals)
        {
            if (deals.Count == 0)
            {
                return;
            }

            var dealID = deals.Where(CRMSecurity.CanAccessTo).Select(x => x.ID).ToArray();

            // Delete relative  keys
            _cache.Insert(_dealCacheKey, String.Empty);


            using (var db = GetDb())
            {
                var tagNames = db.ExecuteList(Query("crm_relationship_event").Select("id").Where(Exp.Eq("have_files", true) & Exp.In("entity_id", dealID) & Exp.Eq("entity_type", (int)EntityType.Opportunity)))
                               .Select(row => String.Format("RelationshipEvent{0}", row[0])).ToArray();

                using (var tx = db.BeginTransaction(true))
                {
                    db.ExecuteNonQuery(Delete("crm_field_value").Where(Exp.In("entity_id", dealID) & Exp.Eq("entity_type", (int)EntityType.Opportunity)));

                    db.ExecuteNonQuery(new SqlDelete("crm_entity_contact")
                                       .Where(Exp.In("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));

                    db.ExecuteNonQuery(Delete("crm_relationship_event")
                                       .Where(Exp.In("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));

                    db.ExecuteNonQuery(Delete("crm_task")
                                       .Where(Exp.In("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));

                    db.ExecuteNonQuery(new SqlDelete("crm_entity_tag").Where(Exp.In("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));

                    db.ExecuteNonQuery(Delete("crm_deal").Where(Exp.In("id", dealID)));

                    tx.Commit();
                }

                deals.ForEach(deal => CoreContext.AuthorizationManager.RemoveAllAces(deal));

                if (tagNames.Length == 0)
                {
                    return;
                }

                using (var tagdao = FilesIntegration.GetTagDao())
                    using (var filedao = FilesIntegration.GetFileDao())
                    {
                        var filesIDs = tagdao.GetTags(tagNames, TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray();

                        foreach (var filesID in filesIDs)
                        {
                            filedao.DeleteFolder(filesID);
                            filedao.DeleteFile(filesID);
                        }
                    }
            }
        }
 public static IEnumerable <File> GetFiles(string eventId)
 {
     using (var dao = FilesIntegration.GetFileDao())
     {
         var folderId = GetFolderId(eventId);
         var fileIds  = dao.GetFiles(folderId);
         return(dao.GetFiles(fileIds));
     }
 }
Example #9
0
        public File GetFile(object id, int version = 1)
        {
            using (var dao = FilesIntegration.GetFileDao())
            {
                var file = 0 < version?dao.GetFile(id, version) : dao.GetFile(id);

                return(file);
            }
        }
Example #10
0
        public virtual void DeleteBatchCases(int[] casesID)
        {
            if (casesID == null || !casesID.Any())
            {
                return;
            }

            var cases = GetCases(casesID).Where(CRMSecurity.CanAccessTo).ToList();

            //// Delete relative  keys
            _cache.Insert(_caseCacheKey, String.Empty);

            var tagNames = DbManager.ExecuteList(Query("crm_relationship_event").Select("id")
                                                 .Where(Exp.Eq("have_files", true) &
                                                        Exp.In("entity_id", casesID) &
                                                        Exp.Eq("entity_type", (int)EntityType.Case)))
                           .Select(row => String.Format("RelationshipEvent{0}", row[0])).ToArray();

            using (var tx = DbManager.BeginTransaction(true))
            {
                DbManager.ExecuteNonQuery(Delete("crm_field_value")
                                          .Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case)));

                DbManager.ExecuteNonQuery(Delete("crm_relationship_event")
                                          .Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case)));

                DbManager.ExecuteNonQuery(Delete("crm_task")
                                          .Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case)));

                DbManager.ExecuteNonQuery(new SqlDelete("crm_entity_tag").Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case)));

                DbManager.ExecuteNonQuery(Delete("crm_case").Where(Exp.In("id", casesID)));

                tx.Commit();
            }

            cases.ForEach(item => CoreContext.AuthorizationManager.RemoveAllAces(item));

            if (tagNames.Length == 0)
            {
                return;
            }

            using (var tagdao = FilesIntegration.GetTagDao())
                using (var filedao = FilesIntegration.GetFileDao())
                {
                    var filesIDs = tagdao.GetTags(tagNames, TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray();

                    foreach (var filesID in filesIDs)
                    {
                        filedao.DeleteFolder(filesID);
                        filedao.DeleteFile(filesID);
                    }
                }
        }
Example #11
0
        public virtual void DeleteDeal(int dealID)
        {
            var deal = GetByID(dealID);

            CRMSecurity.DemandAccessTo(deal);

            // Delete relative  keys
            _cache.Insert(_dealCacheKey, String.Empty);


            var tagNames = DbManager.ExecuteList(Query("crm_relationship_event").Select("id").Where(Exp.Eq("have_files", true) & Exp.Eq("entity_id", dealID) & Exp.Eq("entity_type", (int)EntityType.Opportunity)))
                           .Select(row => String.Format("RelationshipEvent{0}", row[0])).ToArray();

            using (var tx = DbManager.BeginTransaction(true))
            {
                DbManager.ExecuteNonQuery(Delete("crm_field_value").Where(Exp.Eq("entity_id", dealID) & Exp.Eq("entity_type", (int)EntityType.Opportunity)));

                DbManager.ExecuteNonQuery(new SqlDelete("crm_entity_contact")
                                          .Where(Exp.Eq("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));

                DbManager.ExecuteNonQuery(Delete("crm_relationship_event")
                                          .Where(Exp.Eq("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));

                DbManager.ExecuteNonQuery(Delete("crm_task")
                                          .Where(Exp.Eq("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));

                DbManager.ExecuteNonQuery(new SqlDelete("crm_entity_tag").Where(Exp.Eq("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));

                DbManager.ExecuteNonQuery(Delete("crm_deal").Where(Exp.Eq("id", dealID)));

                tx.Commit();
            }

            CoreContext.AuthorizationManager.RemoveAllAces(deal);

            if (tagNames.Length == 0)
            {
                return;
            }

            using (var tagdao = FilesIntegration.GetTagDao())
                using (var filedao = FilesIntegration.GetFileDao())
                {
                    var filesIDs = tagdao.GetTags(tagNames, TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray();

                    var store = FilesIntegration.GetStore();

                    foreach (var filesID in filesIDs)
                    {
                        filedao.DeleteFolder(filesID);
                        filedao.DeleteFile(filesID);
                    }
                }
        }
        public List <File> GetAllFiles(int[] contactID, EntityType entityType, int entityID)
        {
            using (var filedao = FilesIntegration.GetFileDao())
            {
                var ids   = GetFilesIDs(contactID, entityType, entityID);
                var files = 0 < ids.Length ? filedao.GetFiles(ids) : new List <File>();

                files.ForEach(CRMSecurity.SetAccessTo);

                return(files.ToList());
            }
        }
Example #13
0
 public void RemoveFile(object id)
 {
     using (var dao = FilesIntegration.GetFileDao())
     {
         dao.DeleteFile(id);
         dao.DeleteFolder(id);
         try
         {
             projectsStore.Delete(GetThumbPath(id));
         }
         catch
         {
         }
     }
 }
Example #14
0
 public List <File> GetMessageFiles(Message message)
 {
     if (message == null)
     {
         return(new List <File>());
     }
     using (var tagdao = FilesIntegration.GetTagDao())
         using (var filedao = FilesIntegration.GetFileDao())
         {
             var ids   = tagdao.GetTags("Message" + message.ID, TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray();
             var files = 0 < ids.Length ? filedao.GetFiles(ids) : new List <File>();
             files.ForEach(r => r.Access = GetFileShare(r, message.Project.ID));
             SetThumbUrls(files);
             return(files);
         }
 }
Example #15
0
        public List <File> GetEntityFiles(ProjectEntity entity)
        {
            if (entity == null)
            {
                return(new List <File>());
            }

            using (var tagdao = FilesIntegration.GetTagDao())
                using (var filedao = FilesIntegration.GetFileDao())
                {
                    var ids   = tagdao.GetTags(entity.GetType().Name + entity.ID, TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray();
                    var files = 0 < ids.Length ? filedao.GetFiles(ids) : new List <File>();
                    files.ForEach(r => r.Access = GetFileShare(r, entity.Project.ID));
                    SetThumbUrls(files);
                    return(files);
                }
        }
        private void RemoveAllFiles(int[] contactID, EntityType entityType, int entityID)
        {
            if (entityID > 0 && entityType != EntityType.Opportunity && entityType != EntityType.Case)
            {
                throw new ArgumentException();
            }

            var files = GetAllFiles(contactID, entityType, entityID);

            using (var dao = FilesIntegration.GetFileDao())
            {
                foreach (var file in files)
                {
                    dao.DeleteFile(file.ID);
                }
            }
        }
        public List <File> GetFiles(int eventID)
        {
            if (eventID == 0)
            {
                throw new ArgumentException("eventID");
            }

            using (var tagdao = FilesIntegration.GetTagDao())
                using (var filedao = FilesIntegration.GetFileDao())
                {
                    var ids   = tagdao.GetTags(String.Concat("RelationshipEvent_", eventID), TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray();
                    var files = 0 < ids.Length ? filedao.GetFiles(ids) : new List <File>();

                    files.ForEach(CRMSecurity.SetAccessTo);

                    return(files.ToList());
                }
        }
Example #18
0
        private void DeleteBatchDealsExecute(List <Deal> deals)
        {
            if (deals == null || !deals.Any())
            {
                return;
            }

            var dealID = deals.Select(x => x.ID).ToArray();

            object[] filesIDs;

            using (var db = GetDb())
                using (var tagdao = FilesIntegration.GetTagDao())
                {
                    var tagNames = db.ExecuteList(Query("crm_relationship_event").Select("id")
                                                  .Where(Exp.Eq("have_files", true) & Exp.In("entity_id", dealID) & Exp.Eq("entity_type", (int)EntityType.Opportunity)))
                                   .Select(row => String.Format("RelationshipEvent_{0}", row[0])).ToArray();
                    filesIDs = tagdao.GetTags(tagNames, TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray();

                    using (var tx = db.BeginTransaction(true))
                    {
                        db.ExecuteNonQuery(Delete("crm_field_value").Where(Exp.In("entity_id", dealID) & Exp.Eq("entity_type", (int)EntityType.Opportunity)));
                        db.ExecuteNonQuery(new SqlDelete("crm_entity_contact").Where(Exp.In("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));
                        db.ExecuteNonQuery(Delete("crm_relationship_event").Where(Exp.In("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));
                        db.ExecuteNonQuery(Delete("crm_task").Where(Exp.In("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));
                        db.ExecuteNonQuery(new SqlDelete("crm_entity_tag").Where(Exp.In("entity_id", dealID) & Exp.Eq("entity_type", EntityType.Opportunity)));
                        db.ExecuteNonQuery(Delete("crm_deal").Where(Exp.In("id", dealID)));

                        tx.Commit();
                    }

                    deals.ForEach(deal => CoreContext.AuthorizationManager.RemoveAllAces(deal));
                }

            using (var filedao = FilesIntegration.GetFileDao())
            {
                foreach (var filesID in filesIDs)
                {
                    filedao.DeleteFolder(filesID);
                    filedao.DeleteFile(filesID);
                }
            }
        }
Example #19
0
        private void DeleteFiles()
        {
            if (_fileID == null || _fileID.Count == 0)
            {
                return;
            }

            using (var fileDao = FilesIntegration.GetFileDao())
            {
                foreach (var fileID in _fileID)
                {
                    var fileObj = fileDao.GetFile(fileID);
                    if (fileObj == null)
                    {
                        continue;
                    }

                    fileDao.DeleteFile(fileObj.ID);
                }
            }
        }
Example #20
0
        private void DeleteBatchCasesExecute(List <Cases> caseses)
        {
            var casesID = caseses.Select(x => x.ID).ToArray();

            using (var db = GetDb())
                using (var tagdao = FilesIntegration.GetTagDao())
                {
                    var tagNames = db.ExecuteList(Query("crm_relationship_event").Select("id")
                                                  .Where(Exp.Eq("have_files", true) & Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case)))
                                   .Select(row => String.Format("RelationshipEvent_{0}", row[0])).ToArray();
                    var filesIDs = tagdao.GetTags(tagNames, TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray();

                    using (var tx = db.BeginTransaction(true))
                    {
                        db.ExecuteNonQuery(Delete("crm_field_value").Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case)));
                        db.ExecuteNonQuery(Delete("crm_relationship_event").Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case)));
                        db.ExecuteNonQuery(Delete("crm_task").Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case)));
                        db.ExecuteNonQuery(new SqlDelete("crm_entity_tag").Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case)));
                        db.ExecuteNonQuery(Delete("crm_case").Where(Exp.In("id", casesID)));

                        tx.Commit();
                    }

                    caseses.ForEach(item => CoreContext.AuthorizationManager.RemoveAllAces(item));

                    if (0 < tagNames.Length)
                    {
                        using (var filedao = FilesIntegration.GetFileDao())
                        {
                            foreach (var filesID in filesIDs)
                            {
                                filedao.DeleteFolder(filesID);
                                filedao.DeleteFile(filesID);
                            }
                        }
                    }
                }
        }
Example #21
0
        internal void GenerateImageThumb(File file)
        {
            if (file == null || FileUtility.GetFileTypeByFileName(file.Title) != FileType.Image)
            {
                return;
            }

            try
            {
                using (var filedao = FilesIntegration.GetFileDao())
                {
                    using (var stream = filedao.GetFileStream(file))
                    {
                        var ii = new ImageInfo();
                        ImageHelper.GenerateThumbnail(stream, GetThumbPath(file.ID), ref ii, 128, 96, projectsStore);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("ASC.Web.Projects").Error(ex);
            }
        }
Example #22
0
        public void RunJob()
        {
            var smtpClient = GetSmtpClient();

            ASC.Core.CoreContext.TenantManager.SetCurrentTenant(_tenantID);
            SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currentUserID));

            var contactCount = _contactID.Count;

            if (contactCount == 0)
            {
                Complete();

                return;
            }

            var from = new MailAddress(_SMTPSetting.SenderEmailAddress, _SMTPSetting.SenderDisplayName, Encoding.UTF8);

            var filePaths = new List <String>();

            using (var fileDao = FilesIntegration.GetFileDao())
                foreach (var fileID in _fileID)
                {
                    var fileObj = fileDao.GetFile(fileID);

                    if (fileObj == null)
                    {
                        continue;
                    }

                    using (var fileStream = fileDao.GetFileStream(fileObj))
                    {
                        var directoryPath = String.Concat(Path.GetTempPath(), "/teamlab/", _tenantID,
                                                          "/crm/files/mailsender/");

                        if (!Directory.Exists(directoryPath))
                        {
                            Directory.CreateDirectory(directoryPath);
                        }

                        var filePath = String.Concat(directoryPath, fileObj.Title);


                        using (var newFileStream = File.Create(filePath))
                            fileStream.StreamCopyTo(newFileStream);

                        filePaths.Add(filePath);
                    }
                }


            var templateManager = new MailTemplateManager(_daoFactory);

            var deliveryCount = 0;

            try
            {
                Error = String.Empty;

                foreach (var contactID in _contactID)
                {
                    if (IsCompleted)
                    {
                        break;              // User selected cancel
                    }
                    var contactInfoDao = _daoFactory.GetContactInfoDao();
                    var startDate      = DateTime.Now;

                    var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true);

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

                    var recipientEmail = contactEmails[0].Data;

                    if (!isValidMail(recipientEmail))
                    {
                        Error += String.Format(CRMCommonResource.MailSender_InvalidEmail,
                                               recipientEmail) + "<br/>";


                        continue;
                    }

                    var to = new MailAddress(recipientEmail);

                    using (var message = new MailMessage(from, to))
                    {
                        try
                        {
                            message.Subject         = _subject;
                            message.Body            = templateManager.Apply(_bodyTempate, contactID);
                            message.SubjectEncoding = Encoding.UTF8;
                            message.BodyEncoding    = Encoding.UTF8;
                            message.IsBodyHtml      = true;

                            foreach (var filePath in filePaths)
                            {
                                message.Attachments.Add(new Attachment(filePath));
                            }

                            _log.Debug(GetLoggerRow(message));

                            smtpClient.Send(message);

                            if (_storeInHistory)
                            {
                                AddToHistory(contactID, String.Format(CRMCommonResource.MailHistoryEventTemplate, message.Subject));
                            }


                            var endDate = DateTime.Now;

                            var waitInterval = endDate.Subtract(startDate);

                            deliveryCount++;

                            var estimatedTime = TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount));

                            Status = new
                            {
                                RecipientCount = _contactID.Count,
                                EstimatedTime  = new TimeSpan(
                                    estimatedTime.Days,
                                    estimatedTime.Hours,
                                    estimatedTime.Minutes,
                                    estimatedTime.Seconds).ToString(),
                                DeliveryCount = deliveryCount
                            };
                        }
                        catch (SmtpFailedRecipientsException ex)
                        {
                            for (int i = 0; i < ex.InnerExceptions.Length; i++)
                            {
                                SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;

                                if (status == SmtpStatusCode.MailboxBusy ||
                                    status == SmtpStatusCode.MailboxUnavailable)
                                {
                                    Error = String.Format(CRMCommonResource.MailSender_MailboxBusyException, 5);

                                    _log.Error(Error);

                                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));

                                    smtpClient.Send(message);

                                    deliveryCount++;
                                }
                                else
                                {
                                    Error += String.Format(CRMCommonResource.MailSender_FailedDeliverException,
                                                           ex.InnerExceptions[i].FailedRecipient) + "<br/>";

                                    _log.Error(Error);
                                }
                            }
                        }

                        _exactPercentageValue += 100.0 / contactCount;
                        Percentage             = Math.Round(_exactPercentageValue);

                        if (Percentage > 100)
                        {
                            Percentage = 100;
                        }
                    }
                }
            }
            finally
            {
                foreach (var filePath in filePaths)
                {
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                }
            }

            Status = new
            {
                RecipientCount = _contactID.Count,
                EstimatedTime  = new TimeSpan(0, 0, 0).ToString(),
                DeliveryCount  = deliveryCount
            };

            Complete();
        }
Example #23
0
        public virtual void DeleteBatchContact(int[] contactID)
        {
            if (contactID == null || contactID.Length == 0)
            {
                return;
            }

            // Delete relative  keys
            _cache.Insert(_contactCacheKey, String.Empty);

            var contacts = GetContacts(contactID).Where(CRMSecurity.CanAccessTo).ToList();

            if (contacts.Count == 0)
            {
                return;
            }

            var personsID    = new List <int>();
            var companyID    = new List <int>();
            var newContactID = new List <int>();

            foreach (var contact in contacts)
            {
                newContactID.Add(contact.ID);

                if (contact is Company)
                {
                    companyID.Add(contact.ID);
                }
                else
                {
                    personsID.Add(contact.ID);
                }
            }

            contactID = newContactID.ToArray();

            using (var tx = DbManager.BeginTransaction())
            {
                DbManager.ExecuteNonQuery(Delete("crm_field_value").Where(Exp.In("entity_id", contactID)
                                                                          & Exp.In("entity_type", new[] { (int)EntityType.Contact, (int)EntityType.Person, (int)EntityType.Company })));

                DbManager.ExecuteNonQuery(Delete("crm_task").Where(Exp.In("contact_id", contactID)));
                DbManager.ExecuteNonQuery(new SqlDelete("crm_entity_tag")
                                          .Where(Exp.In("entity_id", contactID) & Exp.Eq("entity_type", (int)EntityType.Contact)));

                DbManager.ExecuteNonQuery(Delete("crm_relationship_event").Where(Exp.In("contact_id", contactID)));
                DbManager.ExecuteNonQuery(Update("crm_deal").Set("contact_id", 0).Where(Exp.In("contact_id", contactID)));

                if (companyID.Count > 0)
                {
                    DbManager.ExecuteNonQuery(Update("crm_contact").Set("company_id", 0).Where(Exp.In("company_id", companyID)));
                }

                if (personsID.Count > 0)
                {
                    RemoveRelative(null, EntityType.Person, personsID.ToArray());
                }

                RemoveRelative(contactID, EntityType.Any, null);

                DbManager.ExecuteNonQuery(Delete("crm_contact_info").Where(Exp.In("contact_id", contactID)));

                DbManager.ExecuteNonQuery(Delete("crm_contact").Where(Exp.In("id", contactID)));

                tx.Commit();
            }

            contacts.ForEach(contact => CoreContext.AuthorizationManager.RemoveAllAces(contact));


            using (var tagdao = FilesIntegration.GetTagDao())
                using (var filedao = FilesIntegration.GetFileDao())
                {
                    var tagNames = DbManager.ExecuteList(Query("crm_relationship_event").Select("id").Where(Exp.In("contact_id", contactID) & Exp.Eq("have_files", true)))
                                   .Select(row => String.Format("RelationshipEvent{0}", row[0])).ToArray();

                    if (tagNames.Length == 0)
                    {
                        return;
                    }

                    var filesIDs = tagdao.GetTags(tagNames, TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray();

                    var store = FilesIntegration.GetStore();

                    foreach (var filesID in filesIDs)
                    {
                        filedao.DeleteFolder(filesID);
                        filedao.DeleteFile(filesID);
                    }
                }
        }
Example #24
0
        public void RunJob()
        {
            using (var smtpClient = GetSmtpClient())
            {
                CoreContext.TenantManager.SetCurrentTenant(_tenantID);
                SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currUser));

                var userCulture = CoreContext.UserManager.GetUsers(_currUser).GetCulture();

                System.Threading.Thread.CurrentThread.CurrentCulture   = userCulture;
                System.Threading.Thread.CurrentThread.CurrentUICulture = userCulture;

                var contactCount = _contactID.Count;

                if (contactCount == 0)
                {
                    Complete();
                    return;
                }

                MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());

                var from      = new MailAddress(_smtpSetting.SenderEmailAddress, _smtpSetting.SenderDisplayName, Encoding.UTF8);
                var filePaths = new List <String>();
                using (var fileDao = FilesIntegration.GetFileDao())
                {
                    foreach (var fileID in _fileID)
                    {
                        var fileObj = fileDao.GetFile(fileID);
                        if (fileObj == null)
                        {
                            continue;
                        }
                        using (var fileStream = fileDao.GetFileStream(fileObj))
                        {
                            var directoryPath = Path.Combine(Path.GetTempPath(), "teamlab", _tenantID.ToString(), "crm/files/mailsender/");
                            if (!Directory.Exists(directoryPath))
                            {
                                Directory.CreateDirectory(directoryPath);
                            }
                            var filePath = Path.Combine(directoryPath, fileObj.Title);
                            using (var newFileStream = File.Create(filePath))
                            {
                                fileStream.StreamCopyTo(newFileStream);
                            }
                            filePaths.Add(filePath);
                        }
                    }
                }

                var templateManager = new MailTemplateManager(_daoFactory);
                var deliveryCount   = 0;

                try
                {
                    if (smtpClient.EnableSsl && WorkContext.IsMono)
                    {
                        ServicePointManager.ServerCertificateValidationCallback = (s, c, h, e) => { return(true); };
                    }

                    Error = String.Empty;
                    foreach (var contactID in _contactID)
                    {
                        if (IsCompleted)
                        {
                            break;              // User selected cancel
                        }
                        var contactInfoDao = _daoFactory.GetContactInfoDao();
                        var startDate      = DateTime.Now;

                        var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true);
                        if (contactEmails.Count == 0)
                        {
                            continue;
                        }

                        var recipientEmail = contactEmails[0].Data;

                        if (!IsValidMail(recipientEmail))
                        {
                            Error += String.Format(CRMCommonResource.MailSender_InvalidEmail, recipientEmail) + "<br/>";
                            continue;
                        }

                        var to = new MailAddress(recipientEmail);
                        using (var message = new MailMessage(from, to))
                        {
                            try
                            {
                                message.Subject         = _subject;
                                message.Body            = templateManager.Apply(_bodyTempate, contactID);
                                message.SubjectEncoding = Encoding.UTF8;
                                message.BodyEncoding    = Encoding.UTF8;
                                message.IsBodyHtml      = true;

                                foreach (var filePath in filePaths)
                                {
                                    message.Attachments.Add(new Attachment(filePath));
                                }
                                _log.Debug(GetLoggerRow(message));

                                smtpClient.Send(message);

                                if (_storeInHistory)
                                {
                                    AddToHistory(contactID, String.Format(CRMCommonResource.MailHistoryEventTemplate, message.Subject));
                                }

                                var endDate      = DateTime.Now;
                                var waitInterval = endDate.Subtract(startDate);
                                deliveryCount++;

                                var estimatedTime = TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount));

                                Status = new
                                {
                                    RecipientCount = _contactID.Count,
                                    EstimatedTime  = estimatedTime.ToString(),
                                    DeliveryCount  = deliveryCount
                                };
                            }
                            catch (SmtpFailedRecipientsException ex)
                            {
                                for (var i = 0; i < ex.InnerExceptions.Length; i++)
                                {
                                    var status = ex.InnerExceptions[i].StatusCode;

                                    if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
                                    {
                                        Error = String.Format(CRMCommonResource.MailSender_MailboxBusyException, 5);
                                        _log.Error(Error, ex);
                                        Thread.Sleep(TimeSpan.FromSeconds(5));
                                        smtpClient.Send(message);
                                        deliveryCount++;
                                    }
                                    else
                                    {
                                        Error += String.Format(CRMCommonResource.MailSender_FailedDeliverException, ex.InnerExceptions[i].FailedRecipient) + "<br/>";
                                        _log.Error(Error, ex);
                                    }
                                }
                            }

                            _exactPercentageValue += 100.0 / contactCount;
                            Percentage             = Math.Round(_exactPercentageValue);

                            if (MailSenderDataCache.CheckCancelFlag())
                            {
                                MailSenderDataCache.ResetAll();

                                throw new OperationCanceledException();
                            }

                            MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());

                            if (Percentage > 100)
                            {
                                Percentage = 100;

                                if (MailSenderDataCache.CheckCancelFlag())
                                {
                                    MailSenderDataCache.ResetAll();

                                    throw new OperationCanceledException();
                                }

                                MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());
                            }
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    MailSenderDataCache.ResetAll();
                    _log.Debug("cancel mail sender");
                }
                finally
                {
                    MailSenderDataCache.ResetAll();

                    if (smtpClient.EnableSsl && WorkContext.IsMono)
                    {
                        ServicePointManager.ServerCertificateValidationCallback = null;
                    }
                    foreach (var filePath in filePaths)
                    {
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                    }
                }

                Status = new
                {
                    RecipientCount = _contactID.Count,
                    EstimatedTime  = TimeSpan.Zero.ToString(),
                    DeliveryCount  = deliveryCount
                };
            }
            Complete();
        }
Example #25
0
        public void RunJob()
        {
            SmtpClient smtpClient = null;

            try
            {
                CoreContext.TenantManager.SetCurrentTenant(_tenantID);
                SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currUser));

                smtpClient = GetSmtpClient();

                using (var scope = DIHelper.Resolve())
                {
                    var _daoFactory = scope.Resolve <DaoFactory>();
                    var userCulture = CoreContext.UserManager.GetUsers(_currUser).GetCulture();

                    Thread.CurrentThread.CurrentCulture   = userCulture;
                    Thread.CurrentThread.CurrentUICulture = userCulture;

                    var contactCount = _contactID.Count;

                    if (contactCount == 0)
                    {
                        Complete();
                        return;
                    }

                    MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());

                    var from      = new MailboxAddress(_smtpSetting.SenderDisplayName, _smtpSetting.SenderEmailAddress);
                    var filePaths = new List <string>();
                    using (var fileDao = FilesIntegration.GetFileDao())
                    {
                        foreach (var fileID in _fileID)
                        {
                            var fileObj = fileDao.GetFile(fileID);
                            if (fileObj == null)
                            {
                                continue;
                            }
                            using (var fileStream = fileDao.GetFileStream(fileObj))
                            {
                                var directoryPath = Path.Combine(Path.GetTempPath(), "teamlab", _tenantID.ToString(),
                                                                 "crm/files/mailsender/");
                                if (!Directory.Exists(directoryPath))
                                {
                                    Directory.CreateDirectory(directoryPath);
                                }
                                var filePath = Path.Combine(directoryPath, fileObj.Title);
                                using (var newFileStream = File.Create(filePath))
                                {
                                    fileStream.StreamCopyTo(newFileStream);
                                }
                                filePaths.Add(filePath);
                            }
                        }
                    }

                    var templateManager = new MailTemplateManager(_daoFactory);
                    var deliveryCount   = 0;

                    try
                    {
                        Error = string.Empty;
                        foreach (var contactID in _contactID)
                        {
                            _exactPercentageValue += 100.0 / contactCount;
                            Percentage             = Math.Round(_exactPercentageValue);

                            if (IsCompleted)
                            {
                                break;              // User selected cancel
                            }
                            var contactInfoDao = _daoFactory.ContactInfoDao;
                            var startDate      = DateTime.Now;

                            var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true);
                            if (contactEmails.Count == 0)
                            {
                                continue;
                            }

                            var recipientEmail = contactEmails[0].Data;

                            if (!recipientEmail.TestEmailRegex())
                            {
                                Error += string.Format(CRMCommonResource.MailSender_InvalidEmail, recipientEmail) +
                                         "<br/>";
                                continue;
                            }

                            var to = new MailboxAddress(recipientEmail);

                            var mimeMessage = new MimeMessage
                            {
                                Subject = _subject
                            };

                            mimeMessage.From.Add(from);
                            mimeMessage.To.Add(to);

                            var bodyBuilder = new BodyBuilder
                            {
                                HtmlBody = templateManager.Apply(_bodyTempate, contactID)
                            };

                            foreach (var filePath in filePaths)
                            {
                                bodyBuilder.Attachments.Add(filePath);
                            }

                            mimeMessage.Body = bodyBuilder.ToMessageBody();

                            mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");

                            _log.Debug(GetLoggerRow(mimeMessage));

                            var success = false;

                            try
                            {
                                smtpClient.Send(mimeMessage);

                                success = true;
                            }
                            catch (SmtpCommandException ex)
                            {
                                _log.Error(Error, ex);

                                Error += string.Format(CRMCommonResource.MailSender_FailedDeliverException, recipientEmail) + "<br/>";
                            }

                            if (success)
                            {
                                if (_storeInHistory)
                                {
                                    AddToHistory(contactID, string.Format(CRMCommonResource.MailHistoryEventTemplate, mimeMessage.Subject), _daoFactory);
                                }

                                var endDate      = DateTime.Now;
                                var waitInterval = endDate.Subtract(startDate);

                                deliveryCount++;

                                var estimatedTime =
                                    TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount));

                                Status = new
                                {
                                    RecipientCount = _contactID.Count,
                                    EstimatedTime  = estimatedTime.ToString(),
                                    DeliveryCount  = deliveryCount
                                };
                            }

                            if (MailSenderDataCache.CheckCancelFlag())
                            {
                                MailSenderDataCache.ResetAll();

                                throw new OperationCanceledException();
                            }

                            MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());

                            if (Percentage > 100)
                            {
                                Percentage = 100;

                                if (MailSenderDataCache.CheckCancelFlag())
                                {
                                    MailSenderDataCache.ResetAll();

                                    throw new OperationCanceledException();
                                }

                                MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        _log.Debug("cancel mail sender");
                    }
                    finally
                    {
                        foreach (var filePath in filePaths)
                        {
                            if (File.Exists(filePath))
                            {
                                File.Delete(filePath);
                            }
                        }
                    }

                    Status = new
                    {
                        RecipientCount = _contactID.Count,
                        EstimatedTime  = TimeSpan.Zero.ToString(),
                        DeliveryCount  = deliveryCount
                    };
                }
            }
            catch (Exception e)
            {
                Error = e.Message;
                _log.Error(Error);
            }
            finally
            {
                if (smtpClient != null)
                {
                    smtpClient.Dispose();
                }
                Complete();
            }
        }
Example #26
0
        public IEnumerable <SearchItem> Search(string searchText, int projectId = 0)
        {
            var queryResult = DaoFactory.SearchDao.Search(searchText, projectId);

            using (var scope = DIHelper.Resolve())
            {
                var projectSecurity = scope.Resolve <ProjectSecurity>();

                foreach (var r in queryResult)
                {
                    switch (r.EntityType)
                    {
                    case EntityType.Project:
                        var project = (Project)r;
                        if (projectSecurity.CanRead(project))
                        {
                            searchItems.Add(new SearchItem(project));
                        }
                        continue;

                    case EntityType.Milestone:
                        var milestone = (Milestone)r;
                        if (projectSecurity.CanRead(milestone))
                        {
                            searchItems.Add(new SearchItem(milestone));
                        }
                        continue;

                    case EntityType.Message:
                        var message = (Message)r;
                        if (projectSecurity.CanRead(message))
                        {
                            searchItems.Add(new SearchItem(message));
                        }
                        continue;

                    case EntityType.Task:
                        var task = (Task)r;
                        if (projectSecurity.CanRead(task))
                        {
                            searchItems.Add(new SearchItem(task));
                        }
                        continue;

                    case EntityType.Comment:
                        var comment = (Comment)r;
                        var entity  = CommentEngine.GetEntityByTargetUniqId(comment);
                        if (entity == null)
                        {
                            continue;
                        }

                        searchItems.Add(new SearchItem(comment.EntityType,
                                                       comment.ID.ToString(CultureInfo.InvariantCulture), HtmlUtil.GetText(comment.Content),
                                                       comment.CreateOn, new SearchItem(entity)));
                        continue;

                    case EntityType.SubTask:
                        var subtask    = (Subtask)r;
                        var parentTask = TaskEngine.GetByID(subtask.Task);
                        if (parentTask == null)
                        {
                            continue;
                        }

                        searchItems.Add(new SearchItem(subtask.EntityType,
                                                       subtask.ID.ToString(CultureInfo.InvariantCulture), subtask.Title, subtask.CreateOn,
                                                       new SearchItem(parentTask)));
                        continue;
                    }
                }
            }

            try
            {
                // search in files
                var fileEntries = new List <FileEntry>();
                using (var folderDao = FilesIntegration.GetFolderDao())
                    using (var fileDao = FilesIntegration.GetFileDao())
                    {
                        fileEntries.AddRange(folderDao.Search(searchText, true));
                        fileEntries.AddRange(fileDao.Search(searchText, true));

                        var projectIds = projectId != 0
                                         ? new List <int> {
                            projectId
                        }
                                         : fileEntries.GroupBy(f => f.RootFolderId)
                        .Select(g => folderDao.GetFolder(g.Key))
                        .Select(f => f != null ? folderDao.GetBunchObjectID(f.RootFolderId).Split('/').Last() : null)
                        .Where(s => !string.IsNullOrEmpty(s))
                        .Select(int.Parse);

                        var rootProject = projectIds.ToDictionary(id => FilesIntegration.RegisterBunch("projects", "project", id.ToString(CultureInfo.InvariantCulture)));
                        fileEntries.RemoveAll(f => !rootProject.ContainsKey(f.RootFolderId));

                        var security = FilesIntegration.GetFileSecurity();
                        fileEntries.RemoveAll(f => !security.CanRead(f));

                        foreach (var f in fileEntries)
                        {
                            var id      = rootProject[f.RootFolderId];
                            var project = DaoFactory.ProjectDao.GetById(id);

                            if (ProjectSecurity.CanReadFiles(project))
                            {
                                var itemId = f.FileEntryType == FileEntryType.File
                                             ? FilesLinkUtility.GetFileWebPreviewUrl(f.Title, f.ID)
                                             : Web.Files.Classes.PathProvider.GetFolderUrl((Folder)f, project.ID);
                                searchItems.Add(new SearchItem(EntityType.File, itemId, f.Title, f.CreateOn, new SearchItem(project), itemPath: "{2}"));
                            }
                        }
                    }
            }
            catch (Exception err)
            {
                LogManager.GetLogger("ASC").Error(err);
            }
            return(searchItems);
        }
Example #27
0
        public MailAttachmentData AttachFileFromDocuments(int tenant, string user, int messageId, string fileId, string version, bool needSaveToTemp = false)
        {
            MailAttachmentData result;

            using (var fileDao = FilesIntegration.GetFileDao())
            {
                var file = string.IsNullOrEmpty(version)
                               ? fileDao.GetFile(fileId)
                               : fileDao.GetFile(fileId, Convert.ToInt32(version));

                if (file == null)
                {
                    throw new AttachmentsException(AttachmentsException.Types.DocumentNotFound, "File not found.");
                }

                if (!FilesIntegration.GetFileSecurity().CanRead(file))
                {
                    throw new AttachmentsException(AttachmentsException.Types.DocumentAccessDenied,
                                                   "Access denied.");
                }

                if (!fileDao.IsExistOnStorage(file))
                {
                    throw new AttachmentsException(AttachmentsException.Types.DocumentNotFound,
                                                   "File not exists on storage.");
                }

                Log.InfoFormat("Original file id: {0}", file.ID);
                Log.InfoFormat("Original file name: {0}", file.Title);
                var fileExt     = FileUtility.GetFileExtension(file.Title);
                var curFileType = FileUtility.GetFileTypeByFileName(file.Title);
                Log.InfoFormat("File converted type: {0}", file.ConvertedType);

                if (file.ConvertedType != null)
                {
                    switch (curFileType)
                    {
                    case FileType.Image:
                        fileExt = file.ConvertedType == ".zip" ? ".pptt" : file.ConvertedType;
                        break;

                    case FileType.Spreadsheet:
                        fileExt = file.ConvertedType != ".xlsx" ? ".xlst" : file.ConvertedType;
                        break;

                    default:
                        if (file.ConvertedType == ".doct" || file.ConvertedType == ".xlst" || file.ConvertedType == ".pptt")
                        {
                            fileExt = file.ConvertedType;
                        }
                        break;
                    }
                }

                var convertToExt = string.Empty;
                switch (curFileType)
                {
                case FileType.Document:
                    if (fileExt == ".doct")
                    {
                        convertToExt = ".docx";
                    }
                    break;

                case FileType.Spreadsheet:
                    if (fileExt == ".xlst")
                    {
                        convertToExt = ".xlsx";
                    }
                    break;

                case FileType.Presentation:
                    if (fileExt == ".pptt")
                    {
                        convertToExt = ".pptx";
                    }
                    break;
                }

                if (!string.IsNullOrEmpty(convertToExt) && fileExt != convertToExt)
                {
                    var fileName = Path.ChangeExtension(file.Title, convertToExt);
                    Log.InfoFormat("Changed file name - {0} for file {1}:", fileName, file.ID);

                    using (var readStream = FileConverter.Exec(file, convertToExt))
                    {
                        if (readStream == null)
                        {
                            throw new AttachmentsException(AttachmentsException.Types.DocumentAccessDenied, "Access denied.");
                        }

                        using (var memStream = new MemoryStream())
                        {
                            readStream.StreamCopyTo(memStream);
                            result = AttachFileToDraft(tenant, user, messageId, fileName, memStream, memStream.Length, null, needSaveToTemp);
                            Log.InfoFormat("Attached attachment: ID - {0}, Name - {1}, StoredUrl - {2}", result.fileName, result.fileName, result.storedFileUrl);
                        }
                    }
                }
                else
                {
                    using (var readStream = fileDao.GetFileStream(file))
                    {
                        if (readStream == null)
                        {
                            throw new AttachmentsException(AttachmentsException.Types.DocumentAccessDenied, "Access denied.");
                        }

                        result = AttachFileToDraft(tenant, user, messageId, file.Title, readStream, readStream.CanSeek ? readStream.Length : file.ContentLength, null, needSaveToTemp);
                        Log.InfoFormat("Attached attachment: ID - {0}, Name - {1}, StoredUrl - {2}", result.fileName, result.fileName, result.storedFileUrl);
                    }
                }
            }

            return(result);
        }
Example #28
0
        public MailAttachment AttachFileFromDocuments(int id_tenant, string id_user, int id_message, string id_file,
                                                      string version, string share_link, string id_stream)
        {
            MailAttachment result;

            using (var file_dao = FilesIntegration.GetFileDao())
            {
                Files.Core.File file;
                var             check_link = FileShareLink.Check(share_link, true, file_dao, out file);
                if (!check_link && file == null)
                {
                    file = String.IsNullOrEmpty(version)
                               ? file_dao.GetFile(id_file)
                               : file_dao.GetFile(id_file, Convert.ToInt32(version));
                }

                if (file == null)
                {
                    throw new AttachmentsException(AttachmentsException.Types.DOCUMENT_NOT_FOUND, "File not found.");
                }

                if (!check_link && !FilesIntegration.GetFileSecurity().CanRead(file))
                {
                    throw new AttachmentsException(AttachmentsException.Types.DOCUMENT_ACCESS_DENIED,
                                                   "Access denied.");
                }

                if (!file_dao.IsExistOnStorage(file))
                {
                    throw new AttachmentsException(AttachmentsException.Types.DOCUMENT_NOT_FOUND,
                                                   "File not exists on storage.");
                }

                var file_ext      = FileUtility.GetFileExtension(file.Title);
                var cur_file_type = FileUtility.GetFileTypeByFileName(file.Title);

                if (file.ConvertedType != null)
                {
                    if (cur_file_type == FileType.Image)
                    {
                        file_ext = file.ConvertedType == ".zip" ? ".pptt" : file.ConvertedType;
                    }
                    else if (cur_file_type == FileType.Spreadsheet)
                    {
                        file_ext = file.ConvertedType != ".xlsx" ? ".xlst" : file.ConvertedType;
                    }
                    else if (file.ConvertedType == ".doct" || file.ConvertedType == ".xlst" || file.ConvertedType == ".pptt")
                    {
                        file_ext = file.ConvertedType;
                    }
                }

                var convert_to_ext = string.Empty;
                switch (cur_file_type)
                {
                case FileType.Document:
                    if (file_ext == ".doct")
                    {
                        convert_to_ext = ".docx";
                    }
                    break;

                case FileType.Spreadsheet:
                    if (file_ext == ".xlst")
                    {
                        convert_to_ext = ".xlsx";
                    }
                    break;

                case FileType.Presentation:
                    if (file_ext == ".pptt")
                    {
                        convert_to_ext = ".pptx";
                    }
                    break;
                }

                if (!string.IsNullOrEmpty(convert_to_ext) && file_ext != convert_to_ext)
                {
                    var file_name = Path.ChangeExtension(file.Title, convert_to_ext);

                    using (var read_stream = FileConverter.Exec(file, convert_to_ext))
                    {
                        if (read_stream != null)
                        {
                            using (var mem_stream = new MemoryStream())
                            {
                                read_stream.StreamCopyTo(mem_stream);
                                result = AttachFile(id_tenant, id_user, id_message, file_name, mem_stream,
                                                    id_stream);
                            }
                        }
                        else
                        {
                            throw new AttachmentsException(AttachmentsException.Types.DOCUMENT_ACCESS_DENIED,
                                                           "Access denied.");
                        }
                    }
                }
                else
                {
                    using (var read_stream = file_dao.GetFileStream(file))
                    {
                        if (read_stream != null)
                        {
                            result = AttachFile(id_tenant, id_user, id_message, file.Title, read_stream, id_stream);
                        }
                        else
                        {
                            throw new AttachmentsException(AttachmentsException.Types.DOCUMENT_ACCESS_DENIED,
                                                           "Access denied.");
                        }
                    }
                }
            }

            return(result);
        }
        public List <SearchGroup> Search(String searchText, int projectId)
        {
            var queryResult = _searchDao.Search(searchText, projectId);

            var groups = new Dictionary <int, SearchGroup>();

            foreach (var r in queryResult)
            {
                var        projId = 0;
                SearchItem item   = null;

                if (r is Project)
                {
                    var p = (Project)r;
                    if (ProjectSecurity.CanRead(p))
                    {
                        projId = p.ID;
                        if (!groups.ContainsKey(projId))
                        {
                            groups[projId] = new SearchGroup(projId, p.Title);
                        }
                        item = new SearchItem(EntityType.Project, p.ID, p.Title, p.Description, p.CreateOn);
                    }
                }
                else
                {
                    if (r is Milestone)
                    {
                        var m = (Milestone)r;
                        if (ProjectSecurity.CanRead(m))
                        {
                            projId = m.Project.ID;
                            if (!groups.ContainsKey(projId))
                            {
                                groups[projId] = new SearchGroup(projId, m.Project.Title);
                            }
                            item = new SearchItem(EntityType.Milestone, m.ID, m.Title, null, m.CreateOn);
                        }
                    }
                    else if (r is Message)
                    {
                        var m = (Message)r;
                        if (ProjectSecurity.CanReadMessages(m.Project))
                        {
                            projId = m.Project.ID;
                            if (!groups.ContainsKey(projId))
                            {
                                groups[projId] = new SearchGroup(projId, m.Project.Title);
                            }
                            item = new SearchItem(EntityType.Message, m.ID, m.Title, m.Content, m.CreateOn);
                        }
                    }
                    else if (r is Task)
                    {
                        var t = (Task)r;
                        if (ProjectSecurity.CanRead(t))
                        {
                            projId = t.Project.ID;
                            if (!groups.ContainsKey(projId))
                            {
                                groups[projId] = new SearchGroup(projId, t.Project.Title);
                            }
                            item = new SearchItem(EntityType.Task, t.ID, t.Title, t.Description, t.CreateOn);
                        }
                    }
                }
                if (0 < projId && item != null)
                {
                    groups[projId].Items.Add(item);
                }
            }

            try
            {
                // search in files
                var fileEntries = new List <Files.Core.FileEntry>();
                using (var folderDao = FilesIntegration.GetFolderDao())
                    using (var fileDao = FilesIntegration.GetFileDao())
                    {
                        fileEntries.AddRange(folderDao.Search(searchText, Files.Core.FolderType.BUNCH).Cast <Files.Core.FileEntry>());
                        fileEntries.AddRange(fileDao.Search(searchText, Files.Core.FolderType.BUNCH).Cast <Files.Core.FileEntry>());

                        var projectIds = projectId != 0
                                         ? new List <int> {
                            projectId
                        }
                                         : fileEntries.GroupBy(f => f.RootFolderId)
                        .Select(g => folderDao.GetFolder(g.Key))
                        .Select(f => f != null ? folderDao.GetBunchObjectID(f.RootFolderId).Split('/').Last() : null)
                        .Where(s => !string.IsNullOrEmpty(s))
                        .Select(s => int.Parse(s));

                        var rootProject = projectIds.ToDictionary(id => FilesIntegration.RegisterBunch("projects", "project", id.ToString()));
                        fileEntries.RemoveAll(f => !rootProject.ContainsKey(f.RootFolderId));

                        var security = FilesIntegration.GetFileSecurity();
                        fileEntries.RemoveAll(f => !security.CanRead(f));

                        foreach (var f in fileEntries)
                        {
                            var id = rootProject[f.RootFolderId];
                            if (!groups.ContainsKey(id))
                            {
                                var project = _projDao.GetById(id);
                                if (project != null && ProjectSecurity.CanRead(project) && ProjectSecurity.CanReadFiles(project))
                                {
                                    groups[id] = new SearchGroup(id, project.Title);
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            var item = new SearchItem
                            {
                                EntityType = EntityType.File,
                                ID         = f is Files.Core.File ? ((Files.Core.File)f).ViewUrl : string.Format("{0}tmdocs.aspx?prjID={1}#{2}", VirtualPathUtility.ToAbsolute("~/products/projects/"), id, f.ID),
                                Title      = f.Title,
                                CreateOn   = f.CreateOn,
                            };
                            groups[id].Items.Add(item);
                        }
                    }
            }
            catch (Exception err)
            {
                LogManager.GetLogger("ASC.Web").Error(err);
            }
            return(new List <SearchGroup>(groups.Values));
        }