private static string ReplaceAddLinksWithExistingLinks(string articleData, WikiArticle targetArticle, ref bool found)
        {
            var encodedDisplayName = HttpUtility.UrlEncode(targetArticle.DisplayName) ?? string.Empty;
            var regex = new Regex(string.Format(NONEXISTINGHTMLLINKFORMATPATTERN, Regex.Escape(encodedDisplayName)), RegexOptions.Multiline);

            return(ReplaceWithExistingLinks(regex, articleData, targetArticle, null, ref found));
        }
        public WikiArticleListItem GetWikiAndChildren(int wikiID)
        {
            WikiArticle         article = WikiArticles.GetWikiArticle(TSAuthentication.GetLoginUser(), wikiID);
            WikiArticleListItem parent  = new WikiArticleListItem
            {
                ID    = article.ArticleID,
                Title = article.ArticleName
            };

            WikiArticles subArticles = WikiArticles.GetWikiSubArticles(TSAuthentication.GetLoginUser(), article.ArticleID);

            if (subArticles != null)
            {
                List <WikiArticleListSubItem> children = new List <WikiArticleListSubItem>();
                foreach (WikiArticle subArticle in subArticles)
                {
                    children.Add(new WikiArticleListSubItem
                    {
                        ID    = subArticle.ArticleID,
                        Title = subArticle.ArticleName
                    });
                }
                parent.SubArticles = children.ToArray();
            }
            return(parent);
        }
Esempio n. 3
0
        public void ProcessRequest(HttpContext context)
        {
            this._context = context;
            String key = this._context.Request["key"];

            String encoding = this._context.Request["encoding"];

            if (String.IsNullOrEmpty(key))
            {
                return;
            }

            context.Response.ContentType = "application/json";
            AjaxResponse response = new AjaxResponse();

            response.Status = "OK";
            WikiArticle article = WikiArticleFactory.CreateWikiArticle(key, "zh");

            response.RawData = article.GetHtmlParagramOnlyTrimHref();//Wikipedia.filterContentFirstPara(article.GetHtmlParagramOnlyTrimHref());
            //response.RawData = "<br/><br/>Taipei City (traditional Chinese: 臺北市; simplified Chinese: 台北市; pinyin: Táiběi Shì; literally \"Northern Taiwan City\")[1] is the capital of the Republic of China (commonly known as \"Taiwan\") and the core city of the largest metropolitan area of Taiwan. Situated at the tip of the island, Taipei is located on the Danshui River, and is about 25 km southwest of Keelung, its port on the Pacific Ocean. Another coastal city, Danshui, is about 20 km northwest at the river\'s mouth on the Taiwan Strait. It lies in the two relatively narrow valleys of the Keelung (基隆河) and Xindian (新店溪) rivers, which join to form the Danshui River along the city\'s western border.[2] The city proper (Taipei City) is home to an estimated 2,606,151 people.[3] Taipei, New Taipei, and Keelung together form the Taipei metropolitan area with a population of 6,776,264.[4] However, they are administered under different local governing bodies. \"Taipei\" sometimes refers to the whole metropolitan area, while \"Taipei City\" refers to the city proper.";
            System.Text.Encoding encd = System.Text.Encoding.Default;
            if (encoding != null && encoding == "utf8")
            {
                encd = System.Text.Encoding.UTF8;
            }
            response.RawData = Citiport.Util.DataUtil.RemoveHtmlTagFromString(response.RawData.ToString());
            //response.RawData = HttpUtility.UrlEncode(Citiport.Util.DataUtil.RemoveHtmlTagFromString(response.RawData.ToString()), encd);
            context.Response.Write(response.ToString());
        }
Esempio n. 4
0
        public void JoinTest()
        {
            User testUser = new User
            {
                FirstName = "Test",
                LastName  = "User",
                Email     = "*****@*****.**"
            };

            WikiArticle testArticle = new WikiArticle
            {
                Url          = "http://test",
                ArticleDate  = DateTime.Now,
                ArticleBody  = "Test Body",
                ArticleTitle = "Test Title"
            };

            using (WediumContext db = new WediumContext(_wediumContextOptions))
            {
                var postType = db.PostType.First();

                Post testPost = new Post
                {
                    Date        = DateTime.Now,
                    Title       = "Urzababa The Great",
                    Description = "The Life of Urzababa",
                    PostTypeId  = postType.PostTypeId
                };

                Favourite testFavourite = new Favourite
                {
                    Date = DateTime.Now
                };

                db.User.Add(testUser);
                db.WikiArticle.Add(testArticle);
                db.SaveChanges();

                WikiArticle wikiArticle = db.WikiArticle.First(wa => wa.ArticleDate == testArticle.ArticleDate);
                testPost.WikiArticleId = wikiArticle.WikiArticleId;

                User user = db.User.First(u => u.Email == testUser.Email);
                testPost.UserId = user.UserId;

                db.Post.Add(testPost);
                db.SaveChanges();

                Post post = db.Post.First(p => p.Title == testPost.Title);
                testFavourite.PostId = post.PostId;
                testFavourite.UserId = user.UserId;

                db.Favourite.Add(testFavourite);
                db.SaveChanges();

                Favourite favourite = db.Favourite.First(f => f.Date == testFavourite.Date);
                Assert.AreEqual(testUser.UserId, favourite.UserId);
                Assert.AreEqual(testPost.PostId, favourite.PostId);
            }
        }
        public static string GetWikiArticle(RestCommand command, int articleID)
        {
            WikiArticle wikiArticle = WikiArticles.GetWikiArticle(command.LoginUser, articleID);

            if (wikiArticle.OrganizationID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            return(wikiArticle.GetXml("WikiArticle", true));
        }
        public WikiArticleProxy GetWiki(int wikiID)
        {
            WikiArticle article = WikiArticles.GetWikiArticle(TSAuthentication.GetLoginUser(), wikiID);

            if (article != null)
            {
                return(article.GetProxy());
            }
            return(null);
        }
Esempio n. 7
0
        public async Task Given_A_DomainUrl_Should_Successfully_Retrieve_Simple_Popular_Articles(string domainUrl)
        {
            // Arrange
            var sut = new WikiArticle(domainUrl);

            // Act
            var result = await sut.PopularArticleSimple(new PopularArticleRequestParameters());

            // Assert
            result.Should().NotBeNull();
        }
Esempio n. 8
0
        public async Task Given_A_DomainUrl_And_An_Article_Category_NewArticleResultSet_Should_Contain_Atleast_1_Item(string domainUrl, string category)
        {
            // Arrange
            var sut = new WikiArticle(domainUrl);

            // Act
            var result = await sut.PageList(category);

            // Assert
            result.Items.Should().NotBeEmpty();
        }
Esempio n. 9
0
        public async Task Given_A_DomainUrl_And_An_Article_Category_Should_Successfully_Retrieve_PageList(string domainUrl, string category)
        {
            // Arrange
            var sut = new WikiArticle(domainUrl);

            // Act
            var result = await sut.PageList(category);

            // Assert
            result.Should().NotBeNull();
        }
Esempio n. 10
0
        public async Task Given_A_DomainUrl_PopularExpandedArticleResultSet_Should_Contain_Atleast_1_Item(string domainUrl)
        {
            // Arrange
            var sut = new WikiArticle(domainUrl);

            // Act
            var result = await sut.PopularArticleDetail(new PopularArticleRequestParameters());

            // Assert
            result.Items.Should().NotBeEmpty();
        }
Esempio n. 11
0
        public async Task Given_A_DomainUrl_And_ArticleId_Should_Successfully_Retrieve_Domain_Simple_ArticleInfo(string domainUrl, int articleId)
        {
            // Arrange
            var sut = new WikiArticle(domainUrl);

            // Act
            var result = await sut.Simple(articleId);

            // Assert
            result.Should().NotBeNull();
        }
Esempio n. 12
0
        public async Task Given_A_DomainUrl_Should_Successfully_Retrieve_NewArticles(string domainUrl)
        {
            // Arrange
            var sut = new WikiArticle(domainUrl);

            // Act
            var result = await sut.NewArticles();

            // Assert
            result.Should().NotBeNull();
        }
Esempio n. 13
0
        public static void RefreshArticlesAsync(WikiArticle targetArticle, string oldName, string oldDisplayName)
        {
            if (string.IsNullOrEmpty(oldName))
            {
                throw new ArgumentNullException("oldName");
            }

            var refreshArticlesDelegate = new RefreshArticlesDelegate(RefreshArticlesAsyncInternal);

            refreshArticlesDelegate.BeginInvoke(targetArticle, WikiArticleAction.Rename, oldName, oldDisplayName, null, null);
        }
Esempio n. 14
0
        public async Task Given_A_DomainUrl_And_ArticleId_SectionList_Should_Not_Be_Empty(string domainUrl, int articleId)
        {
            // Arrange
            IWikiArticle sut = new WikiArticle(domainUrl);

            // Act
            var result = await sut.Simple(articleId);

            // Assert
            result.Sections.Should().NotBeEmpty();
        }
Esempio n. 15
0
        public async Task Given_A_DomainUrl_NewArticleResultSet_Should_Contain_Atleast_1_Item(string domainUrl)
        {
            // Arrange
            var sut = new WikiArticle(domainUrl);

            // Act
            var result = await sut.NewArticles();

            // Assert
            result.Items.Should().NotBeEmpty();
        }
Esempio n. 16
0
        public void DeleteWiki(int wikiID)
        {
            LoginUser   loggedInUser = TSAuthentication.GetLoginUser();
            WikiArticle wiki         = WikiArticles.GetWikiArticle(loggedInUser, wikiID);

            wiki.IsDeleted    = true;
            wiki.ModifiedDate = DateTime.UtcNow;
            wiki.ModifiedBy   = loggedInUser.UserID;
            wiki.Collection.Save();

            ReparentArticles(wikiID);
        }
Esempio n. 17
0
        public PostDto CreatePost(PostDto postDto, int userId)
        {
            WikiArticle wikiArticle;
            string      articleImageUrl = null;

            try
            {
                articleImageUrl = _wikiMediaApiService.GetWikiThumbnailAsync(postDto.ArticleTitle).Result;
            }
            catch (AggregateException e)
            {
                e.Handle((x) =>
                {
                    if (x is WikiArticleThumbnailNotFoundException)
                    {
                        articleImageUrl = WIKIARTICLE_DEFAULT_THUMBNAIL;

                        return(true);
                    }

                    return(false);
                });
            }

            wikiArticle = new WikiArticle()
            {
                Url             = postDto.ArticleUrl,
                ArticleDate     = _wikiMediaApiService.GetWikiLatestDateAsync(postDto.ArticleTitle).Result,
                ArticleBody     = _wikiMediaApiService.GetWikiContentAsync(postDto.ArticleTitle).Result.Query.Pages.Values.First().Extract,
                ArticleTitle    = postDto.ArticleTitle,
                ArticleImageUrl = articleImageUrl
            };

            _db.WikiArticle.Add(wikiArticle);
            _db.SaveChanges();

            PostType postType = _db.PostType.First(pt => pt.PostTypeValue == postDto.PostType);
            Post     post     = new Post()
            {
                UserId        = userId,
                Date          = DateTime.Now,
                WikiArticleId = wikiArticle.WikiArticleId,
                Title         = postDto.Title,
                Description   = postDto.Description,
                PostTypeId    = postType.PostTypeId
            };

            _db.Post.Add(post);
            _db.SaveChanges();

            return(PostMapper.ToDtoPostUrl(post));
        }
Esempio n. 18
0
        public async Task Given_A_DomainUrl_And_ArticleId_Should_Successfully_Deserialize_Article_Details_Json(string domainUrl, int articleId)
        {
            // Arrange
            var sut = new WikiArticle(domainUrl);

            // Act
            var result = await sut.Details(articleId);

            // Assert
            result.Should().NotBeNull();

            //Note: Details returns a Dictionary instead of an array as per documentation
            // http://yugioh.wikia.com/api/v1/#!/Articles/getDetails_get_1
        }
Esempio n. 19
0
        public void LogHistory(LoginUser loggedInUser, WikiArticle wiki, string comment)
        {
            WikiHistoryCollection history        = new WikiHistoryCollection(loggedInUser);
            WikiHistory           newWikiHistory = history.AddNewWikiHistory();

            newWikiHistory.ModifiedBy     = loggedInUser.UserID;
            newWikiHistory.CreatedBy      = loggedInUser.UserID;
            newWikiHistory.Version        = wiki.Version;
            newWikiHistory.Body           = wiki.Body;
            newWikiHistory.ArticleName    = wiki.ArticleName;
            newWikiHistory.OrganizationID = wiki.OrganizationID;
            newWikiHistory.ArticleID      = wiki.ArticleID;
            newWikiHistory.ModifiedDate   = DateTime.UtcNow;
            newWikiHistory.CreatedDate    = DateTime.UtcNow;
            newWikiHistory.Comment        = comment;

            newWikiHistory.Collection.Save();
        }
Esempio n. 20
0
        private static string ReplaceWithExistingLinks(Regex regex, string articleData, WikiArticle targetArticle, string oldDisplayName, ref bool found)
        {
            var index = 0;

            while (true)
            {
                var match = regex.Match(articleData, index);
                if (!match.Success)
                    break;

                //if the link title equals with the old display name, change it to the new one
                var lTitle = match.Groups["LinkTitle"].Value;
                if (string.IsNullOrEmpty(lTitle) || lTitle.CompareTo(oldDisplayName ?? string.Empty) == 0)
                    lTitle = targetArticle.DisplayName;

                var templateValue = GetExistingLinkHtml(targetArticle.Path, lTitle);

                articleData = articleData.Remove(match.Index, match.Length)
                    .Insert(match.Index, templateValue);

                found = true;

                index = match.Index + templateValue.Length;

                if (index >= articleData.Length)
                    break;
            }

            return articleData;
        }
Esempio n. 21
0
        private static string ReplaceOldLinksWithRenamedLinks(string articleData, WikiArticle targetArticle, string oldPath, string oldDisplayName, ref bool found)
        {
            var regex = new Regex(string.Format(EXISTINGHTMLLINKFORMATPATTERN, Regex.Escape(oldPath)), RegexOptions.Multiline);

            return ReplaceWithExistingLinks(regex, articleData, targetArticle, oldDisplayName, ref found);
        }
Esempio n. 22
0
        private static string ReplaceAddLinksWithExistingLinks(string articleData, WikiArticle targetArticle, ref bool found)
        {
            var encodedDisplayName = HttpUtility.UrlEncode(targetArticle.DisplayName) ?? string.Empty;
            var regex = new Regex(string.Format(NONEXISTINGHTMLLINKFORMATPATTERN, Regex.Escape(encodedDisplayName)), RegexOptions.Multiline);

            return ReplaceWithExistingLinks(regex, articleData, targetArticle, null, ref found);
        }
Esempio n. 23
0
        internal static string GetReferencedTitles(WikiArticle wikiArticle)
        {
            var articleData = wikiArticle.WikiArticleText;

            if (string.IsNullOrEmpty(articleData))
                return string.Empty;

            var referencedTitles = new StringBuilder();

            //find links that reference EXISTING content
            var index = 0;
            var regex = new Regex(EXISTINGHTMLLINKPATTERN, RegexOptions.Multiline);

            while (true)
            {
                var match = regex.Match(articleData, index);
                if (!match.Success)
                    break;

                var articlePath = match.Groups["ArticlePath"].Value;

                if (!string.IsNullOrEmpty(articlePath))
                {
                    Node targetArticle = null;

                    using (new SystemAccount())
                    {
                        if (StorageContext.Search.IsOuterEngineEnabled && StorageContext.Search.SearchEngine != InternalSearchEngine.Instance)
                            targetArticle = ContentQuery.Query(string.Format("+TypeIs:WikiArticle +Path:\"{0}\"", articlePath),
                                new QuerySettings {EnableAutofilters = false, Top = 1}).Nodes.FirstOrDefault();
                    }

                    if (targetArticle != null)
                        referencedTitles.AppendFormat("{0}{1}", targetArticle.DisplayName, REFERENCEDTITLESFIELDSEPARATOR);
                }

                index = match.Index + match.Length;

                if (index >= articleData.Length)
                    break;
            }

            //find links that reference NONEXISTING content
            index = 0;
            regex = new Regex(NONEXISTINGHTMLLINKPATTERN, RegexOptions.Multiline);

            while (true)
            {
                var match = regex.Match(articleData, index);
                if (!match.Success)
                    break;

                var wTitle = HttpUtility.UrlDecode(match.Groups["WikiTitle"].Value);

                if (!string.IsNullOrEmpty(wTitle))
                    referencedTitles.AppendFormat("{0}{1}", wTitle, REFERENCEDTITLESFIELDSEPARATOR);

                index = match.Index + match.Length;

                if (index >= articleData.Length)
                    break;
            }

            return referencedTitles.ToString();
        }
Esempio n. 24
0
        //================================================================================================ Internal methods

        private static void RefreshArticlesAsyncInternal(WikiArticle targetArticle, WikiArticleAction articleAction, string oldName, string oldDisplayName)
        {
            if (targetArticle == null || !StorageContext.Search.IsOuterEngineEnabled)
                return;

            QueryResult results;

            //background task, needs to run in admin mode
            using (new SystemAccount())
            {
                var ws = Workspace.GetWorkspaceForNode(targetArticle);
                var displayNameFilter = string.IsNullOrEmpty(oldDisplayName)
                    ? string.Format("\"{0}\"", targetArticle.DisplayName)
                    : string.Format("(\"{0}\" \"{1}\")", targetArticle.DisplayName, oldDisplayName);

                results = ContentQuery.Query(string.Format("+TypeIs:WikiArticle +ReferencedWikiTitles:{0} +InTree:\"{1}\"", displayNameFilter, ws.Path),
                        new QuerySettings {EnableAutofilters = false});

                if (results.Count == 0)
                    return;

                foreach (var article in results.Nodes.Cast<WikiArticle>())
                {
                    var articleData = article.WikiArticleText ?? string.Empty;
                    var found = false;

                    switch (articleAction)
                    {
                        case WikiArticleAction.Create:
                            //find references to NONEXISTING articles
                            articleData = ReplaceAddLinksWithExistingLinks(articleData, targetArticle, ref found);
                            break;
                        case WikiArticleAction.Delete:
                            //find references to EXISTING articles
                            articleData = ReplaceExistingLinksWithAddLinks(articleData, targetArticle.Parent, targetArticle.Path, targetArticle.DisplayName, ref found);
                            break;
                        case WikiArticleAction.Rename:
                            //find references to EXISTING articles
                            articleData = ReplaceOldLinksWithRenamedLinks(articleData, targetArticle, RepositoryPath.Combine(targetArticle.ParentPath, oldName), oldDisplayName,  ref found);
                            break;
                    }

                    if (!found)
                        continue;

                    article.WikiArticleText = articleData;

                    //TODO: this is a technical save, so set ModificationDate and 
                    //ModifiedBy fields to the original values!!!!!!!

                    article.Save(SavingMode.KeepVersion);
                }
            }
        }
Esempio n. 25
0
        public static void RefreshArticlesAsync(WikiArticle targetArticle,  string oldName, string oldDisplayName)
        {
            if (string.IsNullOrEmpty(oldName))
                throw new ArgumentNullException("oldName");

            var refreshArticlesDelegate = new RefreshArticlesDelegate(RefreshArticlesAsyncInternal);

            refreshArticlesDelegate.BeginInvoke(targetArticle, WikiArticleAction.Rename, oldName, oldDisplayName, null, null);
        }
Esempio n. 26
0
        public static void RefreshArticlesAsync(WikiArticle targetArticle, WikiArticleAction articleAction)
        {
            var refreshArticlesDelegate = new RefreshArticlesDelegate(RefreshArticlesAsyncInternal);

            refreshArticlesDelegate.BeginInvoke(targetArticle, articleAction, null, null, null, null);
        }
Esempio n. 27
0
        public static void RefreshArticlesAsync(WikiArticle targetArticle, WikiArticleAction articleAction)
        {
            var refreshArticlesDelegate = new RefreshArticlesDelegate(RefreshArticlesAsyncInternal);

            refreshArticlesDelegate.BeginInvoke(targetArticle, articleAction, null, null, null, null);
        }
Esempio n. 28
0
        // ================================================================================================ Internal methods

        private static void RefreshArticlesAsyncInternal(WikiArticle targetArticle, WikiArticleAction articleAction, string oldName, string oldDisplayName)
        {
            if (targetArticle == null || !SearchManager.ContentQueryIsAllowed)
            {
                return;
            }

            // background task, needs to run in admin mode
            using (new SystemAccount())
            {
                var ws = Workspace.GetWorkspaceForNode(targetArticle);
                var displayNameFilter = string.IsNullOrEmpty(oldDisplayName)
                    ? $"\"{targetArticle.DisplayName}\""
                    : $"(\"{targetArticle.DisplayName}\" \"{oldDisplayName}\")";

                var results = ContentQuery.Query(Compatibility.SafeQueries.WikiArticlesByReferenceTitlesAndSubtree,
                                                 new QuerySettings {
                    EnableAutofilters = FilterStatus.Disabled
                },
                                                 displayNameFilter, ws.Path);

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

                foreach (var article in results.Nodes.Cast <WikiArticle>())
                {
                    var articleData = article.WikiArticleText ?? string.Empty;
                    var found       = false;

                    switch (articleAction)
                    {
                    case WikiArticleAction.Create:
                        // find references to NONEXISTING articles
                        articleData = ReplaceAddLinksWithExistingLinks(articleData, targetArticle, ref found);
                        break;

                    case WikiArticleAction.Delete:
                        // find references to EXISTING articles
                        articleData = ReplaceExistingLinksWithAddLinks(articleData, targetArticle.Parent, targetArticle.Path, targetArticle.DisplayName, ref found);
                        break;

                    case WikiArticleAction.Rename:
                        // find references to EXISTING articles
                        articleData = ReplaceOldLinksWithRenamedLinks(articleData, targetArticle, RepositoryPath.Combine(targetArticle.ParentPath, oldName), oldDisplayName, ref found);
                        break;
                    }

                    if (!found)
                    {
                        continue;
                    }

                    article.WikiArticleText = articleData;

                    //TODO: this is a technical save, so set ModificationDate and ModifiedBy fields to the original values!!!!!!!
                    article.Save(SavingMode.KeepVersion);
                }
            }
        }
Esempio n. 29
0
        private static string ReplaceWithExistingLinks(Regex regex, string articleData, WikiArticle targetArticle, string oldDisplayName, ref bool found)
        {
            var index = 0;

            while (true)
            {
                var match = regex.Match(articleData, index);
                if (!match.Success)
                {
                    break;
                }

                // if the link title equals with the old display name, change it to the new one
                var lTitle = match.Groups["LinkTitle"].Value;
                if (string.IsNullOrEmpty(lTitle) || lTitle.CompareTo(oldDisplayName ?? string.Empty) == 0)
                {
                    lTitle = targetArticle.DisplayName;
                }

                var templateValue = GetExistingLinkHtml(targetArticle.Path, lTitle);

                articleData = articleData.Remove(match.Index, match.Length)
                              .Insert(match.Index, templateValue);

                found = true;

                index = match.Index + templateValue.Length;

                if (index >= articleData.Length)
                {
                    break;
                }
            }

            return(articleData);
        }
Esempio n. 30
0
        private static string ReplaceOldLinksWithRenamedLinks(string articleData, WikiArticle targetArticle, string oldPath, string oldDisplayName, ref bool found)
        {
            var regex = new Regex(string.Format(EXISTINGHTMLLINKFORMATPATTERN, Regex.Escape(oldPath)), RegexOptions.Multiline);

            return(ReplaceWithExistingLinks(regex, articleData, targetArticle, oldDisplayName, ref found));
        }
Esempio n. 31
0
        //================================================================================================ Internal methods

        private static void RefreshArticlesAsyncInternal(WikiArticle targetArticle, WikiArticleAction articleAction, string oldName, string oldDisplayName)
        {
            if (targetArticle == null || !StorageContext.Search.IsOuterEngineEnabled)
            {
                return;
            }

            QueryResult results;

            //background task, needs to run in admin mode
            using (new SystemAccount())
            {
                var ws = Workspace.GetWorkspaceForNode(targetArticle);
                var displayNameFilter = string.IsNullOrEmpty(oldDisplayName)
                    ? string.Format("\"{0}\"", targetArticle.DisplayName)
                    : string.Format("(\"{0}\" \"{1}\")", targetArticle.DisplayName, oldDisplayName);

                results = ContentQuery.Query(string.Format("+TypeIs:WikiArticle +ReferencedWikiTitles:{0} +InTree:\"{1}\"", displayNameFilter, ws.Path),
                                             new QuerySettings {
                    EnableAutofilters = false
                });

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

                foreach (var article in results.Nodes.Cast <WikiArticle>())
                {
                    var articleData = article.WikiArticleText ?? string.Empty;
                    var found       = false;

                    switch (articleAction)
                    {
                    case WikiArticleAction.Create:
                        //find references to NONEXISTING articles
                        articleData = ReplaceAddLinksWithExistingLinks(articleData, targetArticle, ref found);
                        break;

                    case WikiArticleAction.Delete:
                        //find references to EXISTING articles
                        articleData = ReplaceExistingLinksWithAddLinks(articleData, targetArticle.Parent, targetArticle.Path, targetArticle.DisplayName, ref found);
                        break;

                    case WikiArticleAction.Rename:
                        //find references to EXISTING articles
                        articleData = ReplaceOldLinksWithRenamedLinks(articleData, targetArticle, RepositoryPath.Combine(targetArticle.ParentPath, oldName), oldDisplayName, ref found);
                        break;
                    }

                    if (!found)
                    {
                        continue;
                    }

                    article.WikiArticleText = articleData;

                    //TODO: this is a technical save, so set ModificationDate and
                    //ModifiedBy fields to the original values!!!!!!!

                    article.Save(SavingMode.KeepVersion);
                }
            }
        }
Esempio n. 32
0
    private void LoadProperties(int organizationID)
    {
        lblProperties.Visible = true;

        Organizations organizations = new Organizations(UserSession.LoginUser);

        organizations.LoadByOrganizationID(organizationID);

        if (organizations.IsEmpty)
        {
            return;
        }
        Organization organization = organizations[0];


        Users  users       = new Users(UserSession.LoginUser);
        string primaryUser = "******";

        if (organization.PrimaryUserID != null)
        {
            users.LoadByUserID((int)organization.PrimaryUserID);
            primaryUser = users.IsEmpty ? "" : users[0].FirstLastName;
        }


        string defaultGroup = "[Unassigned]";

        if (organization.DefaultPortalGroupID != null)
        {
            Group group = (Group)Groups.GetGroup(UserSession.LoginUser, (int)organization.DefaultPortalGroupID);
            if (group != null)
            {
                defaultGroup = group.Name;
            }
        }

        lblProperties.Visible = organizations.IsEmpty;

        DataTable table = new DataTable();

        table.Columns.Add("Name");
        table.Columns.Add("Value");

        table.Rows.Add(new string[] { "Name:", organization.Name });
        table.Rows.Add(new string[] { "Description:", organization.Description });
        //table.Rows.Add(new string[] { "Portal Access:", organization.HasPortalAccess.ToString() });

        /*
         * if (UserSession.CurrentUser.HasPortalRights)
         * {
         * string portalLink = "http://portal.ts.com?OrganizationID=" + organization.OrganizationID.ToString();
         * portalLink = @"<a href=""" + portalLink + @""" target=""PortalLink"" onclick=""window.open('" + portalLink + @"', 'PortalLink')"">" + portalLink + "</a>";
         * table.Rows.Add(new string[] { "Portal Link:", portalLink });
         * table.Rows.Add(new string[] { "Default Portal Group:", defaultGroup });
         * }
         */
        table.Rows.Add(new string[] { "Organization ID:", organization.OrganizationID.ToString() });
        table.Rows.Add(new string[] { "Primary Contact:", primaryUser });


        //"Central Standard Time"

        TimeZoneInfo timeZoneInfo = null;

        try
        {
            timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(organization.TimeZoneID);
        }
        catch (Exception)
        {
            timeZoneInfo = null;
        }

        table.Rows.Add(new string[] { "Time Zone:", timeZoneInfo == null ? "Central Standard Time" : timeZoneInfo.DisplayName });

        table.Rows.Add(new string[] { "Date Format:", (new CultureInfo(organization.CultureName)).DisplayName });
        table.Rows.Add(new string[] { "Default Font Family:", organization.FontFamilyDescription });
        table.Rows.Add(new string[] { "Default Font Size:", organization.FontSizeDescription });

        table.Rows.Add(new string[] { "Business Days:", organization.BusinessDaysText == "" ? "[None Assigned]" : organization.BusinessDaysText });
        table.Rows.Add(new string[] { "Business Day Start:", organization.BusinessDayStart == null ? "[None Assigned]" : ((DateTime)organization.BusinessDayStart).ToString("t", UserSession.LoginUser.CultureInfo) });
        table.Rows.Add(new string[] { "Business Day End:", organization.BusinessDayEnd == null ? "[None Assigned]" : ((DateTime)organization.BusinessDayEnd).ToString("t", UserSession.LoginUser.CultureInfo) });

        table.Rows.Add(new string[] { "Product Required on Ticket:", organization.ProductRequired.ToString() });
        table.Rows.Add(new string[] { "Product Version Required on ticket:", organization.ProductVersionRequired.ToString() });

        table.Rows.Add(new string[] { "Only show products for the customers of a ticket:", Settings.OrganizationDB.ReadBool("ShowOnlyCustomerProducts", false).ToString() });
        table.Rows.Add(new string[] { "Auto Assign Customer with Asset On Tickets:", organization.AutoAssignCustomerWithAssetOnTickets.ToString() });
        table.Rows.Add(new string[] { "Auto Associate Customer To Ticket based on Asset Assignment:", organization.AutoAssociateCustomerToTicketBasedOnAssetAssignment.ToString() });
        table.Rows.Add(new string[] { "Require customer for new ticket:", Settings.OrganizationDB.ReadBool("RequireNewTicketCustomer", false).ToString() });
        table.Rows.Add(new string[] { "Require time spent on timed actions:", organization.TimedActionsRequired.ToString() });
        table.Rows.Add(new string[] { "Disable ticket status update emails:", Settings.OrganizationDB.ReadBool("DisableStatusNotification", false).ToString() });
        table.Rows.Add(new string[] { "Visible to customers is initially enabled for new actions:", organization.SetNewActionsVisibleToCustomers.ToString() });
        table.Rows.Add(new string[] { "Allow unauthenticated users to view attachments:", organization.AllowUnsecureAttachmentViewing.ToString() });
        table.Rows.Add(new string[] { "Allow private actions to satisfy SLA first reponse:", organization.SlaInitRespAnyAction.ToString() });
        table.Rows.Add(new string[] { "Chat ID:", organization.ChatID.ToString() });


        /*    string email = organization.SystemEmailID + "@teamsupport.com";
         *      table.Rows.Add(new string[] { "System Email:", "<a href=\"mailto:" + email + "\">" + email + "</a>" });
         *      table.Rows.Add(new string[] { "Organization Reply To Address:", organization.OrganizationReplyToAddress });
         *      table.Rows.Add(new string[] { "Require [New] keyword for emails:", organization.RequireNewKeyword.ToString() });
         *      table.Rows.Add(new string[] { "Require a known email address for emails:", organization.RequireKnownUserForNewEmail.ToString() });
         */

        //table.Rows.Add(new string[] { "Use Community:", organization.UseForums.ToString() });
        WikiArticle defArticle = organization.DefaultWikiArticleID == null ? null : WikiArticles.GetWikiArticle(UserSession.LoginUser, (int)organization.DefaultWikiArticleID);

        table.Rows.Add(new string[] { "Default Wiki Article:", defArticle == null ? "[None Assigned]" : defArticle.ArticleName });


        //table.Rows.Add(new string[] { "Only Admin Can Modify Customers:", organization.AdminOnlyCustomers.ToString() });
        table.Rows.Add(new string[] { "Only Admin Can View Reports:", organization.AdminOnlyReports.ToString() });

        SlaLevel level = organization.InternalSlaLevelID != null?SlaLevels.GetSlaLevel(UserSession.LoginUser, (int)organization.InternalSlaLevelID) : null;

        table.Rows.Add(new string[] { "Internal SLA:", level == null ? "[None Assigned]" : level.Name });

        table.Rows.Add(new string[] { "Show Group Members First in Ticket Assignment List:", organization.ShowGroupMembersFirstInTicketAssignmentList.ToString() });
        table.Rows.Add(new string[] { "Require Group Assignment On Tickets:", organization.RequireGroupAssignmentOnTickets.ToString() });
        table.Rows.Add(new string[] { "Update Ticket Children Group With Parent:", organization.UpdateTicketChildrenGroupWithParent.ToString() });
        table.Rows.Add(new string[] { "Hide Alert Dismiss for Non Admins:", organization.HideDismissNonAdmins.ToString() });
        if ((organization.ProductType == ProductType.Enterprise || organization.ProductType == ProductType.BugTracking))
        {
            table.Rows.Add(new string[] { "Use Product Lines:", organization.UseProductFamilies.ToString() });
        }

        table.Rows.Add(new string[] { "Customer Insights:", organization.IsCustomerInsightsActive.ToString() });
        table.Rows.Add(new string[] { "Two Factor Verification:", organization.TwoStepVerificationEnabled.ToString() });
        table.Rows.Add(new string[] { "How many days before user passwords expire:", organization.DaysBeforePasswordExpire.ToString() });
        table.Rows.Add(new string[] { "Do not include attachments on outbound emails:", organization.NoAttachmentsInOutboundEmail.ToString() });

        if (organization.NoAttachmentsInOutboundEmail && !string.IsNullOrEmpty(organization.NoAttachmentsInOutboundExcludeProductLine))
        {
            ProductFamilies productFamilies = new ProductFamilies(UserSession.LoginUser);

            try
            {
                productFamilies.LoadByIds(organization.NoAttachmentsInOutboundExcludeProductLine.Split(',').Select(int.Parse).ToList(), organization.OrganizationID);

                if (productFamilies.Count > 0)
                {
                    table.Rows.Add(new string[] { "Except for the following Product Lines (include attachments):", string.Join(",", productFamilies.Select(p => p.Name).ToArray()) });
                }
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(UserSession.LoginUser, ex, "AdminCompany.aspx.cs.LoadProperties");
            }
        }

        table.Rows.Add(new string[] { "Warn if contact has no email address:", organization.AlertContactNoEmail.ToString() });
        table.Rows.Add(new string[] { "Allow TeamSupport to log into your account for technical support:", (!organization.DisableSupportLogin).ToString() });
        table.Rows.Add(new string[] { "Use Watson:", organization.UseWatson.ToString() });
        // table.Rows.Add(new string[] { "Require Two Factor Authentication:", organization.RequireTwoFactor.ToString() });

        rptProperties.DataSource = table;
        rptProperties.DataBind();
    }
Esempio n. 33
0
 public void Setup()
 {
     _wikiaHttpClient = Substitute.For <IWikiaHttpClient>();
     _sut             = new WikiArticle(Url, WikiaSettings.ApiVersion, _wikiaHttpClient);
 }
Esempio n. 34
0
        internal static string GetReferencedTitles(WikiArticle wikiArticle)
        {
            var articleData = wikiArticle.WikiArticleText;

            if (string.IsNullOrEmpty(articleData))
            {
                return(string.Empty);
            }

            var referencedTitles = new StringBuilder();

            // find links that reference EXISTING content
            var index = 0;
            var regex = new Regex(EXISTINGHTMLLINKPATTERN, RegexOptions.Multiline);

            while (true)
            {
                var match = regex.Match(articleData, index);
                if (!match.Success)
                {
                    break;
                }

                var articlePath = match.Groups["ArticlePath"].Value;

                if (!string.IsNullOrEmpty(articlePath))
                {
                    Node targetArticle = null;

                    using (new SystemAccount())
                    {
                        if (SearchManager.ContentQueryIsAllowed)
                        {
                            targetArticle = ContentQuery.Query(Compatibility.SafeQueries.WikiArticlesByPath,
                                                               new QuerySettings {
                                EnableAutofilters = FilterStatus.Disabled, Top = 1
                            },
                                                               articlePath).Nodes.FirstOrDefault();
                        }
                    }

                    if (targetArticle != null)
                    {
                        referencedTitles.AppendFormat("{0}{1}", targetArticle.DisplayName, REFERENCEDTITLESFIELDSEPARATOR);
                    }
                }

                index = match.Index + match.Length;

                if (index >= articleData.Length)
                {
                    break;
                }
            }

            // find links that reference NONEXISTING content
            index = 0;
            regex = new Regex(NONEXISTINGHTMLLINKPATTERN, RegexOptions.Multiline);

            while (true)
            {
                var match = regex.Match(articleData, index);
                if (!match.Success)
                {
                    break;
                }

                var wTitle = HttpUtility.UrlDecode(match.Groups["WikiTitle"].Value);

                if (!string.IsNullOrEmpty(wTitle))
                {
                    referencedTitles.AppendFormat("{0}{1}", wTitle, REFERENCEDTITLESFIELDSEPARATOR);
                }

                index = match.Index + match.Length;

                if (index >= articleData.Length)
                {
                    break;
                }
            }

            return(referencedTitles.ToString());
        }
Esempio n. 35
0
 public Ret(string raw)
 {
     Type = WikiArticle.GetValue(raw, "type");
 }