Пример #1
0
        private MailMessage BuildMailMessage(NotifyMessage message)
        {
            var email = new MailMessage
            {
                BodyEncoding    = Encoding.UTF8,
                SubjectEncoding = Encoding.UTF8,
                From            = new MailAddress(message.From),
            };

            var recipients = message.To.Split('|');

            foreach (string address in recipients)
            {
                email.To.Add(address);
            }

            email.ReplyTo = message.ReplayTo != null ? new MailAddress(message.ReplayTo) : email.From;

            email.Subject = message.Subject.Trim(' ', '\t', '\n', '\r');

            if (message.ContentType == "html")
            {
                email.Body = HtmlUtil.GetText(message.Content);
                var html      = String.Format(HtmlForm, message.Content);
                var alternate = AlternateView.CreateAlternateViewFromString(html, Encoding.UTF8, "text/html");
                email.AlternateViews.Add(alternate);
            }
            else
            {
                email.Body = message.Content;
            }

            return(email);
        }
Пример #2
0
        public override SearchResultItem[] Search(string text)
        {
            var list        = new List <SearchResultItem>();
            var defPageHref = VirtualPathUtility.ToAbsolute(WikiManager.ViewVirtualPath);

            foreach (var page in new WikiEngine().SearchPagesByContent(text))
            {
                var pageName = page.PageName;
                if (string.IsNullOrEmpty(pageName))
                {
                    pageName = WikiResource.MainWikiCaption;
                }

                list.Add(new SearchResultItem
                {
                    Name        = pageName,
                    Description = HtmlUtil.GetText(
                        EditPage.ConvertWikiToHtml(page.PageName, page.Body, defPageHref,
                                                   WikiSection.Section.ImageHangler.UrlFormat, TenantProvider.CurrentTenantID), 120),
                    URL  = ActionHelper.GetViewPagePath(defPageHref, page.PageName),
                    Date = page.Date
                });
            }
            return(list.ToArray());
        }
Пример #3
0
 private List <Tuple <string, string> > SelectTextsForIndex(DateTime date, bool withContent)
 {
     using (var db = new DbManager(module.ConnectionStringName))
     {
         return(db.Connection
                .CreateCommand(withContent ? module.Select : ModifySelect(module.Select))
                .AddParameter("tenant", tenant.TenantId)
                .AddParameter("lastModified", date)
                .ExecuteList()
                .ConvertAll(r =>
         {
             var text = default(string);
             if (withContent)
             {
                 text = (string)r[1];
                 var html = 2 < r.Length && r[2] != null ? Convert.ToBoolean(r[2]) : false;
                 if (html && !string.IsNullOrEmpty(text))
                 {
                     text = HtmlUtil.GetText(text);
                 }
             }
             return Tuple.Create(r[0].ToString(), text);
         }));
     }
 }
Пример #4
0
        private ITagValue[] GetCategoryNotifyTags(string objectId, string pageName)
        {
            var page = GetPage(pageName);

            if (page == null)
            {
                return(null);
            }

            var user        = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
            var defPageHref = VirtualPathUtility.ToAbsolute(WikiManager.ViewVirtualPath);

            var tags = new List <ITagValue>
            {
                new TagValue(Constants.TagPageName, page.PageName),
                new TagValue(Constants.TagURL, CommonLinkUtility.GetFullAbsolutePath(ActionHelper.GetViewPagePath(defPageHref, page.PageName))),
                new TagValue(Constants.TagUserName, user.DisplayUserName()),
                new TagValue(Constants.TagUserURL, CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetUserProfile(user.ID))),
                new TagValue(Constants.TagDate, TenantUtil.DateTimeNow()),
                new TagValue(Constants.TagPostPreview, HtmlUtil.GetText(EditPage.ConvertWikiToHtml(page.PageName, page.Body, defPageHref, WikiSection.Section.ImageHangler.UrlFormat, CoreContext.TenantManager.GetCurrentTenant().TenantId), 120)),
                new TagValue(Constants.TagCatName, objectId),
                ReplyToTagProvider.Comment("wiki", pageName)
            };

            return(tags.ToArray());
        }
Пример #5
0
        public override IEnumerable <object[]> BuildReport(TaskFilter filter)
        {
            filter.FromDate = new DateTime(1970, 1, 1);
            filter.ToDate   = TenantUtil.DateTimeNow();
            filter.TaskStatuses.Add(TaskStatus.Open);

            var tasks = Global.EngineFactory.GetTaskEngine().GetByFilter(filter).FilterResult.OrderBy(r => r.Project.Title).ToList();

            var result = tasks.Select(r => new object[]
            {
                r.Project.ID, r.Project.Title,
                r.MilestoneDesc != null ? r.MilestoneDesc.ID : 0,
                r.MilestoneDesc != null ? r.MilestoneDesc.Title : "",
                r.MilestoneDesc != null ? r.MilestoneDesc.DeadLine.ToString("d"): null,
                r.MilestoneDesc != null ? (int)r.MilestoneDesc.Status : -1,
                r.ID, r.Title,
                r.Responsibles.Any() ? r.Responsibles.Select(a => a.ToString()).Aggregate((a, b) => a + "," + b) : "",
                r.Status,
                !r.Deadline.Equals(DateTime.MinValue) ? r.Deadline.ToString("d") : "",
                HtmlUtil.GetText(r.Description, 500)
            });

            result = result.Where(row => row[10] != null).ToList();

            result = AddUserInfo(result, 8);
            result = AddStatusCssClass(result);

            return(result);
        }
Пример #6
0
        private ITagValue[] GetNotifyTags(string pageName, string patternType, Comment comment)
        {
            var page = GetPage(pageName);

            if (page == null)
            {
                return(null);
            }

            var user    = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
            var defPage = VirtualPathUtility.ToAbsolute(WikiManager.ViewVirtualPath);

            var tags = new List <ITagValue>
            {
                new TagValue(Constants.TagPageName, String.IsNullOrEmpty(page.PageName) ? WikiResource.MainWikiCaption : page.PageName),
                new TagValue(Constants.TagURL, CommonLinkUtility.GetFullAbsolutePath(ActionHelper.GetViewPagePath(defPage, page.PageName))),
                new TagValue(Constants.TagUserName, user.DisplayUserName()),
                new TagValue(Constants.TagUserURL, CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetUserProfile(user.ID))),
                new TagValue(Constants.TagDate, TenantUtil.DateTimeNow()),
                new TagValue(Constants.TagPostPreview, HtmlUtil.GetText(EditPage.ConvertWikiToHtml(page.PageName, page.Body, defPage, WikiSection.Section.ImageHangler.UrlFormat, CoreContext.TenantManager.GetCurrentTenant().TenantId), 120))
            };

            if (!string.IsNullOrEmpty(patternType))
            {
                tags.Add(new TagValue(Constants.TagChangePageType, patternType));
            }
            if (comment != null)
            {
                tags.Add(new TagValue(Constants.TagCommentBody, comment.Body));
            }

            return(tags.ToArray());
        }
Пример #7
0
        private MailMessage BuildMailMessage(NotifyMessage m)
        {
            var email = new MailMessage
            {
                BodyEncoding    = Encoding.UTF8,
                SubjectEncoding = Encoding.UTF8,
                From            = MailAddressUtils.Create(m.From),
                Subject         = m.Subject,
            };

            foreach (var to in m.To.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
            {
                email.To.Add(MailAddressUtils.Create(to));
            }

            if (m.ContentType == Pattern.HTMLContentType)
            {
                email.Body = HtmlUtil.GetText(m.Content);
                email.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(GetHtmlView(m.Content), Encoding.UTF8, "text/html"));
            }
            else
            {
                email.Body = m.Content;
            }

            if (!string.IsNullOrEmpty(m.ReplyTo))
            {
                email.ReplyToList.Add(MailAddressUtils.Create(m.ReplyTo));
            }

            return(email);
        }
Пример #8
0
        public override IEnumerable <object[]> BuildReport(TaskFilter filter)
        {
            if (!filter.UserId.Equals(Guid.Empty))
            {
                filter.ParticipantId = filter.UserId;
                filter.UserId        = Guid.Empty;
            }

            var createdFrom = filter.FromDate;
            var createdTo   = filter.ToDate;

            filter.FromDate = DateTime.MinValue;
            filter.ToDate   = DateTime.MinValue;

            filter.SortBy    = "deadline";
            filter.SortOrder = true;

            using (var scope = DIHelper.Resolve())
            {
                var tasks = scope.Resolve <EngineFactory>().TaskEngine.GetByFilter(filter)
                            .FilterResult.OrderBy(r => r.Project.Title)
                            .ToList();

                filter.FromDate = createdFrom;
                filter.ToDate   = createdTo;

                if (!filter.FromDate.Equals(DateTime.MinValue) && !filter.ToDate.Equals(DateTime.MinValue))
                {
                    tasks =
                        tasks.Where(r => r.CreateOn.Date >= filter.FromDate && r.CreateOn.Date <= filter.ToDate)
                        .ToList();
                }

                if (!filter.NoResponsible)
                {
                    tasks = tasks.Where(r => r.Responsibles.Any()).ToList();
                }

                var result = tasks.Select(r => new object[]
                {
                    r.Project.ID, r.Project.Title,
                    r.MilestoneDesc != null ? r.MilestoneDesc.ID : 0,
                    r.MilestoneDesc != null ? r.MilestoneDesc.Title : "",
                    r.MilestoneDesc != null ? r.MilestoneDesc.DeadLine.ToString("d") : null,
                    r.MilestoneDesc != null ? (int)r.MilestoneDesc.Status : -1,
                    r.ID, r.Title,
                    GetResponsible(r, filter.ParticipantId),
                    r.Status,
                    !r.Deadline.Equals(DateTime.MinValue) ? r.Deadline.ToString("d") : "",
                    HtmlUtil.GetText(r.Description, 500)
                });

                result = AddUserInfo(result, 8, filter.DepartmentId);
                result = AddStatusCssClass(result);

                return(result);
            }
        }
Пример #9
0
        public void GetTextBr()
        {
            string html = "Hello";

            Assert.AreEqual("Hello", HtmlUtil.GetText(html));

            html = "Hello    anton";
            Assert.AreEqual("Hello    anton", HtmlUtil.GetText(html));

            html = "Hello<\\ br>anton";
            //Assert.AreEqual("Hello\n\ranton", HtmlUtil.GetText(html));
        }
Пример #10
0
 public override SearchResultItem[] Search(string text)
 {
     return(FeedStorageFactory.Create()
            .SearchFeeds(text)
            .ConvertAll(f => new SearchResultItem
     {
         Name = f.Caption,
         Description = HtmlUtil.GetText(f.Text, 120),
         URL = FeedUrls.GetFeedUrl(f.Id),
         Date = f.Date
     })
            .ToArray());
 }
Пример #11
0
        private NoticeSendResult SendMessage(NotifyMessage m)
        {
            //Check if we need to query stats
            RefreshQuotaIfNeeded();
            if (quota != null)
            {
                lock (locker)
                {
                    if (quota.Max24HourSend <= quota.SentLast24Hours)
                    {
                        //Quota exceeded, queue next refresh to +24 hours
                        lastRefresh = DateTime.UtcNow.AddHours(24);
                        log.WarnFormat("Quota limit reached. setting next check to: {0}", lastRefresh);
                        return NoticeSendResult.SendingImpossible;
                    }
                }
            }

            var dest = new Destination
            {
                ToAddresses = m.To.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(a => MailAddressUtils.Create(a).Address).ToList(),
            };

            var subject = new Content(MimeHeaderUtils.EncodeMime(m.Subject)) { Charset = Encoding.UTF8.WebName, };

            Body body;
            if (m.ContentType == Pattern.HTMLContentType)
            {
                body = new Body(new Content(HtmlUtil.GetText(m.Content)) { Charset = Encoding.UTF8.WebName });
                body.Html = new Content(GetHtmlView(m.Content)) { Charset = Encoding.UTF8.WebName };
            }
            else
            {
                body = new Body(new Content(m.Content) { Charset = Encoding.UTF8.WebName });
            }

            var from = MailAddressUtils.Create(m.From).ToEncodedString();
            var request = new SendEmailRequest {Source = from, Destination = dest, Message = new Message(subject, body)};
            if (!string.IsNullOrEmpty(m.ReplyTo))
            {
                request.ReplyToAddresses.Add(MailAddressUtils.Create(m.ReplyTo).Address);
            }

            ThrottleIfNeeded();

            var response = ses.SendEmail(request);
            lastSend = DateTime.UtcNow;

            return response != null ? NoticeSendResult.OK : NoticeSendResult.TryOnceAgain;
        }
Пример #12
0
        public void Hard()
        {
            string html = @"<a href=""http://mediaserver:8080/Products/Community/Modules/Blogs/ViewBlog.aspx?blogID=94fae49d-2faa-46d3-bf34-655afbc6f7f4""><font size=""+1"">Неадекватное коммерческое предложение</font></a>
<div class=""moz-text-html"" lang=""x-unicode""><hr />
По работе много &quot;листаю&quot; спама, но пришел спам который меня заинтересовал:<br />
<blockquote> План действий, способствующих достижению успеха и богатства Аудиокнига mp3 &quot;ДУМАЙ И БОГАТЕЙ&quot;<br />
<br />
&quot;Думай и богатей&quot; - эта книга получила статус непревзойденного классического учебника по достижению богатства. В каждой главе автор упоминает о секрете добывания денег, пользуясь которым тысячи людей приобрели, преумножили и продолжают ...</blockquote>... <br />
<hr />
опубликовано <a href=""http://mediaserver:8080/Products/Community/Modules/Blogs/UserPage.aspx?userid=731fa2f6-0283-41ab-b4a6-b014cc29f358"">Хурлапов Павел</a> 20 авг 2009 15:53<br />
<a href=""http://mediaserver:8080/Products/Community/Modules/Blogs/ViewBlog.aspx?blogID=94fae49d-2faa-46d3-bf34-655afbc6f7f4#comments"">прокомментировать</a></div>";

            System.Diagnostics.Trace.Write(HtmlUtil.GetText(html));
        }
        protected string GetFirstName()
        {
            var value = string.Empty;

            if (!string.IsNullOrEmpty(Request["firstname"]))
            {
                value = Request["firstname"].Trim();
            }
            if (!string.IsNullOrEmpty(Request["firstnameInput"]))
            {
                value = Request["firstnameInput"].Trim();
            }
            return(HtmlUtil.GetText(value));
        }
Пример #14
0
        public void Hard()
        {
            string html = @"<a href=""http://mediaserver:8080/Products/Community/Modules/Blogs/ViewBlog.aspx?blogID=94fae49d-2faa-46d3-bf34-655afbc6f7f4""><font size=""+1"">XXX</font></a>
<div class=""moz-text-html"" lang=""x-unicode""><hr />
A &quot;b&quot; c, d:<br />
<blockquote>mp3 &quot;s&quot;<br />
<br />
&quot;s&quot; - book...</blockquote>... <br />
<hr />
w <a href=""http://mediaserver:8080/Products/Community/Modules/Blogs/UserPage.aspx?userid=731fa2f6-0283-41ab-b4a6-b014cc29f358"">AA</a> 20 a 2009 15:53<br />
<a href=""http://mediaserver:8080/Products/Community/Modules/Blogs/ViewBlog.aspx?blogID=94fae49d-2faa-46d3-bf34-655afbc6f7f4#comments"">fg</a></div>";

            System.Diagnostics.Trace.Write(HtmlUtil.GetText(html));
        }
Пример #15
0
        public void FromFile()
        {
            var html = File.ReadAllText("tests/utils/html_test.html");//Include file!
            //var text = HtmlUtil.GetText(html);

            //var advancedFormating = HtmlUtil.GetText(html, true);
            var advancedFormating2 = HtmlUtil.GetText(html, 40);

            Assert.IsTrue(advancedFormating2.Length <= 40);

            var advancedFormating3 = HtmlUtil.GetText(html, 40, "...");

            Assert.IsTrue(advancedFormating3.Length <= 40);
            StringAssert.EndsWith(advancedFormating3, "...");

            var empty = HtmlUtil.GetText(string.Empty);

            Assert.AreEqual(string.Empty, empty);

            var invalid = HtmlUtil.GetText("This is not html <div>");

            Assert.AreEqual(invalid, "This is not html");

            var xss = HtmlUtil.GetText("<script>alert(1);</script> <style>html{color:#444}</style>This is not html <div on click='javascript:alert(1);'>");

            Assert.AreEqual(xss, "This is not html");

            //var litleText = HtmlUtil.GetText("12345678901234567890", 20, "...",true);

            var test1 = HtmlUtil.GetText(null);

            Assert.AreEqual(string.Empty, test1);

            var test2 = HtmlUtil.GetText("text with \r\n line breaks", 20);

            Assert.IsTrue(test2.Length <= 20);

            var test3 = HtmlUtil.GetText("long \r\n text \r\n with \r\n text with \r\n line breaks", 20);

            Assert.IsTrue(test3.Length <= 20);

            var test4 = HtmlUtil.GetText("text text text text text text text text!", 20);

            Assert.IsTrue(test3.Length <= 20);
            StringAssert.StartsWith(test4, "text text text");
        }
Пример #16
0
        public string Unhtml(object htmlString)
        {
            if (htmlString == null || Convert.ToString(htmlString) == String.Empty)
            {
                return("");
            }

            var html = htmlString.ToString();

            try
            {
                return(HtmlUtil.ToPlainText(html));
            }
            catch
            {
                return(HtmlUtil.GetText(html));
            }
        }
Пример #17
0
        protected String GetShortenContent(String fileContent)
        {
            if (string.IsNullOrEmpty(fileContent))
            {
                return(string.Empty);
            }

            var startIndex   = fileContent.IndexOf(SearchText);
            var endIndex     = startIndex + SearchText.Length;
            var leftFraming  = false;
            var rightFraming = false;

            if (startIndex == -1)
            {
                return(String.Empty);
            }

            startIndex -= 50;

            if (startIndex <= 0)
            {
                startIndex = 0;
            }
            else
            {
                leftFraming = true;
            }

            if (endIndex + 50 > fileContent.Length)
            {
                endIndex = fileContent.Length;
            }
            else
            {
                endIndex    += 50;
                rightFraming = true;
            }

            return(String.Concat(leftFraming ? "..." : "",
                                 HtmlUtil.GetText(fileContent.Substring(startIndex, endIndex - startIndex)),
                                 rightFraming ? "..." : ""));
        }
        public SearchResultItem[] SearchBookmarksBySearchString(string searchString)
        {
            var searchStringList = ConvertStringToArray(searchString);
            var bookmarks        = _service.SearchAllBookmarks(searchStringList);

            var searchResultItems = new List <SearchResultItem>();

            if (bookmarks == null)
            {
                return(searchResultItems.ToArray());
            }
            foreach (var b in bookmarks)
            {
                var url = VirtualPathUtility.ToAbsolute(BookmarkingRequestConstants.BookmarkingBasePath) + "/" + GenerateBookmarkInfoUrl(b.URL);
                searchResultItems.Add(new SearchResultItem()
                {
                    Name        = b.Name,
                    Description = HtmlUtil.GetText(b.Description, 120),
                    URL         = url,
                    Date        = b.Date
                });
            }
            return(searchResultItems.ToArray());
        }
        protected string RenderLastUpdates()
        {
            if (Topic.RecentPostID == 0)
            {
                return("");
            }

            var recentPostURL = _settings.LinkProvider.RecentPost(Topic.RecentPostID, Topic.ID, Topic.PostCount);

            var sb = new StringBuilder();

            var fullText = HtmlUtil.GetText(Topic.RecentPostText);
            var text     = HtmlUtil.GetText(Topic.RecentPostText, 20);

            sb.Append("<div style='margin-bottom:5px;'><a class = 'link' title=\"" + HttpUtility.HtmlEncode(fullText) + "\" href=\"" + recentPostURL + "\">" + HttpUtility.HtmlEncode(text) + "</a></div>");

            sb.Append("<div class = 'link' style='overflow: hidden; max-width: 180px;'>" + ASC.Core.Users.StudioUserInfoExtension.RenderCustomProfileLink(CoreContext.UserManager.GetUsers(Topic.RecentPostAuthorID), "describe-text", "link gray") + "</div>");
            sb.Append("<div style='margin-top:5px;'>");
            sb.Append(DateTimeService.DateTime2StringTopicStyle(Topic.RecentPostCreateDate));
            sb.Append("<a href=\"" + recentPostURL + "\"><img hspace=\"5\" align=\"absmiddle\" alt=\"&raquo;\" title=\"&raquo;\" border=\"0\" src=\"" + WebImageSupplier.GetAbsoluteWebPath("goto.png", _settings.ImageItemID) + "\"/></a>");
            sb.Append("</div>");

            return(sb.ToString());
        }
Пример #20
0
        private SearchResultItem[] ToSearchResultItem(IEnumerable <object[]> rows)
        {
            var result = new List <SearchResultItem>();

            foreach (var row in rows)
            {
                var    containerType = ((EntityType)Convert.ToInt32(row[0]));
                var    id            = row[1];
                string imageRef;
                String url;

                switch (containerType)
                {
                case EntityType.Contact:
                {
                    var contact = Global.DaoFactory.GetContactDao().GetByID(Convert.ToInt32(id));

                    if (contact == null || !CRMSecurity.CanAccessTo(contact))
                    {
                        continue;
                    }

                    url = String.Format("default.aspx?id={0}", id);

                    if (contact is Company)
                    {
                        imageRef = WebImageSupplier.GetAbsoluteWebPath("companies_widget.png",
                                                                       ProductEntryPoint.ID);
                    }
                    else
                    {
                        imageRef = WebImageSupplier.GetAbsoluteWebPath("people_widget.png",
                                                                       ProductEntryPoint.ID);
                    }

                    break;
                }

                case EntityType.Opportunity:
                {
                    var deal = Global.DaoFactory.GetDealDao().GetByID(Convert.ToInt32(id));

                    if (deal == null || !CRMSecurity.CanAccessTo(deal))
                    {
                        continue;
                    }

                    url = String.Format("deals.aspx?id={0}", id);

                    imageRef = WebImageSupplier.GetAbsoluteWebPath("deal_widget.png",
                                                                   ProductEntryPoint.ID);
                    break;
                }

                case EntityType.Case:
                {
                    var cases = Global.DaoFactory.GetCasesDao().GetByID(Convert.ToInt32(id));

                    if (cases == null || !CRMSecurity.CanAccessTo(cases))
                    {
                        continue;
                    }

                    url = String.Format("cases.aspx?id={0}", id);

                    imageRef = WebImageSupplier.GetAbsoluteWebPath("cases_widget.png",
                                                                   ProductEntryPoint.ID);

                    break;
                }

                case EntityType.Task:
                {
                    var task = Global.DaoFactory.GetTaskDao().GetByID(Convert.ToInt32(id));

                    if (task == null || !CRMSecurity.CanAccessTo(task))
                    {
                        continue;
                    }

                    url = String.Format("tasks.aspx?id={0}", id);

                    imageRef = WebImageSupplier.GetAbsoluteWebPath("tasks_widget.png",
                                                                   ProductEntryPoint.ID);
                    break;
                }

                case EntityType.Invoice:
                {
                    var invoice = Global.DaoFactory.GetInvoiceDao().GetByID(Convert.ToInt32(id));

                    if (invoice == null || !CRMSecurity.CanAccessTo(invoice))
                    {
                        continue;
                    }

                    url = String.Format("invoices.aspx?id={0}", id);

                    imageRef = WebImageSupplier.GetAbsoluteWebPath("invoices_widget.png",
                                                                   ProductEntryPoint.ID);

                    break;
                }

                default:
                    throw new ArgumentException();
                }

                result.Add(new SearchResultItem
                {
                    Name        = Convert.ToString(row[2]),
                    Description = HtmlUtil.GetText(Convert.ToString(row[3]), 120),
                    URL         = String.Concat(PathProvider.BaseAbsolutePath, url),
                    Date        = TenantUtil.DateTimeFromUtc(DateTime.Parse(Convert.ToString(row[7]))),
                    Additional  = new Dictionary <String, Object>
                    {
                        { "imageRef", imageRef },
                        { "relativeInfo", GetPath(
                              Convert.ToInt32(row[4]),
                              Convert.ToInt32(row[5]),
                              (EntityType)Convert.ToInt32(row[6])) },
                        { "typeInfo", containerType.ToLocalizedString() }
                    }
                });
            }

            return(result.ToArray());
        }
        protected string RenderRecentUpdate(Thread thread)
        {
            if (thread.RecentPostID == 0)
            {
                return("");
            }

            var sb = new StringBuilder();

            sb.Append("<div><a class = 'link' title=\"" + HttpUtility.HtmlEncode(thread.RecentTopicTitle) + "\" href=\"" + _settings.LinkProvider.PostList(thread.RecentTopicID) + "\">" + HttpUtility.HtmlEncode(HtmlUtil.GetText(thread.RecentTopicTitle, 20)) + "</a></div>");
            //sb.Append("<div style='margin-top:5px;overflow: hidden;width: 180px;'>" + CoreContext.UserManager.GetUsers(thread.RecentPosterID).RenderProfileLink(_settings.ProductID, "describe-text", "link gray") + "</div>");
            sb.Append("<div style='margin-top:5px;overflow: hidden; max-width: 180px;'>" + ASC.Core.Users.StudioUserInfoExtension.RenderCustomProfileLink(CoreContext.UserManager.GetUsers(thread.RecentPosterID), "describe-text", "link gray") + "</div>");
            sb.Append("<div style='margin-top:5px;'>");
            sb.Append("<span class='text-medium-describe'>" + DateTimeExtension.AgoSentence(thread.RecentPostCreateDate) + "</span>");
            sb.Append("<a href=\"" + _settings.LinkProvider.RecentPost(thread.RecentPostID, thread.RecentTopicID, thread.RecentTopicPostCount) + "\"><img hspace=\"3\" align=\"absmiddle\" alt=\"&raquo;\" title=\"&raquo;\" border=\"0\" src=\"" + WebImageSupplier.GetAbsoluteWebPath("goto.png", _settings.ImageItemID) + "\"/></a>");
            sb.Append("</div>");
            return(sb.ToString());
        }
Пример #22
0
        public void RunJob()
        {
            var smtpClient = GetSmtpClient();

            ASC.Core.CoreContext.TenantManager.SetCurrentTenant(_tenantID);

            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)
                {
                    using (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(
                                                     @"{0}:\n\r{1}\n\r{2}:\n\r\n\r{3}",
                                                     CRMCommonResource.MailBody,
                                                     HtmlUtil.GetText(message.Body),
                                                     CRMCommonResource.MailSubject,
                                                     HtmlUtil.GetText(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);
                                    }
                                }
                            }

                            Percentage += 100 / contactCount;

                            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();
        }
Пример #23
0
        public void SendMsgWhatsNew(DateTime scheduleDate)
        {
            var log            = ServiceProvider.GetService <IOptionsMonitor <ILog> >().Get("ASC.Notify");
            var WebItemManager = ServiceProvider.GetService <WebItemManager>();

            if (WebItemManager.GetItemsAll <IProduct>().Count == 0)
            {
                log.Info("No products. Return from function");
                return;
            }

            log.Info("Start send whats new.");

            var products = WebItemManager.GetItemsAll().ToDictionary(p => p.GetSysName());

            foreach (var tenantid in GetChangedTenants(ServiceProvider.GetService <FeedAggregateDataProvider>(), scheduleDate))
            {
                try
                {
                    using var scope = ServiceProvider.CreateScope();
                    var tenantManager  = scope.ServiceProvider.GetService <TenantManager>();
                    var paymentManager = scope.ServiceProvider.GetService <PaymentManager>();

                    var tenant = tenantManager.GetTenant(tenantid);
                    if (tenant == null ||
                        tenant.Status != TenantStatus.Active ||
                        !TimeToSendWhatsNew(TenantUtil.DateTimeFromUtc(tenant.TimeZone, scheduleDate)) ||
                        TariffState.NotPaid <= paymentManager.GetTariff(tenantid).State)
                    {
                        continue;
                    }

                    tenantManager.SetCurrentTenant(tenant);

                    var studioNotifyHelper        = scope.ServiceProvider.GetService <StudioNotifyHelper>();
                    var userManager               = scope.ServiceProvider.GetService <UserManager>();
                    var securityContext           = scope.ServiceProvider.GetService <SecurityContext>();
                    var authContext               = scope.ServiceProvider.GetService <AuthContext>();
                    var authentication            = scope.ServiceProvider.GetService <AuthManager>();
                    var tenantUtil                = scope.ServiceProvider.GetService <TenantUtil>();
                    var commonLinkUtility         = scope.ServiceProvider.GetService <CommonLinkUtility>();
                    var displayUserSettingsHelper = scope.ServiceProvider.GetService <DisplayUserSettingsHelper>();
                    var feedAggregateDataProvider = scope.ServiceProvider.GetService <FeedAggregateDataProvider>();
                    var coreSettings              = scope.ServiceProvider.GetService <CoreSettings>();
                    var client = WorkContext.NotifyContext.NotifyService.RegisterClient(studioNotifyHelper.NotifySource, scope);

                    log.InfoFormat("Start send whats new in {0} ({1}).", tenant.GetTenantDomain(coreSettings), tenantid);
                    foreach (var user in userManager.GetUsers())
                    {
                        if (!studioNotifyHelper.IsSubscribedToNotify(user, Actions.SendWhatsNew))
                        {
                            continue;
                        }

                        securityContext.AuthenticateMe(authentication.GetAccountByID(tenant.TenantId, user.ID));

                        var culture = string.IsNullOrEmpty(user.CultureName) ? tenant.GetCulture() : user.GetCulture();

                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;

                        var feeds = feedAggregateDataProvider.GetFeeds(new FeedApiFilter
                        {
                            From = scheduleDate.Date.AddDays(-1),
                            To   = scheduleDate.Date.AddSeconds(-1),
                            Max  = 100,
                        });

                        var feedMinWrappers = feeds.ConvertAll(f => f.ToFeedMin(userManager));

                        var feedMinGroupedWrappers = feedMinWrappers
                                                     .Where(f =>
                                                            (f.CreatedDate == DateTime.MaxValue || f.CreatedDate >= scheduleDate.Date.AddDays(-1)) && //'cause here may be old posts with new comments
                                                            products.ContainsKey(f.Product) &&
                                                            !f.Id.StartsWith("participant")
                                                            )
                                                     .GroupBy(f => products[f.Product]);

                        var ProjectsProductName = products["projects"]?.Name; //from ASC.Feed.Aggregator.Modules.ModulesHelper.ProjectsProductName

                        var activities = feedMinGroupedWrappers
                                         .Where(f => f.Key.Name != ProjectsProductName) //not for project product
                                         .ToDictionary(
                            g => g.Key.Name,
                            g => g.Select(f => new WhatsNewUserActivity
                        {
                            Date            = f.CreatedDate,
                            UserName        = f.Author != null && f.Author.UserInfo != null ? f.Author.UserInfo.DisplayUserName(displayUserSettingsHelper) : string.Empty,
                            UserAbsoluteURL = f.Author != null && f.Author.UserInfo != null ? commonLinkUtility.GetFullAbsolutePath(f.Author.UserInfo.GetUserProfilePageURL(commonLinkUtility)) : string.Empty,
                            Title           = HtmlUtil.GetText(f.Title, 512),
                            URL             = commonLinkUtility.GetFullAbsolutePath(f.ItemUrl),
                            BreadCrumbs     = new string[0],
                            Action          = getWhatsNewActionText(f)
                        }).ToList());


                        var projectActivities = feedMinGroupedWrappers
                                                .Where(f => f.Key.Name == ProjectsProductName) // for project product
                                                .SelectMany(f => f);

                        var projectActivitiesWithoutBreadCrumbs = projectActivities.Where(p => string.IsNullOrEmpty(p.ExtraLocation));

                        var whatsNewUserActivityGroupByPrjs = new List <WhatsNewUserActivity>();

                        foreach (var prawbc in projectActivitiesWithoutBreadCrumbs)
                        {
                            whatsNewUserActivityGroupByPrjs.Add(
                                new WhatsNewUserActivity
                            {
                                Date            = prawbc.CreatedDate,
                                UserName        = prawbc.Author != null && prawbc.Author.UserInfo != null ? prawbc.Author.UserInfo.DisplayUserName(displayUserSettingsHelper) : string.Empty,
                                UserAbsoluteURL = prawbc.Author != null && prawbc.Author.UserInfo != null ? commonLinkUtility.GetFullAbsolutePath(prawbc.Author.UserInfo.GetUserProfilePageURL(commonLinkUtility)) : string.Empty,
                                Title           = HtmlUtil.GetText(prawbc.Title, 512),
                                URL             = commonLinkUtility.GetFullAbsolutePath(prawbc.ItemUrl),
                                BreadCrumbs     = new string[0],
                                Action          = getWhatsNewActionText(prawbc)
                            });
                        }

                        var groupByPrjs = projectActivities.Where(p => !string.IsNullOrEmpty(p.ExtraLocation)).GroupBy(f => f.ExtraLocation);
                        foreach (var gr in groupByPrjs)
                        {
                            var grlist = gr.ToList();
                            for (var i = 0; i < grlist.Count(); i++)
                            {
                                var ls = grlist[i];
                                whatsNewUserActivityGroupByPrjs.Add(
                                    new WhatsNewUserActivity
                                {
                                    Date            = ls.CreatedDate,
                                    UserName        = ls.Author != null && ls.Author.UserInfo != null ? ls.Author.UserInfo.DisplayUserName(displayUserSettingsHelper) : string.Empty,
                                    UserAbsoluteURL = ls.Author != null && ls.Author.UserInfo != null ? commonLinkUtility.GetFullAbsolutePath(ls.Author.UserInfo.GetUserProfilePageURL(commonLinkUtility)) : string.Empty,
                                    Title           = HtmlUtil.GetText(ls.Title, 512),
                                    URL             = commonLinkUtility.GetFullAbsolutePath(ls.ItemUrl),
                                    BreadCrumbs     = i == 0 ? new string[1] {
                                        gr.Key
                                    } : new string[0],
                                    Action = getWhatsNewActionText(ls)
                                });
                            }
                        }

                        if (whatsNewUserActivityGroupByPrjs.Count > 0)
                        {
                            activities.Add(ProjectsProductName, whatsNewUserActivityGroupByPrjs);
                        }

                        if (activities.Count > 0)
                        {
                            log.InfoFormat("Send whats new to {0}", user.Email);
                            client.SendNoticeAsync(
                                Actions.SendWhatsNew, null, user,
                                new TagValue(Tags.Activities, activities),
                                new TagValue(Tags.Date, DateToString(scheduleDate.AddDays(-1), culture)),
                                new TagValue(CommonTags.Priority, 1)
                                );
                        }
                    }
                }
                catch (Exception error)
                {
                    log.Error(error);
                }
            }
        }
Пример #24
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);
        }
Пример #25
0
        private SearchResultItem[] GetSearchResultItems(String[] keywords)
        {
            var result = new List <SearchResultItem>();

            if (IncludeToSearch(EntityType.Task))
            {
                var sqlQuery = Query(CrmDbContext.Tasks);

                if (_findedIDs.ContainsKey(EntityType.Task))
                {
                    sqlQuery = sqlQuery.Where(x => _findedIDs[EntityType.Task].Contains(x.Id));
                }
                else
                {
                    if (keywords.Length > 0)
                    {
                        foreach (var k in keywords)
                        {
                            sqlQuery = sqlQuery.Where(x => Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Title, k + "%") ||
                                                      Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Description, k + "%"));
                        }
                    }
                }

                sqlQuery.ToList().ForEach(x =>
                {
                    if (!_crmSecurity.CanAccessTo(new Task {
                        ID = x.Id
                    }))
                    {
                        return;
                    }

                    result.Add(new SearchResultItem
                    {
                        Name        = x.Title,
                        Description = HtmlUtil.GetText(x.Description, 120),
                        URL         = _pathProvider.BaseAbsolutePath,
                        Date        = _tenantUtil.DateTimeFromUtc(x.CreateOn),
                        Additional  = new Dictionary <String, Object>
                        {
                            { "imageRef", _webImageSupplier.GetAbsoluteWebPath("tasks_widget.png", ProductEntryPoint.ID) },
                            { "relativeInfo", GetPath(
                                  x.ContactId,
                                  x.EntityId,
                                  x.EntityType) },
                            { "typeInfo", EntityType.Task.ToLocalizedString() }
                        }
                    });
                });
            }

            if (IncludeToSearch(EntityType.Opportunity))
            {
                var sqlQuery = Query(CrmDbContext.Deals);

                if (_findedIDs.ContainsKey(EntityType.Opportunity))
                {
                    sqlQuery = sqlQuery.Where(x => _findedIDs[EntityType.Opportunity].Contains(x.Id));
                }
                else
                {
                    if (keywords.Length > 0)
                    {
                        foreach (var k in keywords)
                        {
                            sqlQuery = sqlQuery.Where(x => Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Title, k + "%") ||
                                                      Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Description, k + "%"));
                        }
                    }
                }


                sqlQuery.ToList().ForEach(x =>
                {
                    if (!_crmSecurity.CanAccessTo(new Deal {
                        ID = x.Id
                    }))
                    {
                        return;
                    }

                    result.Add(new SearchResultItem
                    {
                        Name        = x.Title,
                        Description = HtmlUtil.GetText(x.Description, 120),
                        URL         = string.Concat(_pathProvider.BaseAbsolutePath, string.Format("deals.aspx?id={0}", x.Id)),
                        Date        = _tenantUtil.DateTimeFromUtc(x.CreateOn),
                        Additional  = new Dictionary <string, object>
                        {
                            { "imageRef", _webImageSupplier.GetAbsoluteWebPath("deal_widget.png", ProductEntryPoint.ID) },
                            { "relativeInfo", GetPath(
                                  x.ContactId,
                                  0,
                                  0) },
                            { "typeInfo", EntityType.Opportunity.ToLocalizedString() }
                        }
                    });
                });
            }


            if (IncludeToSearch(EntityType.Contact))
            {
                var sqlQuery = Query(CrmDbContext.Contacts);

                if (_findedIDs.ContainsKey(EntityType.Contact))
                {
                    sqlQuery = sqlQuery.Where(x => _findedIDs[EntityType.Contact].Contains(x.Id));
                }
                else
                {
                    if (keywords.Length > 0)
                    {
                        foreach (var k in keywords)
                        {
                            sqlQuery = sqlQuery.Where(x => Microsoft.EntityFrameworkCore.EF.Functions.Like(x.FirstName, k + "%") ||
                                                      Microsoft.EntityFrameworkCore.EF.Functions.Like(x.LastName, k + "%") ||
                                                      Microsoft.EntityFrameworkCore.EF.Functions.Like(x.CompanyName, k + "%") ||
                                                      Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Title, k + "%") ||
                                                      Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Notes, k + "%")
                                                      );
                        }
                    }
                }

                sqlQuery.ToList().ForEach(x =>
                {
                    if (x.IsCompany)
                    {
                        if (!_crmSecurity.CanAccessTo(new Company {
                            ID = x.Id
                        }))
                        {
                            return;
                        }
                    }
                    else
                    {
                        if (!_crmSecurity.CanAccessTo(new Person {
                            ID = x.Id
                        }))
                        {
                            return;
                        }
                    }

                    result.Add(new SearchResultItem
                    {
                        Name        = x.IsCompany ? x.CompanyName : String.Format("{0} {1}", x.FirstName, x.LastName),
                        Description = HtmlUtil.GetText(x.Notes, 120),
                        URL         = String.Concat(_pathProvider.BaseAbsolutePath, String.Format("default.aspx?id={0}", x.Id)),
                        Date        = _tenantUtil.DateTimeFromUtc(x.CreateOn),
                        Additional  = new Dictionary <String, Object>
                        {
                            { "imageRef", _webImageSupplier.GetAbsoluteWebPath(x.IsCompany ? "companies_widget.png" : "people_widget.png", ProductEntryPoint.ID) },
                            { "relativeInfo", GetPath(
                                  0,
                                  0,
                                  0) },
                            { "typeInfo", EntityType.Contact.ToLocalizedString() }
                        }
                    });
                });
            }

            if (IncludeToSearch(EntityType.Case))
            {
                var sqlQuery = Query(CrmDbContext.Cases);

                if (_findedIDs.ContainsKey(EntityType.Case))
                {
                    sqlQuery = sqlQuery.Where(x => _findedIDs[EntityType.Case].Contains(x.Id));
                }
                else
                {
                    if (keywords.Length > 0)
                    {
                        foreach (var k in keywords)
                        {
                            sqlQuery = sqlQuery.Where(x => Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Title, k + "%"));
                        }
                    }
                }

                sqlQuery.ToList().ForEach(x =>
                {
                    if (!_crmSecurity.CanAccessTo(new Cases {
                        ID = x.Id
                    }))
                    {
                        return;
                    }

                    result.Add(new SearchResultItem
                    {
                        Name        = x.Title,
                        Description = String.Empty,
                        URL         = String.Concat(_pathProvider.BaseAbsolutePath, String.Format("cases.aspx?id={0}", x.Id)),
                        Date        = _tenantUtil.DateTimeFromUtc(x.CreateOn),
                        Additional  = new Dictionary <String, Object>
                        {
                            { "imageRef", _webImageSupplier.GetAbsoluteWebPath("cases_widget.png", ProductEntryPoint.ID) },
                            { "relativeInfo", GetPath(
                                  0,
                                  0,
                                  0) },
                            { "typeInfo", EntityType.Case.ToLocalizedString() }
                        }
                    });
                });
            }


            if (IncludeToSearch(EntityType.Invoice))
            {
                var sqlQuery = Query(CrmDbContext.Invoices);

                if (_findedIDs.ContainsKey(EntityType.Invoice))
                {
                    sqlQuery = sqlQuery.Where(x => _findedIDs[EntityType.Invoice].Contains(x.Id));
                }
                else
                {
                    if (keywords.Length > 0)
                    {
                        foreach (var k in keywords)
                        {
                            sqlQuery = sqlQuery.Where(x => Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Number, k + "%") ||
                                                      Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Description, k + "%"));
                        }
                    }
                }

                sqlQuery.ToList().ForEach(x =>
                {
                    if (!_crmSecurity.CanAccessTo(new Invoice {
                        ID = x.Id
                    }))
                    {
                        return;
                    }

                    result.Add(new SearchResultItem
                    {
                        Name        = x.Number,
                        Description = String.Empty,
                        URL         = String.Concat(_pathProvider.BaseAbsolutePath, String.Format("invoices.aspx?id={0}", x.Id)),
                        Date        = _tenantUtil.DateTimeFromUtc(x.CreateOn),
                        Additional  = new Dictionary <String, Object>
                        {
                            { "imageRef", _webImageSupplier.GetAbsoluteWebPath("invoices_widget.png", ProductEntryPoint.ID) },
                            { "relativeInfo", GetPath(
                                  x.ContactId,
                                  x.EntityId,
                                  x.EntityType) },
                            { "typeInfo", EntityType.Invoice.ToLocalizedString() }
                        }
                    });
                });
            }

            return(result.ToArray());
        }
Пример #26
0
 public static string GetText(string html)
 {
     return(HtmlUtil.GetText(html));
 }
Пример #27
0
        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "tableBase");
            writer.AddAttribute("cellspacing", "0");
            writer.AddAttribute("cellpadding", "8");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tbody);

            foreach (var srGroup in Items.GetRange(0, (MaxCount < Items.Count) ? MaxCount : Items.Count))
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "search-result-item");
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "borderBase left-column gray-text");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.AddAttribute(HtmlTextWriterAttribute.Title, srGroup.Additional["Hint"].ToString());
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                writer.Write(srGroup.Additional["Hint"].ToString());
                writer.RenderEndTag();
                writer.RenderEndTag();

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "borderBase center-column");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);

                writer.AddAttribute(HtmlTextWriterAttribute.Href, srGroup.URL);
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "link bold");
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.Write(HtmlUtil.SearchTextHighlight(Text, srGroup.Name.HtmlEncode()));
                writer.RenderEndTag();

                if ((EntityType)(Enum.Parse(typeof(EntityType), (srGroup.Additional["Type"]).ToString())) == EntityType.Project)
                {
                    if (!string.IsNullOrEmpty(srGroup.Description))
                    {
                        writer.WriteBreak();
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, "describe-text");
                        writer.RenderBeginTag(HtmlTextWriterTag.Span);
                        writer.Write(CheckEmptyValue(HttpUtility.HtmlEncode(HtmlUtil.GetText(srGroup.Description, 100))));
                        writer.RenderEndTag();
                    }
                }
                else
                {
                    writer.WriteBreak();
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "describe-text");
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    writer.Write(srGroup.Additional["ContainerTitle"].ToString());
                    writer.RenderEndTag();
                    writer.Write("&nbsp;");

                    writer.AddAttribute(HtmlTextWriterAttribute.Href, srGroup.Additional["ContainerPath"].ToString());
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "link");
                    writer.RenderBeginTag(HtmlTextWriterTag.A);
                    writer.Write(srGroup.Additional["ContainerValue"].ToString().HtmlEncode());
                    writer.RenderEndTag();
                }

                writer.RenderEndTag();

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "borderBase right-column gray-text");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                if (srGroup.Date.HasValue)
                {
                    var srGroupDate = srGroup.Date.Value;
                    writer.AddAttribute(HtmlTextWriterAttribute.Title, srGroupDate.ToShortDateString());
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    writer.Write(srGroupDate.ToShortDateString());
                    writer.RenderEndTag();
                }

                writer.RenderEndTag();
                writer.RenderEndTag();
            }

            writer.RenderEndTag();
            writer.RenderEndTag();
        }
        public void SendMsgWhatsNew(DateTime scheduleDate)
        {
            if (WebItemManager.Instance.GetItemsAll <IProduct>().Count == 0)
            {
                return;
            }

            var log = LogManager.GetLogger("ASC.Notify.WhatsNew");

            log.Info("Start send whats new.");

            var products = WebItemManager.Instance.GetItemsAll().ToDictionary(p => p.GetSysName());

            foreach (var tenantid in GetChangedTenants(scheduleDate))
            {
                try
                {
                    var tenant = CoreContext.TenantManager.GetTenant(tenantid);
                    if (tenant == null ||
                        tenant.Status != TenantStatus.Active ||
                        !TimeToSendWhatsNew(TenantUtil.DateTimeFromUtc(tenant, scheduleDate)) ||
                        TariffState.NotPaid <= CoreContext.PaymentManager.GetTariff(tenantid).State)
                    {
                        continue;
                    }

                    CoreContext.TenantManager.SetCurrentTenant(tenant);

                    log.InfoFormat("Start send whats new in {0} ({1}).", tenant.TenantDomain, tenantid);
                    foreach (var user in CoreContext.UserManager.GetUsers())
                    {
                        if (!IsSubscribeToWhatsNew(user))
                        {
                            continue;
                        }

                        SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(user.ID));
                        Thread.CurrentThread.CurrentCulture   = user.GetCulture();
                        Thread.CurrentThread.CurrentUICulture = user.GetCulture();

                        var feeds = FeedAggregateDataProvider.GetFeeds(new FeedApiFilter
                        {
                            From = scheduleDate.Date.AddDays(-1),
                            To   = scheduleDate.Date.AddSeconds(-1),
                            Max  = 100,
                        });

                        var activities = feeds
                                         .Select(f => f.ToFeedMin())
                                         .SelectMany(f =>
                        {
                            if (f.Comments == null || !f.Comments.Any())
                            {
                                return(new[] { f });
                            }
                            var comment     = f.Comments.Last().ToFeedMin();
                            comment.Id      = f.Id;
                            comment.Product = f.Product;
                            comment.ItemUrl = f.ItemUrl;
                            if (f.Date < scheduleDate.Date.AddDays(-1))
                            {
                                return(new[] { comment });
                            }
                            return(new[] { f, comment });
                        })
                                         .Where(f => products.ContainsKey(f.Product) && !f.Id.StartsWith("participant"))
                                         .GroupBy(f => products[f.Product])
                                         .ToDictionary(g => g.Key.Name, g => g.Select(f => new WhatsNewUserActivity
                        {
                            Date            = TenantUtil.DateTimeFromUtc(tenant, f.Date),
                            UserName        = f.Author != null && f.Author.UserInfo != null ? f.Author.UserInfo.DisplayUserName() : string.Empty,
                            UserAbsoluteURL = f.Author != null && f.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(f.Author.UserInfo.GetUserProfilePageURL()) : string.Empty,
                            Title           = HtmlUtil.GetText(f.Title, 512),
                            URL             = CommonLinkUtility.GetFullAbsolutePath(f.ItemUrl),
                            BreadCrumbs     = GetBreadCrumbs(products, f),
                        }).ToList());

                        if (0 < activities.Count)
                        {
                            log.InfoFormat("Send whats new to {0}", user.Email);
                            client.SendNoticeAsync(
                                Constants.ActionSendWhatsNew, null, user, null,
                                new TagValue(Constants.TagActivities, activities),
                                new TagValue(Constants.TagDate, DateToString(scheduleDate.AddDays(-1), user.GetCulture())),
                                new TagValue(CommonTags.Priority, 1)
                                );
                        }
                    }
                }
                catch (Exception error)
                {
                    log.Error(error);
                }
            }
        }
Пример #29
0
        private MimeMessage BuildMailMessage(NotifyMessage m)
        {
            var mimeMessage = new MimeMessage
            {
                Subject = m.Subject
            };

            var fromAddress = MailboxAddress.Parse(ParserOptions.Default, m.From);

            mimeMessage.From.Add(fromAddress);

            foreach (var to in m.To.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
            {
                mimeMessage.To.Add(MailboxAddress.Parse(ParserOptions.Default, to));
            }

            if (m.ContentType == Pattern.HTMLContentType)
            {
                var textPart = new TextPart("plain")
                {
                    Text = HtmlUtil.GetText(m.Content),
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                var multipartAlternative = new MultipartAlternative {
                    textPart
                };

                var htmlPart = new TextPart("html")
                {
                    Text = GetHtmlView(m.Content),
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                if (m.EmbeddedAttachments != null && m.EmbeddedAttachments.Length > 0)
                {
                    var multipartRelated = new MultipartRelated
                    {
                        Root = htmlPart
                    };

                    foreach (var attachment in m.EmbeddedAttachments)
                    {
                        var mimeEntity = ConvertAttachmentToMimePart(attachment);
                        if (mimeEntity != null)
                        {
                            multipartRelated.Add(mimeEntity);
                        }
                    }

                    multipartAlternative.Add(multipartRelated);
                }
                else
                {
                    multipartAlternative.Add(htmlPart);
                }

                mimeMessage.Body = multipartAlternative;
            }
            else
            {
                mimeMessage.Body = new TextPart("plain")
                {
                    Text = m.Content,
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };
            }

            if (!string.IsNullOrEmpty(m.ReplyTo))
            {
                mimeMessage.ReplyTo.Add(MailboxAddress.Parse(ParserOptions.Default, m.ReplyTo));
            }

            mimeMessage.Headers.Add("Auto-Submitted", string.IsNullOrEmpty(m.AutoSubmitted) ? "auto-generated" : m.AutoSubmitted);

            return(mimeMessage);
        }