示例#1
0
        private int SaveTaskInDb(Task newTask)
        {
            if (String.IsNullOrEmpty(newTask.Title) || newTask.DeadLine == DateTime.MinValue ||
                newTask.CategoryID == 0)
            {
                throw new ArgumentException();
            }

            var result = Db.ExecuteScalar <int>(
                Insert("crm_task")
                .InColumnValue("id", 0)
                .InColumnValue("title", newTask.Title)
                .InColumnValue("description", newTask.Description)
                .InColumnValue("deadline", TenantUtil.DateTimeToUtc(newTask.DeadLine))
                .InColumnValue("responsible_id", newTask.ResponsibleID)
                .InColumnValue("contact_id", newTask.ContactID)
                .InColumnValue("entity_type", (int)newTask.EntityType)
                .InColumnValue("entity_id", newTask.EntityID)
                .InColumnValue("is_closed", newTask.IsClosed)
                .InColumnValue("category_id", newTask.CategoryID)
                .InColumnValue("create_on", newTask.CreateOn == DateTime.MinValue ? DateTime.UtcNow : newTask.CreateOn)
                .InColumnValue("create_by", ASC.Core.SecurityContext.CurrentAccount.ID)
                .InColumnValue("last_modifed_on", newTask.CreateOn == DateTime.MinValue ? DateTime.UtcNow : newTask.CreateOn)
                .InColumnValue("last_modifed_by", ASC.Core.SecurityContext.CurrentAccount.ID)
                .InColumnValue("alert_value", (int)newTask.AlertValue)
                .Identity(1, 0, true));

            newTask.ID = result;
            FactoryIndexer <TasksWrapper> .IndexAsync(newTask);

            return(result);
        }
        public int[] SaveList(List <ContactInfo> items, Contact contact = null)
        {
            if (items == null || items.Count == 0)
            {
                return(null);
            }

            var result = new List <int>();

            using (var tx = Db.BeginTransaction(true))
            {
                foreach (var contactInfo in items)
                {
                    var contactInfoId = SaveInDb(contactInfo);
                    contactInfo.ID = contactInfoId;
                    result.Add(contactInfoId);
                }


                tx.Commit();
            }

            if (contact != null)
            {
                FactoryIndexer <EmailWrapper> .IndexAsync(EmailWrapper.ToEmailWrapper(contact, items.Where(r => r.InfoType == ContactInfoType.Email).ToList()));

                foreach (var item in items.Where(r => r.InfoType != ContactInfoType.Email))
                {
                    FactoryIndexer <InfoWrapper> .IndexAsync(item);
                }
            }

            return(result.ToArray());
        }
示例#3
0
        public void SaveOrUpdate(Comment comment)
        {
            if (comment == null)
            {
                throw new ArgumentNullException("comment");
            }

            if (comment.CreateBy == default(Guid))
            {
                comment.CreateBy = SecurityContext.CurrentAccount.ID;
            }

            var now = TenantUtil.DateTimeNow();

            if (comment.CreateOn == default(DateTime))
            {
                comment.CreateOn = now;
            }

            DaoFactory.CommentDao.Save(comment);

            if (!comment.Inactive)
            {
                FactoryIndexer <CommentsWrapper> .IndexAsync(comment);
            }
            else
            {
                FactoryIndexer <CommentsWrapper> .DeleteAsync(comment);
            }
        }
示例#4
0
        public virtual void EditDeal(Deal deal)
        {
            CRMSecurity.DemandEdit(deal);

            //   var oldDeal = GetByID(deal.ID);

            //   if (oldDeal.ContactID > 0)
            //      RemoveMember(oldDeal.ID, oldDeal.ContactID);

            //    AddMember(deal.ID, deal.ContactID);

            Db.ExecuteNonQuery(
                Update("crm_deal")
                .Set("title", deal.Title)
                .Set("description", deal.Description)
                .Set("responsible_id", deal.ResponsibleID)
                .Set("contact_id", deal.ContactID)
                .Set("bid_currency", deal.BidCurrency)
                .Set("bid_value", deal.BidValue)
                .Set("bid_type", deal.BidType)
                .Set("deal_milestone_id", deal.DealMilestoneID)
                .Set("deal_milestone_probability", deal.DealMilestoneProbability)
                .Set("expected_close_date", TenantUtil.DateTimeToUtc(deal.ExpectedCloseDate))
                .Set("per_period_value", deal.PerPeriodValue)
                .Set("actual_close_date", TenantUtil.DateTimeToUtc(deal.ActualCloseDate))
                .Set("last_modifed_on", TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow()))
                .Set("last_modifed_by", ASC.Core.SecurityContext.CurrentAccount.ID)
                .Where(Exp.Eq("id", deal.ID))
                );

            FactoryIndexer <DealsWrapper> .IndexAsync(deal);
        }
示例#5
0
        public Page SavePage(Page page)
        {
            using (var dao = GetPageDao())
            {
                var saved = dao.SavePage(page);
                FactoryIndexer <WikiWrapper> .IndexAsync(page);

                if (saved != null)
                {
                    var subscriptionProvider = WikiNotifySource.Instance.GetSubscriptionProvider();
                    var amAsRecipient        = (IDirectRecipient)WikiNotifySource.Instance.GetRecipientsProvider().GetRecipient(SecurityContext.CurrentAccount.ID.ToString());

                    subscriptionProvider.Subscribe(
                        Constants.EditPage,
                        PageNameUtil.ReplaceSpaces(page.PageName),
                        amAsRecipient
                        );

                    if (saved.Version == 1)
                    {
                        NotifyPageCreated(saved);
                    }
                    else
                    {
                        NotifyPageEdited(saved);
                    }
                }

                return(saved);
            }
        }
        public Folder CopyFolder(object folderId, object toFolderId, CancellationToken?cancellationToken)
        {
            var folder = GetFolder(folderId);

            var toFolder = GetFolder(toFolderId);

            if (folder.FolderType == FolderType.BUNCH)
            {
                folder.FolderType = FolderType.DEFAULT;
            }

            var copy = new Folder
            {
                ParentFolderID    = toFolderId,
                RootFolderId      = toFolder.RootFolderId,
                RootFolderCreator = toFolder.RootFolderCreator,
                RootFolderType    = toFolder.RootFolderType,
                Title             = folder.Title,
                FolderType        = folder.FolderType
            };

            copy = GetFolder(SaveFolder(copy));

            FactoryIndexer <FoldersWrapper> .IndexAsync(copy);

            return(copy);
        }
示例#7
0
        public Page UpdatePage(Page page)
        {
            var toUpdate = GetPage(page.PageName);

            if (toUpdate == null)
            {
                throw new ItemNotFoundException("page not found");
            }
            if (String.IsNullOrEmpty(page.Body))
            {
                throw new ArgumentException(@"page content cannot be empty", "page");
            }

            toUpdate.UserID = SecurityContext.CurrentAccount.ID;
            toUpdate.Body   = page.Body;
            toUpdate.Version++;
            toUpdate.Date = DateTime.UtcNow;

            toUpdate = SavePage(toUpdate);
            UpdateCategoriesByPageContent(toUpdate);

            FactoryIndexer <WikiWrapper> .IndexAsync(toUpdate);

            return(toUpdate);
        }
示例#8
0
        public virtual Project SaveOrUpdate(Project project, bool notifyManager, bool isImport)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            // check guest responsible
            if (ProjectSecurity.IsVisitor(project.Responsible))
            {
                ProjectSecurity.CreateGuestSecurityException();
            }

            project.LastModifiedBy = SecurityContext.CurrentAccount.ID;
            project.LastModifiedOn = TenantUtil.DateTimeNow();

            if (project.ID == 0)
            {
                if (project.CreateBy == default(Guid))
                {
                    project.CreateBy = SecurityContext.CurrentAccount.ID;
                }
                if (project.CreateOn == default(DateTime))
                {
                    project.CreateOn = TenantUtil.DateTimeNow();
                }

                ProjectSecurity.DemandCreate <Project>(null);

                DaoFactory.ProjectDao.Create(project);

                FactoryIndexer <ProjectsWrapper> .IndexAsync(project);
            }
            else
            {
                var oldProject = DaoFactory.ProjectDao.GetById(new List <int> {
                    project.ID
                }).FirstOrDefault();
                ProjectSecurity.DemandEdit(oldProject);

                DaoFactory.ProjectDao.Update(project);

                if (!project.Private)
                {
                    ResetTeamSecurity(oldProject);
                }

                FactoryIndexer <ProjectsWrapper> .UpdateAsync(project);
            }

            if (notifyManager && !DisableNotifications && !project.Responsible.Equals(SecurityContext.CurrentAccount.ID))
            {
                NotifyClient.Instance.SendAboutResponsibleByProject(project.Responsible, project);
            }

            return(project);
        }
示例#9
0
        public virtual int CreateNewDeal(Deal deal)
        {
            var result = CreateNewDealInDb(deal);

            deal.ID = result;

            FactoryIndexer <DealsWrapper> .IndexAsync(deal);

            return(result);
        }
示例#10
0
        public Bookmark UpdateBookmark(UserBookmark userBookmark, IList <Tag> tags)
        {
            Dao.UpdateBookmark(userBookmark, tags);
            var b = GetBookmarkByID(userBookmark.BookmarkID);

            SubscribeOnBookmarkComments(b);
            FactoryIndexer <BookmarksUserWrapper> .IndexAsync(BookmarksUserWrapper.Create(userBookmark, b));

            return(b);
        }
示例#11
0
        public virtual int SaveOrUpdateInvoice(Invoice invoice)
        {
            _cache.Remove(new Regex(TenantID.ToString(CultureInfo.InvariantCulture) + "invoice.*"));

            var result = SaveOrUpdateInvoiceInDb(invoice);

            FactoryIndexer <InvoicesWrapper> .IndexAsync(invoice);

            return(result);
        }
示例#12
0
        public Message SaveOrUpdate(Message message, bool notify, IEnumerable <Guid> participant,
                                    IEnumerable <int> fileIds = null)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            var isNew = message.ID == default(int);

            message.LastModifiedBy = SecurityContext.CurrentAccount.ID;
            message.LastModifiedOn = TenantUtil.DateTimeNow();

            if (isNew)
            {
                if (message.CreateBy == default(Guid))
                {
                    message.CreateBy = SecurityContext.CurrentAccount.ID;
                }
                if (message.CreateOn == default(DateTime))
                {
                    message.CreateOn = TenantUtil.DateTimeNow();
                }

                ProjectSecurity.DemandCreate <Message>(message.Project);
                DaoFactory.MessageDao.Save(message);
            }
            else
            {
                ProjectSecurity.DemandEdit(message);
                DaoFactory.MessageDao.Save(message);
            }

            if (fileIds != null)
            {
                foreach (var fileId in fileIds)
                {
                    AttachFile(message, fileId);
                }
            }

            if (participant == null)
            {
                participant = GetSubscribers(message).Select(r => new Guid(r.ID)).ToList();
            }

            NotifyParticipiant(message, isNew, participant, GetFiles(message), notify);

            FactoryIndexer <DiscussionsWrapper> .IndexAsync(message);

            return(message);
        }
示例#13
0
 public virtual int[] SaveDealList(List <Deal> items)
 {
     using (var tx = Db.BeginTransaction())
     {
         var result = items.Select(item => CreateNewDealInDb(item)).ToArray();
         tx.Commit();
         foreach (var item in items)
         {
             FactoryIndexer <DealsWrapper> .IndexAsync(item);
         }
         return(result);
     }
 }
示例#14
0
        public CasesWrapper CreateCases(
            string title,
            IEnumerable <int> members,
            IEnumerable <ItemKeyValuePair <int, string> > customFieldList,
            bool isPrivate,
            IEnumerable <Guid> accessList,
            bool isNotify)
        {
            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentException();
            }

            var casesID = DaoFactory.CasesDao.CreateCases(title);

            var cases = new Cases
            {
                ID       = casesID,
                Title    = title,
                CreateBy = SecurityContext.CurrentAccount.ID,
                CreateOn = DateTime.UtcNow
            };

            FactoryIndexer <Web.CRM.Core.Search.CasesWrapper> .IndexAsync(cases);

            SetAccessToCases(cases, isPrivate, accessList, isNotify, false);

            var membersList = members != null?members.ToList() : new List <int>();

            if (membersList.Any())
            {
                var contacts = DaoFactory.ContactDao.GetContacts(membersList.ToArray()).Where(CRMSecurity.CanAccessTo).ToList();
                membersList = contacts.Select(m => m.ID).ToList();
                DaoFactory.CasesDao.SetMembers(cases.ID, membersList.ToArray());
            }

            if (customFieldList != null)
            {
                var existingCustomFieldList = DaoFactory.CustomFieldDao.GetFieldsDescription(EntityType.Case).Select(fd => fd.ID).ToList();
                foreach (var field in customFieldList)
                {
                    if (string.IsNullOrEmpty(field.Value) || !existingCustomFieldList.Contains(field.Key))
                    {
                        continue;
                    }
                    DaoFactory.CustomFieldDao.SetFieldValue(EntityType.Case, cases.ID, field.Key, field.Value);
                }
            }

            return(ToCasesWrapper(DaoFactory.CasesDao.GetByID(casesID)));
        }
示例#15
0
        public void SaveMessages(params Message[] messages)
        {
            if (messages == null)
            {
                throw new ArgumentNullException("message");
            }
            if (messages.Length == 0)
            {
                return;
            }

            foreach (var m in messages)
            {
                if (string.IsNullOrEmpty(m.Body) && string.IsNullOrEmpty(m.Subject) && string.IsNullOrEmpty(m.Thread) && m.Html == null)
                {
                    continue;
                }

                if (m.XDelay == null)
                {
                    m.XDelay = new Delay();
                }
                if (m.XDelay.Stamp == default(DateTime))
                {
                    m.XDelay.Stamp = DateTime.UtcNow;
                }

                var message = ElementSerializer.SerializeElement(m);
                var jid     = GetKey(m.From, m.To);
                var stamp   = DateTime.UtcNow;

                var id = ExecuteScalar <int>(
                    new SqlInsert("jabber_archive")
                    .InColumnValue("id", 0)
                    .InColumnValue("jid", jid)
                    .InColumnValue("stamp", stamp)
                    .InColumnValue("message", message)
                    .Identity(0, 0, true));

                FactoryIndexer <JabberWrapper> .IndexAsync(new JabberWrapper
                {
                    Id             = id,
                    Jid            = jid,
                    LastModifiedOn = stamp,
                    Message        = message
                });
            }
        }
示例#16
0
        public Feed SaveFeed(Feed feed, bool isEdit, FeedType type)
        {
            if (feed == null)
            {
                throw new ArgumentNullException("feed");
            }

            using (var tx = dbManager.BeginTransaction())
            {
                feed.Id = dbManager.ExecuteScalar <long>(
                    Insert("events_feed").InColumns("Id", "FeedType", "Caption", "Text", "Date", "Creator")
                    .Values(feed.Id, feed.FeedType, feed.Caption, feed.Text, TenantUtil.DateTimeToUtc(feed.Date),
                            feed.Creator)
                    .Identity(1, 0L, true)
                    );

                var poll = feed as FeedPoll;
                if (poll != null)
                {
                    dbManager.ExecuteNonQuery(Insert("events_poll").InColumns("Id", "PollType", "StartDate", "EndDate")
                                              .Values(poll.Id, poll.PollType,
                                                      TenantUtil.DateTimeToUtc(poll.StartDate),
                                                      TenantUtil.DateTimeToUtc(poll.EndDate)));

                    dbManager.ExecuteNonQuery(Delete("events_pollvariant").Where("Poll", poll.Id));
                    foreach (var variant in poll.Variants)
                    {
                        variant.ID = dbManager.ExecuteScalar <long>(
                            Insert("events_pollvariant").InColumns("Id", "Name", "Poll")
                            .Values(variant.ID, variant.Name, poll.Id)
                            .Identity(1, 0L, true));
                    }
                }
                tx.Commit();
            }


            NotifyFeed(feed, isEdit, type);

            FactoryIndexer <NewsWrapper> .IndexAsync(feed);

            return(feed);
        }
示例#17
0
        private void SetFieldValueInDb(EntityType entityType, int entityID, int fieldID, String fieldValue)
        {
            if (!_supportedEntityType.Contains(entityType))
            {
                throw new ArgumentException();
            }

            fieldValue = fieldValue.Trim();

            Db.ExecuteNonQuery(Delete("crm_field_value").Where(Exp.Eq("entity_id", entityID) & Exp.Eq("entity_type", (int)entityType) & Exp.Eq("field_id", fieldID)));

            if (!String.IsNullOrEmpty(fieldValue))
            {
                var lastModifiedOn = TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow());
                var id             = Db.ExecuteScalar <int>(
                    Insert("crm_field_value")
                    .InColumnValue("id", 0)
                    .InColumnValue("entity_id", entityID)
                    .InColumnValue("value", fieldValue)
                    .InColumnValue("field_id", fieldID)
                    .InColumnValue("entity_type", (int)entityType)
                    .InColumnValue("last_modifed_on", lastModifiedOn)
                    .InColumnValue("last_modifed_by", ASC.Core.SecurityContext.CurrentAccount.ID)
                    .Identity(1, 0, true)
                    );

                FactoryIndexer <FieldsWrapper> .IndexAsync(new FieldsWrapper
                {
                    Id             = id,
                    EntityId       = entityID,
                    EntityType     = (int)entityType,
                    Value          = fieldValue,
                    FieldId        = fieldID,
                    LastModifiedOn = lastModifiedOn,
                    TenantId       = CoreContext.TenantManager.GetCurrentTenant().TenantId
                });
            }
        }
示例#18
0
        public int Save(ContactInfo contactInfo)
        {
            var id = SaveInDb(contactInfo);

            contactInfo.ID = id;

            FactoryIndexer <InfoWrapper> .IndexAsync(contactInfo);

            if (contactInfo.InfoType == ContactInfoType.Email)
            {
                FactoryIndexer <EmailWrapper> .Index(new EmailWrapper
                {
                    Id               = contactInfo.ContactID,
                    TenantId         = TenantID,
                    EmailInfoWrapper = new List <EmailInfoWrapper>
                    {
                        contactInfo
                    }
                });
            }

            return(id);
        }
示例#19
0
        public object SaveFolder(Folder folder)
        {
            if (folder == null)
            {
                throw new ArgumentNullException("folder");
            }

            folder.Title = Global.ReplaceInvalidCharsAndTruncate(folder.Title);

            folder.ModifiedOn = TenantUtil.DateTimeNow();
            folder.ModifiedBy = SecurityContext.CurrentAccount.ID;

            if (folder.CreateOn == default(DateTime))
            {
                folder.CreateOn = TenantUtil.DateTimeNow();
            }
            if (folder.CreateBy == default(Guid))
            {
                folder.CreateBy = SecurityContext.CurrentAccount.ID;
            }

            var isnew = false;

            using (var tx = dbManager.BeginTransaction(true))
            {
                if (folder.ID != null && IsExist(folder.ID))
                {
                    dbManager.ExecuteNonQuery(
                        Update("files_folder")
                        .Set("title", folder.Title)
                        .Set("create_by", folder.CreateBy.ToString())
                        .Set("modified_on", TenantUtil.DateTimeToUtc(folder.ModifiedOn))
                        .Set("modified_by", folder.ModifiedBy.ToString())
                        .Where("id", folder.ID));
                }
                else
                {
                    isnew     = true;
                    folder.ID = dbManager.ExecuteScalar <int>(
                        Insert("files_folder")
                        .InColumnValue("id", 0)
                        .InColumnValue("parent_id", folder.ParentFolderID)
                        .InColumnValue("title", folder.Title)
                        .InColumnValue("create_on", TenantUtil.DateTimeToUtc(folder.CreateOn))
                        .InColumnValue("create_by", folder.CreateBy.ToString())
                        .InColumnValue("modified_on", TenantUtil.DateTimeToUtc(folder.ModifiedOn))
                        .InColumnValue("modified_by", folder.ModifiedBy.ToString())
                        .InColumnValue("folder_type", (int)folder.FolderType)
                        .Identity(1, 0, true));

                    //itself link
                    dbManager.ExecuteNonQuery(
                        new SqlInsert("files_folder_tree")
                        .InColumns("folder_id", "parent_id", "level")
                        .Values(folder.ID, folder.ID, 0));

                    //full path to root
                    dbManager.ExecuteNonQuery(
                        new SqlInsert("files_folder_tree")
                        .InColumns("folder_id", "parent_id", "level")
                        .Values(
                            new SqlQuery("files_folder_tree t")
                            .Select(folder.ID.ToString(), "t.parent_id", "t.level + 1")
                            .Where("t.folder_id", folder.ParentFolderID)));
                }

                tx.Commit();
            }

            if (!dbManager.InTransaction && isnew)
            {
                RecalculateFoldersCount(folder.ID);
            }

            if (folder.FolderType == FolderType.DEFAULT || folder.FolderType == FolderType.BUNCH)
            {
                FactoryIndexer <FoldersWrapper> .IndexAsync(folder);
            }
            return(folder.ID);
        }
示例#20
0
        internal void UpdateBookmark(Bookmark bookmark, IList <Tag> tags)
        {
            UserBookmark userBookmark = null;
            var          tx           = DbManager.BeginTransaction();

            try
            {
                var date = Core.Tenants.TenantUtil.DateTimeToUtc(bookmark.Date);

                bookmark.ID = DbManager.ExecuteScalar <long>(
                    new SqlInsert("bookmarking_bookmark", true)
                    .InColumns("ID", "URL", "Date", "Name", "Description", "UserCreatorID", "Tenant")
                    .Values(bookmark.ID, bookmark.URL, date, bookmark.Name, bookmark.Description, bookmark.UserCreatorID, Tenant)
                    .Identity(0, 0L, true));

                DbManager.ExecuteNonQuery(
                    new SqlDelete("bookmarking_bookmarktag")
                    .Where(Exp.Eq("BookmarkID", bookmark.ID)
                           & Exp.Eq("Tenant", Tenant)));

                userBookmark = GetCurrentUserBookmark(bookmark);
                long userBookmarkId = 0;
                if (userBookmark != null)
                {
                    userBookmarkId = userBookmark.UserBookmarkID;
                }

                var nowDate = DateTime.UtcNow;

                userBookmarkId = DbManager.ExecuteScalar <long>(
                    new SqlInsert("bookmarking_userbookmark", true)
                    .InColumns("UserBookmarkID", "UserID", "DateAdded", "Name", "Description", "BookmarkID", "Raiting", "Tenant")
                    .Values(userBookmarkId, GetCurrentUserId(), nowDate, bookmark.Name, bookmark.Description, bookmark.ID, 1, Tenant)
                    .Identity(0, 0L, true));

                userBookmark = new UserBookmark
                {
                    UserBookmarkID = userBookmarkId,
                    BookmarkID     = bookmark.ID,
                    UserID         = GetCurrentUserId(),
                    DateAdded      = nowDate,
                    Name           = bookmark.Name,
                    Description    = bookmark.Description,
                    Raiting        = 1
                };

                DbManager.ExecuteNonQuery(
                    new SqlDelete("bookmarking_userbookmarktag")
                    .Where(Exp.Eq("UserBookmarkID", userBookmarkId)
                           & Exp.Eq("Tenant", Tenant)));

                if (bookmark.Tags == null)
                {
                    bookmark.Tags = new List <Tag>();
                }
                foreach (var tag in tags)
                {
                    tag.TagID = DbManager.ExecuteScalar <long>(
                        new SqlInsert("bookmarking_tag", true)
                        .InColumns("TagID", "Name", "Tenant")
                        .Values(tag.TagID, tag.Name, Tenant)
                        .Identity(0, 0L, true));

                    new BookmarkTag
                    {
                        BookmarkID    = bookmark.ID,
                        TagID         = tag.TagID,
                        BookmarkTagID = DbManager.ExecuteScalar <long>(
                            new SqlInsert("bookmarking_bookmarktag", true)
                            .InColumns("BookmarkID", "TagID", "Tenant")
                            .Values(bookmark.ID, tag.TagID, Tenant)
                            .Identity(0, 0L, true))
                    };



                    var ubt = new UserBookmarkTag {
                        UserBookmarkID = userBookmarkId, TagID = tag.TagID
                    };

                    ubt.UserBookmarkTagID = DbManager.ExecuteScalar <long>(
                        new SqlInsert("bookmarking_userbookmarktag", true)
                        .InColumns("UserBookmarkID", "TagID", "Tenant")
                        .Values(ubt.UserBookmarkID, tag.TagID, Tenant)
                        .Identity(0, 0L, true));

                    if (bookmark.Tags.All(r => r.TagID == tag.TagID))
                    {
                        bookmark.Tags.Add(tag);
                    }
                }

                tx.Commit();
            }
            catch (Exception)
            {
                tx.Rollback();
            }

            if (userBookmark != null)
            {
                FactoryIndexer <BookmarksUserWrapper> .IndexAsync(BookmarksUserWrapper.Create(userBookmark, bookmark));
            }
        }
示例#21
0
        public void SavePost(Post post, bool isNew, bool notifyComments)
        {
            CommunitySecurity.DemandPermissions(
                new PersonalBlogSecObject(CoreContext.UserManager.GetUsers(post.UserID)),
                isNew ? Constants.Action_AddPost : Constants.Action_EditRemovePost);

            _storage.GetPostDao().SavePost(post);
            FactoryIndexer <BlogsWrapper> .IndexAsync(post);

            if (isNew)
            {
                var initiatorInterceptor = new InitiatorInterceptor(new DirectRecipient(post.UserID.ToString(), ""));
                try
                {
                    NotifyClient.BeginSingleRecipientEvent("asc_blog");
                    NotifyClient.AddInterceptor(initiatorInterceptor);

                    var tags = new List <ITagValue>
                    {
                        new TagValue(Constants.TagPostSubject, post.Title),
                        new TagValue(Constants.TagPostPreview,
                                     post.GetPreviewText(500)),
                        new TagValue(Constants.TagUserName,
                                     DisplayUserSettings.GetFullUserName(post.UserID)),
                        new TagValue(Constants.TagUserURL,
                                     CommonLinkUtility.GetFullAbsolutePath(
                                         CommonLinkUtility.GetUserProfile(post.UserID))),
                        new TagValue(Constants.TagDate,
                                     string.Format("{0:d} {0:t}", post.Datetime)),
                        new TagValue(Constants.TagURL,
                                     CommonLinkUtility.GetFullAbsolutePath(
                                         Constants.ViewBlogPageUrl +
                                         "?blogid=" + post.ID.ToString())),
                        GetReplyToTag(Guid.Empty, post)
                    };

                    NotifyClient.SendNoticeAsync(
                        Constants.NewPost,
                        null,
                        null,
                        tags.ToArray());


                    NotifyClient.SendNoticeAsync(
                        Constants.NewPostByAuthor,
                        post.UserID.ToString(),
                        null,
                        tags.ToArray());

                    NotifyClient.EndSingleRecipientEvent("asc_blog");
                }
                finally
                {
                    NotifyClient.RemoveInterceptor(initiatorInterceptor.Name);
                }
            }
            if (!notifyComments)
            {
                return;
            }

            var subscriptionProvider = NotifySource.GetSubscriptionProvider();

            subscriptionProvider.Subscribe(
                Constants.NewComment,
                post.ID.ToString(),
                NotifySource.GetRecipientsProvider().
                GetRecipient(post.UserID.ToString())
                );
        }
        protected void SaveOrUpdateCase(object sender, CommandEventArgs e)
        {
            try
            {
                using (var scope = DIHelper.Resolve())
                {
                    var daoFactory = scope.Resolve <DaoFactory>();
                    int caseID;

                    if (TargetCase != null)
                    {
                        caseID           = TargetCase.ID;
                        TargetCase.Title = Request["caseTitle"];
                        daoFactory.CasesDao.UpdateCases(TargetCase);
                        FactoryIndexer <CasesWrapper> .UpdateAsync(TargetCase);

                        MessageService.Send(HttpContext.Current.Request, MessageAction.CaseUpdated, MessageTarget.Create(TargetCase.ID), TargetCase.Title);
                        SetPermission(TargetCase);
                    }
                    else
                    {
                        caseID = daoFactory.CasesDao.CreateCases(Request["caseTitle"]);
                        var newCase = daoFactory.CasesDao.GetByID(caseID);
                        FactoryIndexer <CasesWrapper> .IndexAsync(newCase);

                        MessageService.Send(HttpContext.Current.Request, MessageAction.CaseCreated, MessageTarget.Create(newCase.ID), newCase.Title);
                        SetPermission(newCase);
                    }


                    daoFactory.CasesDao.SetMembers(caseID,
                                                   !String.IsNullOrEmpty(Request["memberID"])
                            ? Request["memberID"].Split(',').Select(
                                                       id => Convert.ToInt32(id)).ToArray()
                            : new List <int>().ToArray());


                    var assignedTags = Request["baseInfo_assignedTags"];
                    if (assignedTags != null)
                    {
                        var oldTagList = daoFactory.TagDao.GetEntityTags(EntityType.Case, caseID);
                        foreach (var tag in oldTagList)
                        {
                            daoFactory.TagDao.DeleteTagFromEntity(EntityType.Case, caseID, tag);
                        }
                        if (assignedTags != string.Empty)
                        {
                            var tagListInfo = JObject.Parse(assignedTags)["tagListInfo"].ToArray();
                            var newTagList  = tagListInfo.Select(t => t.ToString()).ToArray();
                            daoFactory.TagDao.SetTagToEntity(EntityType.Case, caseID, newTagList);
                        }
                    }

                    foreach (var customField in Request.Form.AllKeys)
                    {
                        if (!customField.StartsWith("customField_"))
                        {
                            continue;
                        }
                        int    fieldID    = Convert.ToInt32(customField.Split('_')[1]);
                        string fieldValue = Request.Form[customField];

                        if (String.IsNullOrEmpty(fieldValue) && TargetCase == null)
                        {
                            continue;
                        }

                        daoFactory.CustomFieldDao.SetFieldValue(EntityType.Case, caseID, fieldID, fieldValue);
                    }

                    Response.Redirect(
                        string.Compare(e.CommandArgument.ToString(), "0", StringComparison.OrdinalIgnoreCase) == 0
                            ? string.Format("Cases.aspx?id={0}", caseID)
                            : "Cases.aspx?action=manage", false);
                    Context.ApplicationInstance.CompleteRequest();
                }
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("ASC.CRM").Error(ex);
                var cookie = HttpContext.Current.Request.Cookies.Get(ErrorCookieKey);
                if (cookie == null)
                {
                    cookie = new HttpCookie(ErrorCookieKey)
                    {
                        Value = ex.Message
                    };
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
            }
        }
示例#23
0
        public File SaveFile(File file, Stream fileStream, bool checkQuota = true)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            if (checkQuota && SetupInfo.MaxChunkedUploadSize < file.ContentLength)
            {
                throw FileSizeComment.GetFileSizeException(SetupInfo.MaxChunkedUploadSize);
            }

            if (CoreContext.Configuration.Personal && SetupInfo.IsVisibleSettings("PersonalMaxSpace"))
            {
                if (CoreContext.Configuration.PersonalMaxSpace - Global.GetUserUsedSpace(file.ID == null ? SecurityContext.CurrentAccount.ID : file.CreateBy) < file.ContentLength)
                {
                    throw FileSizeComment.GetPersonalFreeSpaceException(CoreContext.Configuration.PersonalMaxSpace);
                }
            }

            var           isNew = false;
            List <object> parentFoldersIds;

            lock (syncRoot)
            {
                using (var tx = dbManager.BeginTransaction())
                {
                    if (file.ID == null)
                    {
                        file.ID           = dbManager.ExecuteScalar <int>(new SqlQuery("files_file").SelectMax("id")) + 1;
                        file.Version      = 1;
                        file.VersionGroup = 1;
                        isNew             = true;
                    }

                    file.Title = Global.ReplaceInvalidCharsAndTruncate(file.Title);
                    //make lowerCase
                    file.Title = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetFileExtension(file.Title));

                    file.ModifiedBy = SecurityContext.CurrentAccount.ID;
                    file.ModifiedOn = TenantUtil.DateTimeNow();
                    if (file.CreateBy == default(Guid))
                    {
                        file.CreateBy = SecurityContext.CurrentAccount.ID;
                    }
                    if (file.CreateOn == default(DateTime))
                    {
                        file.CreateOn = TenantUtil.DateTimeNow();
                    }

                    dbManager.ExecuteNonQuery(
                        Update("files_file")
                        .Set("current_version", false)
                        .Where("id", file.ID)
                        .Where("current_version", true));

                    var sql = Insert("files_file")
                              .InColumnValue("id", file.ID)
                              .InColumnValue("version", file.Version)
                              .InColumnValue("version_group", file.VersionGroup)
                              .InColumnValue("current_version", true)
                              .InColumnValue("folder_id", file.FolderID)
                              .InColumnValue("title", file.Title)
                              .InColumnValue("content_length", file.ContentLength)
                              .InColumnValue("category", (int)file.FilterType)
                              .InColumnValue("create_by", file.CreateBy.ToString())
                              .InColumnValue("create_on", TenantUtil.DateTimeToUtc(file.CreateOn))
                              .InColumnValue("modified_by", file.ModifiedBy.ToString())
                              .InColumnValue("modified_on", TenantUtil.DateTimeToUtc(file.ModifiedOn))
                              .InColumnValue("converted_type", file.ConvertedType)
                              .InColumnValue("comment", file.Comment)
                              .InColumnValue("encrypted", file.Encrypted)
                              .InColumnValue("forcesave", (int)file.Forcesave)
                              .InColumnValue("thumb", file.ThumbnailStatus);
                    dbManager.ExecuteNonQuery(sql);
                    tx.Commit();

                    file.PureTitle = file.Title;

                    parentFoldersIds = dbManager.ExecuteList(
                        new SqlQuery("files_folder_tree")
                        .Select("parent_id")
                        .Where(Exp.Eq("folder_id", file.FolderID))
                        .OrderBy("level", false)
                        ).ConvertAll(row => row[0]);

                    if (parentFoldersIds.Count > 0)
                    {
                        dbManager.ExecuteNonQuery(
                            Update("files_folder")
                            .Set("modified_on", TenantUtil.DateTimeToUtc(file.ModifiedOn))
                            .Set("modified_by", file.ModifiedBy.ToString())
                            .Where(Exp.In("id", parentFoldersIds)));
                    }

                    if (isNew)
                    {
                        RecalculateFilesCount(dbManager, file.FolderID);
                    }
                }
            }

            if (fileStream != null)
            {
                try
                {
                    SaveFileStream(file, fileStream);
                }
                catch (Exception saveException)
                {
                    try
                    {
                        if (isNew)
                        {
                            var stored = Global.GetStore().IsDirectory(GetUniqFileDirectory(file.ID));
                            DeleteFile(file.ID, stored);
                        }
                        else if (!IsExistOnStorage(file))
                        {
                            DeleteVersion(file);
                        }
                    }
                    catch (Exception deleteException)
                    {
                        throw new Exception(saveException.Message, deleteException);
                    }
                    throw;
                }
            }

            FactoryIndexer <FilesWrapper> .IndexAsync(FilesWrapper.GetFilesWrapper(file, parentFoldersIds));

            return(GetFile(file.ID));
        }
示例#24
0
        public Task SaveOrUpdate(Task task, IEnumerable <int> attachedFileIds, bool notifyResponsible, bool isImport = false)
        {
            if (task == null)
            {
                throw new ArgumentNullException("task");
            }
            if (task.Project == null)
            {
                throw new Exception("task.Project");
            }

            var milestone            = task.Milestone != 0 ? DaoFactory.MilestoneDao.GetById(task.Milestone) : null;
            var milestoneResponsible = milestone != null ? milestone.Responsible : Guid.Empty;

            var removeResponsibles   = new List <Guid>();
            var inviteToResponsibles = new List <Guid>();

            task.Responsibles.RemoveAll(r => r.Equals(Guid.Empty));

            if (task.Deadline.Kind != DateTimeKind.Local && task.Deadline != DateTime.MinValue)
            {
                task.Deadline = TenantUtil.DateTimeFromUtc(task.Deadline);
            }

            if (task.StartDate.Kind != DateTimeKind.Local && task.StartDate != DateTime.MinValue)
            {
                task.StartDate = TenantUtil.DateTimeFromUtc(task.StartDate);
            }

            var isNew = task.ID == default(int); //Task is new

            if (isNew)
            {
                foreach (var responsible in task.Responsibles)
                {
                    if (ProjectSecurity.IsVisitor(responsible))
                    {
                        ProjectSecurity.CreateGuestSecurityException();
                    }

                    if (!ProjectSecurity.IsInTeam(task.Project, responsible))
                    {
                        ProjectSecurity.CreateSecurityException();
                    }
                }

                if (task.CreateBy == default(Guid))
                {
                    task.CreateBy = SecurityContext.CurrentAccount.ID;
                }
                if (task.CreateOn == default(DateTime))
                {
                    task.CreateOn = TenantUtil.DateTimeNow();
                }

                ProjectSecurity.DemandCreate <Task>(task.Project);

                task = DaoFactory.TaskDao.Create(task);

                inviteToResponsibles.AddRange(task.Responsibles.Distinct());
            }
            else
            {
                var oldTask = DaoFactory.TaskDao.GetById(new[] { task.ID }).FirstOrDefault();

                if (oldTask == null)
                {
                    throw new ArgumentNullException("task");
                }
                ProjectSecurity.DemandEdit(oldTask);

                var newResponsibles = task.Responsibles.Distinct().ToList();
                var oldResponsibles = oldTask.Responsibles.Distinct().ToList();

                foreach (var responsible in newResponsibles.Except(oldResponsibles))
                {
                    if (ProjectSecurity.IsVisitor(responsible))
                    {
                        ProjectSecurity.CreateGuestSecurityException();
                    }

                    if (!ProjectSecurity.IsInTeam(task.Project, responsible))
                    {
                        ProjectSecurity.CreateSecurityException();
                    }
                }

                removeResponsibles.AddRange(oldResponsibles.Where(p => !newResponsibles.Contains(p)));
                inviteToResponsibles.AddRange(newResponsibles.Where(participant => !oldResponsibles.Contains(participant)));

                task.LastModifiedBy = SecurityContext.CurrentAccount.ID;
                task.LastModifiedOn = TenantUtil.DateTimeNow();

                task = DaoFactory.TaskDao.Update(task);
            }

            FactoryIndexer <TasksWrapper> .IndexAsync(task);

            if (attachedFileIds != null && attachedFileIds.Any())
            {
                foreach (var attachedFileId in attachedFileIds)
                {
                    AttachFile(task, attachedFileId);
                }
            }

            var senders = new HashSet <Guid>(task.Responsibles)
            {
                task.Project.Responsible, milestoneResponsible, task.CreateBy
            };

            senders.Remove(Guid.Empty);

            foreach (var subscriber in senders)
            {
                Subscribe(task, subscriber);
            }

            inviteToResponsibles.RemoveAll(r => r.Equals(Guid.Empty));
            removeResponsibles.RemoveAll(r => r.Equals(Guid.Empty));

            NotifyTask(task, inviteToResponsibles, removeResponsibles, isNew, notifyResponsible);

            return(task);
        }
示例#25
0
        private Task SaveOrUpdateTaskInDb(Task newTask)
        {
            if (String.IsNullOrEmpty(newTask.Title) || newTask.DeadLine == DateTime.MinValue ||
                newTask.CategoryID <= 0)
            {
                throw new ArgumentException();
            }

            if (newTask.ID == 0 || Db.ExecuteScalar <int>(Query("crm_task").SelectCount().Where(Exp.Eq("id", newTask.ID))) == 0)
            {
                newTask.CreateOn = DateTime.UtcNow;
                newTask.CreateBy = ASC.Core.SecurityContext.CurrentAccount.ID;

                newTask.LastModifedOn = DateTime.UtcNow;
                newTask.LastModifedBy = ASC.Core.SecurityContext.CurrentAccount.ID;

                newTask.ID = Db.ExecuteScalar <int>(
                    Insert("crm_task")
                    .InColumnValue("id", 0)
                    .InColumnValue("title", newTask.Title)
                    .InColumnValue("description", newTask.Description)
                    .InColumnValue("deadline", TenantUtil.DateTimeToUtc(newTask.DeadLine))
                    .InColumnValue("responsible_id", newTask.ResponsibleID)
                    .InColumnValue("contact_id", newTask.ContactID)
                    .InColumnValue("entity_type", (int)newTask.EntityType)
                    .InColumnValue("entity_id", newTask.EntityID)
                    .InColumnValue("is_closed", newTask.IsClosed)
                    .InColumnValue("category_id", newTask.CategoryID)
                    .InColumnValue("create_on", newTask.CreateOn)
                    .InColumnValue("create_by", newTask.CreateBy)
                    .InColumnValue("last_modifed_on", newTask.LastModifedOn)
                    .InColumnValue("last_modifed_by", newTask.LastModifedBy)
                    .InColumnValue("alert_value", newTask.AlertValue)
                    .Identity(1, 0, true));
            }
            else
            {
                var oldTask = Db.ExecuteList(GetTaskQuery(Exp.Eq("id", newTask.ID)))
                              .ConvertAll(row => ToTask(row))
                              .FirstOrDefault();

                CRMSecurity.DemandEdit(oldTask);

                newTask.CreateOn = oldTask.CreateOn;
                newTask.CreateBy = oldTask.CreateBy;

                newTask.LastModifedOn = DateTime.UtcNow;
                newTask.LastModifedBy = ASC.Core.SecurityContext.CurrentAccount.ID;

                newTask.IsClosed = oldTask.IsClosed;

                Db.ExecuteNonQuery(
                    Update("crm_task")
                    .Set("title", newTask.Title)
                    .Set("description", newTask.Description)
                    .Set("deadline", TenantUtil.DateTimeToUtc(newTask.DeadLine))
                    .Set("responsible_id", newTask.ResponsibleID)
                    .Set("contact_id", newTask.ContactID)
                    .Set("entity_type", (int)newTask.EntityType)
                    .Set("entity_id", newTask.EntityID)
                    .Set("category_id", newTask.CategoryID)
                    .Set("last_modifed_on", newTask.LastModifedOn)
                    .Set("last_modifed_by", newTask.LastModifedBy)
                    .Set("alert_value", (int)newTask.AlertValue)
                    .Set("exec_alert", 0)
                    .Where(Exp.Eq("id", newTask.ID)));
            }

            FactoryIndexer <TasksWrapper> .IndexAsync(newTask);

            return(newTask);
        }
        public Subtask SaveOrUpdate(Subtask subtask, Task task)
        {
            if (subtask == null)
            {
                throw new Exception("subtask.Task");
            }
            if (task == null)
            {
                throw new ArgumentNullException("task");
            }
            if (task.Status == TaskStatus.Closed)
            {
                throw new Exception("task can't be closed");
            }

            // check guest responsible
            if (ProjectSecurity.IsVisitor(subtask.Responsible))
            {
                ProjectSecurity.CreateGuestSecurityException();
            }

            var isNew          = subtask.ID == default(int); //Task is new
            var oldResponsible = Guid.Empty;

            subtask.LastModifiedBy = SecurityContext.CurrentAccount.ID;
            subtask.LastModifiedOn = TenantUtil.DateTimeNow();

            if (isNew)
            {
                if (subtask.CreateBy == default(Guid))
                {
                    subtask.CreateBy = SecurityContext.CurrentAccount.ID;
                }
                if (subtask.CreateOn == default(DateTime))
                {
                    subtask.CreateOn = TenantUtil.DateTimeNow();
                }

                ProjectSecurity.DemandEdit(task);
                subtask = DaoFactory.SubtaskDao.Save(subtask);
            }
            else
            {
                var oldSubtask = DaoFactory.SubtaskDao.GetById(new[] { subtask.ID }).First();

                if (oldSubtask == null)
                {
                    throw new ArgumentNullException("subtask");
                }

                oldResponsible = oldSubtask.Responsible;

                //changed task
                ProjectSecurity.DemandEdit(task, oldSubtask);
                subtask = DaoFactory.SubtaskDao.Save(subtask);
            }

            NotifySubtask(task, subtask, isNew, oldResponsible);

            var senders = new HashSet <Guid> {
                subtask.Responsible, subtask.CreateBy
            };

            senders.Remove(Guid.Empty);

            foreach (var sender in senders)
            {
                Subscribe(task, sender);
            }

            FactoryIndexer <SubtasksWrapper> .IndexAsync(subtask);

            return(subtask);
        }
示例#27
0
        public Milestone SaveOrUpdate(Milestone milestone, bool notifyResponsible, bool import)
        {
            if (milestone == null)
            {
                throw new ArgumentNullException("milestone");
            }
            if (milestone.Project == null)
            {
                throw new Exception("milestone.project is null");
            }
            if (milestone.Responsible.Equals(Guid.Empty))
            {
                throw new Exception("milestone.responsible is empty");
            }

            // check guest responsible
            if (ProjectSecurity.IsVisitor(milestone.Responsible))
            {
                ProjectSecurity.CreateGuestSecurityException();
            }

            milestone.LastModifiedBy = SecurityContext.CurrentAccount.ID;
            milestone.LastModifiedOn = TenantUtil.DateTimeNow();

            var isNew          = milestone.ID == default(int);//Task is new
            var oldResponsible = Guid.Empty;

            if (isNew)
            {
                if (milestone.CreateBy == default(Guid))
                {
                    milestone.CreateBy = SecurityContext.CurrentAccount.ID;
                }
                if (milestone.CreateOn == default(DateTime))
                {
                    milestone.CreateOn = TenantUtil.DateTimeNow();
                }

                ProjectSecurity.DemandCreate <Milestone>(milestone.Project);
                milestone = DaoFactory.MilestoneDao.Save(milestone);
            }
            else
            {
                var oldMilestone = DaoFactory.MilestoneDao.GetById(new[] { milestone.ID }).FirstOrDefault();

                if (oldMilestone == null)
                {
                    throw new ArgumentNullException("milestone");
                }

                oldResponsible = oldMilestone.Responsible;

                ProjectSecurity.DemandEdit(milestone);
                milestone = DaoFactory.MilestoneDao.Save(milestone);
            }


            if (!milestone.Responsible.Equals(Guid.Empty))
            {
                NotifyMilestone(milestone, notifyResponsible, isNew, oldResponsible);
            }

            FactoryIndexer <MilestonesWrapper> .IndexAsync(milestone);

            return(milestone);
        }
示例#28
0
        public File ReplaceFileVersion(File file, Stream fileStream)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }
            if (file.ID == null)
            {
                throw new ArgumentException("No file id or folder id toFolderId determine provider");
            }

            if (SetupInfo.MaxChunkedUploadSize < file.ContentLength)
            {
                throw FileSizeComment.GetFileSizeException(SetupInfo.MaxChunkedUploadSize);
            }

            if (CoreContext.Configuration.Personal && SetupInfo.IsVisibleSettings("PersonalMaxSpace"))
            {
                if (CoreContext.Configuration.PersonalMaxSpace - Global.GetUserUsedSpace(file.ID == null ? SecurityContext.CurrentAccount.ID : file.CreateBy) < file.ContentLength)
                {
                    throw FileSizeComment.GetPersonalFreeSpaceException(CoreContext.Configuration.PersonalMaxSpace);
                }
            }

            List <object> parentFoldersIds;

            lock (syncRoot)
            {
                using (var tx = dbManager.BeginTransaction())
                {
                    file.Title = Global.ReplaceInvalidCharsAndTruncate(file.Title);
                    //make lowerCase
                    file.Title = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetFileExtension(file.Title));

                    file.ModifiedBy = SecurityContext.CurrentAccount.ID;
                    file.ModifiedOn = TenantUtil.DateTimeNow();
                    if (file.CreateBy == default(Guid))
                    {
                        file.CreateBy = SecurityContext.CurrentAccount.ID;
                    }
                    if (file.CreateOn == default(DateTime))
                    {
                        file.CreateOn = TenantUtil.DateTimeNow();
                    }

                    var sql = Update("files_file")
                              .Set("version", file.Version)
                              .Set("version_group", file.VersionGroup)
                              .Set("folder_id", file.FolderID)
                              .Set("title", file.Title)
                              .Set("content_length", file.ContentLength)
                              .Set("category", (int)file.FilterType)
                              .Set("create_by", file.CreateBy.ToString())
                              .Set("create_on", TenantUtil.DateTimeToUtc(file.CreateOn))
                              .Set("modified_by", file.ModifiedBy.ToString())
                              .Set("modified_on", TenantUtil.DateTimeToUtc(file.ModifiedOn))
                              .Set("converted_type", file.ConvertedType)
                              .Set("comment", file.Comment)
                              .Set("encrypted", file.Encrypted)
                              .Set("forcesave", (int)file.Forcesave)
                              .Set("thumb", file.ThumbnailStatus)
                              .Where("id", file.ID)
                              .Where("version", file.Version);
                    dbManager.ExecuteNonQuery(sql);
                    tx.Commit();

                    file.PureTitle = file.Title;

                    parentFoldersIds = dbManager.ExecuteList(
                        new SqlQuery("files_folder_tree")
                        .Select("parent_id")
                        .Where(Exp.Eq("folder_id", file.FolderID))
                        .OrderBy("level", false)
                        ).ConvertAll(row => row[0]);

                    if (parentFoldersIds.Count > 0)
                    {
                        dbManager.ExecuteNonQuery(
                            Update("files_folder")
                            .Set("modified_on", TenantUtil.DateTimeToUtc(file.ModifiedOn))
                            .Set("modified_by", file.ModifiedBy.ToString())
                            .Where(Exp.In("id", parentFoldersIds)));
                    }
                }
            }

            if (fileStream != null)
            {
                try
                {
                    DeleteVersionStream(file);
                    SaveFileStream(file, fileStream);
                }
                catch
                {
                    if (!IsExistOnStorage(file))
                    {
                        DeleteVersion(file);
                    }
                    throw;
                }
            }

            FactoryIndexer <FilesWrapper> .IndexAsync(FilesWrapper.GetFilesWrapper(file, parentFoldersIds));

            return(GetFile(file.ID));
        }
        public RelationshipEvent CreateItem(RelationshipEvent item)
        {
            CRMSecurity.DemandCreateOrUpdate(item);

            var htmlBody = String.Empty;

            if (item.CreateOn == DateTime.MinValue)
            {
                item.CreateOn = TenantUtil.DateTimeNow();
            }
            item.CreateBy      = ASC.Core.SecurityContext.CurrentAccount.ID;
            item.LastModifedBy = ASC.Core.SecurityContext.CurrentAccount.ID;

            if (item.CategoryID == (int)HistoryCategorySystem.MailMessage)
            {
                var jsonObj   = JObject.Parse(item.Content);
                var messageId = jsonObj.Value <Int32>("message_id");

                var apiServer = new Api.ApiServer();
                var msg       = apiServer.GetApiResponse(
                    String.Format("{0}mail/messages/{1}.json?id={1}&loadImages=true&needSanitize=true", SetupInfo.WebApiBaseUrl, messageId), "GET");

                if (msg == null)
                {
                    throw new ArgumentException("Mail message cannot be found");
                }

                var    msgResponseWrapper = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(msg)));
                var    msgRequestObj      = msgResponseWrapper.Value <JObject>("response");
                string messageUrl;

                htmlBody = msgRequestObj.Value <String>("htmlBody");

                using (var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(htmlBody)))
                {
                    var filePath = String.Format("folder_{0}/message_{1}.html", (messageId / 1000 + 1) * 1000, messageId);

                    Global.GetStore().Save("mail_messages", filePath, fileStream);

                    messageUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=mailmessage&message_id={1}", PathProvider.BaseAbsolutePath, messageId).ToLower();
                }

                var msg_date_created = msgRequestObj.Value <String>("date");
                var message_id       = msgRequestObj.Value <Int32>("id");
                item.Content = JsonConvert.SerializeObject(new
                {
                    @from        = msgRequestObj.Value <String>("from"),
                    to           = msgRequestObj.Value <String>("to"),
                    cc           = msgRequestObj.Value <String>("cc"),
                    bcc          = msgRequestObj.Value <String>("bcc"),
                    subject      = msgRequestObj.Value <String>("subject"),
                    important    = msgRequestObj.Value <Boolean>("important"),
                    chain_id     = msgRequestObj.Value <String>("chainId"),
                    is_sended    = msgRequestObj.Value <Int32>("folder") != 1,
                    date_created = msg_date_created,
                    introduction = msgRequestObj.Value <String>("introduction"),
                    message_id   = message_id,
                    message_url  = messageUrl
                });

                item.CreateOn = DateTime.Parse(msg_date_created, CultureInfo.InvariantCulture);

                var sqlQueryFindMailsAlready = Query("crm_relationship_event")
                                               .SelectCount()
                                               .Where("contact_id", item.ContactID)
                                               .Where(Exp.Like("content", string.Format("\"message_id\":{0},", message_id)))
                                               .Where("entity_type", (int)item.EntityType)
                                               .Where("entity_id", item.EntityID)
                                               .Where("category_id", item.CategoryID);
                if (Db.ExecuteScalar <int>(sqlQueryFindMailsAlready) > 0)
                {
                    throw new Exception("Already exists");
                }
            }


            item.ID = Db.ExecuteScalar <int>(
                Insert("crm_relationship_event")
                .InColumnValue("id", 0)
                .InColumnValue("contact_id", item.ContactID)
                .InColumnValue("content", item.Content)
                .InColumnValue("create_on", TenantUtil.DateTimeToUtc(item.CreateOn))
                .InColumnValue("create_by", item.CreateBy)
                .InColumnValue("entity_type", (int)item.EntityType)
                .InColumnValue("entity_id", item.EntityID)
                .InColumnValue("category_id", item.CategoryID)
                .InColumnValue("last_modifed_on", DateTime.UtcNow)
                .InColumnValue("last_modifed_by", item.LastModifedBy)
                .InColumnValue("have_files", false)
                .Identity(1, 0, true));

            if (item.CreateOn.Kind == DateTimeKind.Utc)
            {
                item.CreateOn = TenantUtil.DateTimeFromUtc(item.CreateOn);
            }

            FactoryIndexer <EventsWrapper> .IndexAsync(item);

            return(item);
        }