public static Feat Parse(WikiPage page, WikiExport export, ILog log = null)
 {
     var feat = new Feat();
     var parser = new FeatParser(feat, page, export);
     parser.Execute(log);
     return feat;
 }
	private void AdditionalResponseParams(PXRenderer renderer, WikiPage article)
	{
		if (renderer is PXRtfRenderer)
		{
			Response.AddHeader("content-disposition", "attachment;filename=\"" + article.Name + ".rtf\"");
			Response.ContentEncoding = this.GetCultureDependentEncoding();
		}
	}
示例#3
0
        public WikiPageUpdateDetails GetUpdate(WikiPage page, int fromRevision)
        {
            var versioned = ((VersionedWikiPage)page);
            var currentRevision = versioned.Revision;

            var patch = this.patcher.patch_make(
                versioned.AllRevisions[fromRevision].Text,
                currentRevision.Text
            );
            return new WikiPageUpdateDetails(
                this.patcher.patch_toText(patch),
                currentRevision
            );
        }
 public static bool TryParse(WikiPage page, WikiExport export, out Feat feat, ILog log = null)
 {
     feat = null;
     try
     {
         feat = Parse(page, export, log);
         return true;
     }
     catch (ParseException e)
     {
         log.Error("{0}: {1}", page.Title, e.Message);
         return false;
     }
 }
 public static bool TryParse(WikiPage page, out Spell spell, ILog log = null)
 {
     spell = null;
     try
     {
         spell = Parse(page, log);
         return true;
     }
     catch (ParseException e)
     {
         log.Error("{0}: {1}", page.Title, e.Message);
         return false;
     }
 }
示例#6
0
		///<summary>Converts a DataTable to a list of objects.</summary>
		public static List<WikiPage> TableToList(DataTable table){
			List<WikiPage> retVal=new List<WikiPage>();
			WikiPage wikiPage;
			for(int i=0;i<table.Rows.Count;i++) {
				wikiPage=new WikiPage();
				wikiPage.WikiPageNum  = PIn.Long  (table.Rows[i]["WikiPageNum"].ToString());
				wikiPage.UserNum      = PIn.Long  (table.Rows[i]["UserNum"].ToString());
				wikiPage.PageTitle    = PIn.String(table.Rows[i]["PageTitle"].ToString());
				wikiPage.KeyWords     = PIn.String(table.Rows[i]["KeyWords"].ToString());
				wikiPage.PageContent  = PIn.String(table.Rows[i]["PageContent"].ToString());
				wikiPage.DateTimeSaved= PIn.DateT (table.Rows[i]["DateTimeSaved"].ToString());
				retVal.Add(wikiPage);
			}
			return retVal;
		}
示例#7
0
        public WikiPageUpdateResult ApplyUpdate(WikiPage page, int revisionToPatch, string patchText)
        {
            var versioned = ((VersionedWikiPage)page);
            var patches = this.patcher.patch_fromText(patchText);

            var patchSets = (PatchSets)null;
            var revision = (WikiPageRevision)null;
            lock (versioned) {
                patchSets = LockedUpdate(versioned, revisionToPatch, patches);
                revision = versioned.Revision;
            }

            return new WikiPageUpdateResult(
                revision,
                this.patcher.patch_toText(patchSets.PatchesForAuthor),
                this.patcher.patch_toText(patchSets.PatchesForOthers)
            );
        }
示例#8
0
        public override int Execute(string[] args)
        {
            base.Execute(args);

            var name = this.Inputs[0];
            var title = string.Join(" ", this.Inputs.Skip(1));

            var page = new WikiPage { Title = title };

            using (var writer = XmlWriter.Create(Path.Combine(specificsPath, name + ".xml"), new XmlWriterSettings { Indent = true }))
            {
                Serializer.Serialize(writer, page);
            }

            File.WriteAllText(Path.Combine(overridesPath, name + ".xml"), DummyContent);

            return 0;
        }
        public void Parse(WikiPage page, string listName, List<Spell> spells)
        {
            this.page = page;
            this.listName = listName;

            this.log.Information("Début de l'analyse de la page \"{0}\"", this.page.Title);

            var wiki = this.page.Raw;

            var lines = wiki.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);

            this.currentLevel = -1;

            foreach (var line in lines)
            {
                this.ReadSpellLine(spells, line);
            }
        }
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary != null)
            {
                var tracker = new WikiPage();

                tracker.Id = dictionary.GetValue<int>("id");
                tracker.Author = dictionary.GetValueAsIdentifiableName("author");
                tracker.Comments = dictionary.GetValue<string>("comments");
                tracker.CreatedOn = dictionary.GetValue<DateTime?>("created_on");
                tracker.Text = dictionary.GetValue<string>("text");
                tracker.Title = dictionary.GetValue<string>("title");
                tracker.UpdatedOn = dictionary.GetValue<DateTime?>("updated_on");
                tracker.Version = dictionary.GetValue<int>("version");
                tracker.Attachments = dictionary.GetValueAsCollection<Attachment>("attachments");

                return tracker;
            }

            return null;
        }
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary != null)
            {
                var tracker = new WikiPage();

                tracker.Id = dictionary.GetValue<int>(RedmineKeys.ID);
                tracker.Author = dictionary.GetValueAsIdentifiableName(RedmineKeys.AUTHOR);
                tracker.Comments = dictionary.GetValue<string>(RedmineKeys.COMMENTS);
                tracker.CreatedOn = dictionary.GetValue<DateTime?>(RedmineKeys.CREATED_ON);
                tracker.Text = dictionary.GetValue<string>(RedmineKeys.TEXT);
                tracker.Title = dictionary.GetValue<string>(RedmineKeys.TITLE);
                tracker.UpdatedOn = dictionary.GetValue<DateTime?>(RedmineKeys.UPDATED_ON);
                tracker.Version = dictionary.GetValue<int>(RedmineKeys.VERSION);
                tracker.Attachments = dictionary.GetValueAsCollection<Attachment>(RedmineKeys.ATTACHMENTS);

                return tracker;
            }

            return null;
        }
        public List<Monster> ParseAll(WikiPage page, string raw)
        {
            sources = null;
            this.page = page;
            i = 0;

            var result = new List<Monster>();

            Match nextBdStart;
            while ((nextBdStart = bdStart.Match(raw, i)).Success)
            {
                Match end = bdEnd.Match(raw, nextBdStart.Index);

                if (!end.Success)
                {
                    // Impossible de détecter la balise de fin du bloc
                    throw new InvalidOperationException("Impossible de détecter le bloc de fin du bloc BD");
                }

                var rawBloc = raw.Substring(nextBdStart.Index, end.Index - nextBdStart.Index);

                try
                {
                    var monster = Parse(page, rawBloc);
                    if (monster != null)
                    {
                        result.Add(monster);
                    }
                }
                catch (Exception ex)
                {
                    throw new ParseException(string.Format("Impossible de décoder le bloc {0}", result.Count + 1), ex);
                }

                i = end.Index;
            }

            return result;
        }
        private static Spell Parse(WikiPage page, ILog log = null)
        {
            var spell = new Spell();
            spell.Name = page.Title;
            spell.Id = page.Id;

            // Ajout source wiki
            spell.Source.References.Add(References.FromFrWiki(page.Url));

            // Ajout source drp
            spell.Source.References.Add(References.FromFrDrp(page.Id));

            var wiki = page.Raw;

            if (wiki.IndexOf("'''École'''", StringComparison.Ordinal) == -1 && wiki.IndexOf("'''Ecole'''", StringComparison.Ordinal) == -1)
            {
                throw new ParseException("École de magie introuvable");
            }

            SpellParser parser = new SpellParser(spell, wiki);
            parser.Execute(log);

            return spell;
        }
示例#14
0
		///<summary>Inserts one WikiPage into the database.  Returns the new priKey.</summary>
		public static long Insert(WikiPage wikiPage){
			if(DataConnection.DBtype==DatabaseType.Oracle) {
				wikiPage.WikiPageNum=DbHelper.GetNextOracleKey("wikipage","WikiPageNum");
				int loopcount=0;
				while(loopcount<100){
					try {
						return Insert(wikiPage,true);
					}
					catch(Oracle.DataAccess.Client.OracleException ex){
						if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
							wikiPage.WikiPageNum++;
							loopcount++;
						}
						else{
							throw ex;
						}
					}
				}
				throw new ApplicationException("Insert failed.  Could not generate primary key.");
			}
			else {
				return Insert(wikiPage,false);
			}
		}
示例#15
0
 public void HtmlContentIncludesTitleAndText()
 {
     WikiPage page = new WikiPage("ThePageName", "Some random text.", 0);
     AssertContainsString(page.AsHtml(),"<h1>ThePageName</h1>");
     AssertContainsString(page.AsHtml(),"Some random text.");
 }
示例#16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MissingPageLink"/> class.
 /// </summary>
 /// <param name="page">Page that links to a missing page.</param>
 /// <param name="missingPagePath">Name of the missing page.</param>
 public MissingPageLink(WikiPage page, PagePath missingPagePath)
 {
     Page = page;
     MissingPagePath = missingPagePath.ToString();
 }
示例#17
0
 private void SetPageContent(WikiPage wikiPage)
 {
     WikiTextFormatter wf = new WikiTextFormatter();
     litContent.Text = wf.FormatPageForDisplay(wikiPage.PageContent);
     if (DateTime.Now != wikiPage.Created)
         lastMod.Text = wf.FormatPageForDisplay("<div class=\"rowfluid\"><div class=\"span12\">This wiki was last modified by " + wikiPage.ModifiedBy + " on " + wikiPage.LastModified + "</div></div>");
 }
示例#18
0
        /// <summary>
        ///     Creates the or update wiki page asynchronous.
        /// </summary>
        /// <param name="redmineManager">The redmine manager.</param>
        /// <param name="projectId">The project identifier.</param>
        /// <param name="pageName">Name of the page.</param>
        /// <param name="wikiPage">The wiki page.</param>
        /// <returns></returns>
        public static async Task <WikiPage> CreateOrUpdateWikiPageAsync(this RedmineManager redmineManager, string projectId, string pageName, WikiPage wikiPage)
        {
            var uri  = UrlHelper.GetWikiCreateOrUpdaterUrl(redmineManager, projectId, pageName);
            var data = RedmineSerializer.Serialize(wikiPage, redmineManager.MimeFormat);

            var response = await WebApiAsyncHelper.ExecuteUpload(redmineManager, uri, HttpVerbs.PUT, data, "CreateOrUpdateWikiPageAsync").ConfigureAwait(false);

            return(RedmineSerializer.Deserialize <WikiPage>(response, redmineManager.MimeFormat));
        }
示例#19
0
        public async void UpdateRequests(List <WikiJobRequest> requests)
        {
            using (var client = new WikiClient
            {
                ClientUserAgent = "WCLQuickStart/1.0 (your user name or contact information here)"
            })

            {
                try
                {
                    // You can create multiple WikiSite instances on the same WikiClient to share the state.
                    var site = _wikiAccessLogic.GetLoggedInWikiSite(_wikiLoginConfig, client, _log);

                    var page = new WikiPage(site, _wikiRequestPage);

                    _log.Information("Pulling requests from job request page for status update.");

                    // Fetch content of job request page so we can update it
                    await page.RefreshAsync(PageQueryOptions.FetchContent
                                            | PageQueryOptions.ResolveRedirects);

                    var parser   = new WikitextParser();
                    var wikiText = parser.Parse(page.Content);

                    foreach (WikiJobRequest request in requests)
                    {
                        _log.Information($"Processing request ID: {request.ID} with raw {request.RawRequest}");
                        //Find corresponding template in the page content
                        var templates        = wikiText.Lines.SelectMany(x => x.EnumDescendants().OfType <Template>());
                        var requestTemplates = templates.Where(template => template.Name.ToPlainText().Equals(_botRequestTemplate));
                        _log.Information($"{requestTemplates.ToList().Count} templates found for template {_botRequestTemplate}");
                        _log.Information($"Template id: {requestTemplates.First().Arguments.SingleOrDefault(arg => arg.Name.ToPlainText().Equals("id"))}");
                        var singletemplate = requestTemplates.First(template => template.EqualsJob(request));

                        if (singletemplate.Arguments.SingleOrDefault(arg => arg.Name.ToPlainText().Equals("status")) == null) //Status argument doesn't exist in the template
                        {
                            var templateArgument = new TemplateArgument {
                                Name = parser.Parse("status"), Value = parser.Parse(request.Status.ToString())
                            };
                            singletemplate.Arguments.Add(templateArgument);
                        }
                        else //Status argument exists
                        {
                            singletemplate.Arguments.Single(arg => arg.Name.ToPlainText().Equals("status")).Value = parser.Parse(request.Status.ToString());
                        }

                        if (singletemplate.Arguments.SingleOrDefault(arg => arg.Name.ToPlainText().Equals("id")) == null) //ID argument doesn't exist in the template
                        {
                            var templateArgument = new TemplateArgument {
                                Name = parser.Parse("id"), Value = parser.Parse(request.ID.ToString())
                            };
                            singletemplate.Arguments.Add(templateArgument);
                        }

                        request.RawRequest = singletemplate.ToString();
                        _database.UpdateRaw(request.ID, request.RawRequest); //TODO: Make batch operation
                    }

                    //Update the content of the page object and push it live
                    await UpdatePageContent(wikiText.ToString(), "Updating request ids and statuses", page);


                    // We're done here
                    await site.LogoutAsync();
                }
                catch (Exception ex)
                {
                    _log.Error(ex, "An error occurred while trying to update requests: ");
                }
            }
        }
示例#20
0
 private void LoadWikiPage(WikiPage wikiPage)
 {
     webBrowserWiki.DocumentText = WikiPages.TranslateToXhtml(wikiPage.PageContent, false);
 }
示例#21
0
 public LuaModule(WikiPage page)
 {
     Debug.Assert(page != null);
     this.page = page;
 }
示例#22
0
        private bool CheckoutTable(IList <string> processed, string usage, WikiPage page, IMvcContext context, string curline, ref bool table,
                                   ref bool ishead)
        {
            if (Regex.IsMatch(curline, @"^\|", RegexOptions.Compiled))
            {
                if (!table)
                {
                    processed.Add("<table>");
                    processed.Add("<thead>");
                    table  = true;
                    ishead = true;
                }
            }
            else
            {
                if (table)
                {
                    processed.Add("</tbody>");
                    processed.Add("</table>");
                    table = false;
                }
            }

            if (table)
            {
                var tde = ishead ? "th" : "td";
                if (!ishead)
                {
                    if (Regex.IsMatch(curline, @"^\|\{\+\}", RegexOptions.Compiled))
                    {
                        curline = Regex.Replace(curline, @"^\|\{\+\}", "|", RegexOptions.Compiled);
                        ishead  = true;
                        tde     = "th";
                    }
                }
                var items = curline.Split('|');
                var row   = "";
                if (!ishead)
                {
                    row += "</thead></tbody>";
                }
                ishead = false;

                row += "<tr>";
                for (var i = 0; i < items.Length; i++)
                {
                    if (i == 0 || i == items.Length - 1)
                    {
                        continue;                         //ignore left-right starters
                    }
                    var cell = items[i].Trim();
                    cell = ProcessInline(cell, usage, page, context);
                    cell = ProcessReferences(cell, usage, page, context).Trim();
                    var spanmatch = Regex.Match(cell, @"^\{(\d+)?(,(\d+))?\}", RegexOptions.Compiled);
                    if (spanmatch.Success)
                    {
                        cell = Regex.Replace(cell, @"^\{(\d+)?(,(\d+))?\}", "", RegexOptions.Compiled);
                        var rowspan = "1";
                        var colspan = "1";

                        if (!string.IsNullOrWhiteSpace(spanmatch.Groups[1].Value))
                        {
                            colspan = spanmatch.Groups[1].Value;
                        }
                        if (!string.IsNullOrWhiteSpace(spanmatch.Groups[3].Value))
                        {
                            rowspan = spanmatch.Groups[3].Value;
                        }
                        row += "<" + tde + " rowspan='" + rowspan + "' colspan='" + colspan + "' >" + cell + "</" + tde + ">";
                    }
                    else
                    {
                        row += "<" + tde + ">" + cell + "</" + tde + ">";
                    }
                }


                row += "</tr>";
                processed.Add(row);

                return(true);
            }
            return(false);
        }
示例#23
0
        private void ProcessHTML(string[] lines, IList <string> processed, string usage, WikiPage page, IMvcContext context)
        {
            bool codeblock   = false;
            bool nowikiblock = false;
            bool table       = false;
            bool ishead      = false;

            for (var idx = 0; idx < lines.Length; idx++)
            {
                var curline = lines[idx];
                if (string.IsNullOrWhiteSpace(curline))
                {
                    continue;
                }
                if (CheckoutCodeBlock(processed, usage, page, context, curline, ref codeblock))
                {
                    continue;
                }
                //WIKI IGNORANCE SUPPORT WITH BLOCK AND INLINE
                if (CheckoutNoWikiBlock(processed, curline, ref nowikiblock))
                {
                    continue;
                }
                if (CheckoutTable(processed, usage, page, context, curline, ref table, ref ishead))
                {
                    continue;
                }
                if (CheckoutSampleBlock(processed, curline))
                {
                    continue;
                }
                if (CheckoutPageDelimiter(processed, curline))
                {
                    continue;
                }
                var defaultProcessed = ProcessDefault(curline, usage, page, context);
                if (!string.IsNullOrWhiteSpace(defaultProcessed))
                {
                    processed.Add(defaultProcessed);
                }
            }
        }
示例#24
0
 private string ProcessReferences(string curline, string usage, WikiPage page, IMvcContext context)
 {
     return(Regex.Replace(curline, ReferenceRegex, m => ReferenceReplacer(m, usage, page, context)));
 }
示例#25
0
        private string ProcessLine(string curline, string usage, WikiPage page, object context)
        {
            if (curline.StartsWith("======"))
            {
                curline = "<h6>" + curline.Substring(6) + "</h6>";
            }
            else if (curline.StartsWith("====="))
            {
                curline = "<h5>" + curline.Substring(5) + "</h5>";
            }
            else if (curline.StartsWith("===="))
            {
                curline = "<h4>" + curline.Substring(4) + "</h4>";
            }
            else if (curline.StartsWith("==="))
            {
                curline = "<h3>" + curline.Substring(3) + "</h3>";
            }
            else if (curline.StartsWith("=="))
            {
                curline = "<h2>" + curline.Substring(2) + "</h2>";
            }
            else if (curline.StartsWith("="))
            {
                curline = "<h1>" + curline.Substring(1) + "</h1>";
            }

            //LIST SUPPORT
            else if (curline.StartsWith("%%%%%%"))
            {
                curline = "<div class='wiki-list wiki-list-6'>" + curline.Substring(6) + "</div>";
            }
            else if (curline.StartsWith("%%%%%"))
            {
                curline = "<div class='wiki-list wiki-list-5'>" + curline.Substring(5) + "</div>";
            }
            else if (curline.StartsWith("%%%%"))
            {
                curline = "<div class='wiki-list wiki-list-4'>" + curline.Substring(4) + "</div>";
            }
            else if (curline.StartsWith("%%%"))
            {
                curline = "<div class='wiki-list wiki-list-3'>" + curline.Substring(3) + "</div>";
            }
            else if (curline.StartsWith("%%"))
            {
                curline = "<div class='wiki-list wiki-list-2'>" + curline.Substring(2) + "</div>";
            }
            else if (curline.StartsWith("%"))
            {
                curline = "<div class='wiki-list wiki-list-1'>" + curline.Substring(1) + "</div>";
            }

            else if (curline.StartsWith("№№№№№№"))
            {
                curline = "<div class='wiki-list wiki-list-6 number' >" + curline.Substring(6) + "</div>";
            }
            else if (curline.StartsWith("№№№№№"))
            {
                curline = "<div class='wiki-list wiki-list-5 number'>" + curline.Substring(5) + "</div>";
            }
            else if (curline.StartsWith("№№№№"))
            {
                curline = "<div class='wiki-list wiki-list-4 number'>" + curline.Substring(4) + "</div>";
            }
            else if (curline.StartsWith("№№№"))
            {
                curline = "<div class='wiki-list wiki-list-3 number'>" + curline.Substring(3) + "</div>";
            }
            else if (curline.StartsWith("№№"))
            {
                curline = "<div class='wiki-list wiki-list-2 number'>" + curline.Substring(2) + "</div>";
            }
            else if (curline.StartsWith("№"))
            {
                curline = "<div class='wiki-list wiki-list-1 number'>" + curline.Substring(1) + "</div>";
            }


            else
            {
                curline = "<p>" + curline + "</p>";
            }
            return(curline);
        }
示例#26
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="redmineManager"></param>
 /// <param name="projectId"></param>
 /// <param name="pageName"></param>
 /// <param name="wikiPage"></param>
 /// <returns></returns>
 public static Task UpdateWikiPageAsync(this RedmineManager redmineManager, string projectId, string pageName, WikiPage wikiPage)
 {
     return(Task.Factory.StartNew(() => redmineManager.UpdateWikiPage(projectId, pageName, wikiPage), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default));
 }
示例#27
0
 public void ShowsTheLastUpdatedTime()
 {
     WikiPage page = new WikiPage("PageName", "Some text.", new DateTime(2010, 4, 25, 13, 17,0).Ticks);
     AssertContainsString(page.AsHtml(),"<i>Last Updated: 4/25/2010 1:17 PM</i>");
 }
示例#28
0
        public void Transform(PageTransformationInformation pageTransformationInformation)
        {
            #region Input validation
            if (pageTransformationInformation.SourcePage == null)
            {
                throw new ArgumentNullException("SourcePage cannot be null");
            }

            // Validate page and it's eligibility for transformation
            if (!pageTransformationInformation.SourcePage.FieldExistsAndUsed(Constants.FileRefField) || !pageTransformationInformation.SourcePage.FieldExistsAndUsed(Constants.FileLeafRefField))
            {
                throw new ArgumentException("Page is not valid due to missing FileRef or FileLeafRef value");
            }

            string pageType = pageTransformationInformation.SourcePage.PageType();

            if (pageType.Equals("ClientSidePage", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Page is a client side page...guess you don't want to transform it...");
            }

            if (pageType.Equals("AspxPage", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Page is an basic aspx page...can't transform that one, sorry!");
            }
            #endregion

            #region Page creation
            // If no targetname specified then we'll come up with one
            if (string.IsNullOrEmpty(pageTransformationInformation.TargetPageName))
            {
                pageTransformationInformation.TargetPageName = $"Migrated_{pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString()}";
            }

            // Check if page name is free to use
            bool           pageExists = false;
            ClientSidePage targetPage = null;
            try
            {
                targetPage = clientContext.Web.LoadClientSidePage(pageTransformationInformation.TargetPageName);
                pageExists = true;
            }
            catch (ArgumentException) { }

            if (pageExists)
            {
                if (!pageTransformationInformation.Overwrite)
                {
                    throw new ArgumentException($"There already exists a page with name {pageTransformationInformation.TargetPageName}.");
                }
                else
                {
                    targetPage.ClearPage();
                }
            }
            else
            {
                // Create a new client side page
                targetPage = clientContext.Web.AddClientSidePage(pageTransformationInformation.TargetPageName);
            }
            #endregion

            #region Analysis of the source page
            // Analyze the source page
            Tuple <PageLayout, List <WebPartEntity> > pageData = null;

            if (pageType.Equals("WikiPage", StringComparison.InvariantCultureIgnoreCase))
            {
                pageData = new WikiPage(pageTransformationInformation.SourcePage, pageTransformation).Analyze();
            }
            else if (pageType.Equals("WebPartPage", StringComparison.InvariantCultureIgnoreCase))
            {
                pageData = new WebPartPage(pageTransformationInformation.SourcePage, pageTransformation).Analyze(true);
            }
            #endregion

            #region Page title configuration
            // Set page title
            if (pageType.Equals("WikiPage", StringComparison.InvariantCultureIgnoreCase) && pageTransformationInformation.SourcePage.FieldExistsAndUsed(Constants.FileTitleField))
            {
                targetPage.PageTitle = pageTransformationInformation.SourcePage[Constants.FileTitleField].ToString();
            }
            else if (pageType.Equals("WebPartPage"))
            {
                var titleBarWebPart = pageData.Item2.Where(p => p.Type == WebParts.TitleBar).FirstOrDefault();
                if (titleBarWebPart != null)
                {
                    if (titleBarWebPart.Properties.ContainsKey("HeaderTitle") && !string.IsNullOrEmpty(titleBarWebPart.Properties["HeaderTitle"]))
                    {
                        targetPage.PageTitle = titleBarWebPart.Properties["HeaderTitle"];
                    }
                }
            }

            if (pageTransformationInformation.PageTitleOverride != null)
            {
                targetPage.PageTitle = pageTransformationInformation.PageTitleOverride(targetPage.PageTitle);
            }
            #endregion

            #region Page layout configuration
            // Use the default layout transformator
            ILayoutTransformator layoutTransformator = new LayoutTransformator(targetPage);

            // Do we have an override?
            if (pageTransformationInformation.LayoutTransformatorOverride != null)
            {
                layoutTransformator = pageTransformationInformation.LayoutTransformatorOverride(targetPage);
            }

            // Apply the layout to the page
            layoutTransformator.ApplyLayout(pageData.Item1);
            #endregion

            #region Content transformation
            // Use the default content transformator
            IContentTransformator contentTransformator = new ContentTransformator(targetPage, pageTransformation);

            // Do we have an override?
            if (pageTransformationInformation.ContentTransformatorOverride != null)
            {
                contentTransformator = pageTransformationInformation.ContentTransformatorOverride(targetPage, pageTransformation);
            }

            // Run the content transformator
            contentTransformator.Transform(pageData.Item2);
            #endregion

            #region Page persisting
            // Persist the client side page
            targetPage.Save(pageTransformationInformation.TargetPageName);
            targetPage.Publish();
            #endregion
        }
示例#29
0
 public void WikiLinksCanAppearAtTheStartOfTheContent()
 {
     WikiPage page = new WikiPage("PageName", "ThisLink should be a link.", 0);
     AssertContainsString(page.AsHtml(), "<a href=\"ThisLink.html\">ThisLink</a>");
 }
    private void InitHeader(Guid pageID)
    {
        PXResult <WikiPage, WikiPageLanguage> result = (PXResult <WikiPage, WikiPageLanguage>) PXSelectJoin <WikiPage,
                                                                                                             InnerJoin <WikiPageLanguage, On <WikiPageLanguage.pageID, Equal <WikiPage.pageID> > >,
                                                                                                             Where <WikiPage.pageID, Equal <Required <WikiPage.pageID> > > > .SelectWindowed(new PXGraph(), 0, 1, pageID);

        PXResult <KBResponseSummary> resultsummary = (PXResult <KBResponseSummary>) PXSelect <KBResponseSummary, Where <KBResponseSummary.pageID, Equal <Required <KBResponseSummary.pageID> > > > .SelectWindowed(new PXGraph(), 0, 1, pageID);

        if (result != null)
        {
            WikiPage          wp   = result[typeof(WikiPage)] as WikiPage;
            WikiPageLanguage  wpl  = result[typeof(WikiPageLanguage)] as WikiPageLanguage;
            KBResponseSummary kbrs = new KBResponseSummary();

            if (resultsummary != null)
            {
                kbrs = resultsummary[typeof(KBResponseSummary)] as KBResponseSummary;
            }

            PXKB.Text = wp.Name + ": " + wpl.Title;

            PXCategori.Text = "Category: ";
            bool firstcategory = false;
            foreach (PXResult <SPWikiCategoryTags, SPWikiCategory> category in PXSelectJoin <SPWikiCategoryTags,
                                                                                             InnerJoin <SPWikiCategory, On <SPWikiCategory.categoryID, Equal <SPWikiCategoryTags.categoryID> > >,
                                                                                             Where <SPWikiCategoryTags.pageID, Equal <Required <SPWikiCategoryTags.pageID> > > > .Select(new PXGraph(), pageID))
            {
                SPWikiCategory wc = category[typeof(SPWikiCategory)] as SPWikiCategory;
                if (firstcategory)
                {
                    PXCategori.Text = PXCategori.Text + ", ";
                }
                PXCategori.Text = PXCategori.Text + wc.Description;
                firstcategory   = true;
            }

            PXProduct.Text = "Applies to: ";
            bool firstproduct = false;
            foreach (PXResult <SPWikiProductTags, SPWikiProduct> category in PXSelectJoin <SPWikiProductTags,
                                                                                           InnerJoin <SPWikiProduct, On <SPWikiProduct.productID, Equal <SPWikiProductTags.productID> > >,
                                                                                           Where <SPWikiProductTags.pageID, Equal <Required <SPWikiProductTags.pageID> > > > .Select(new PXGraph(), pageID))
            {
                SPWikiProduct wc = category[typeof(SPWikiProduct)] as SPWikiProduct;
                if (firstproduct)
                {
                    PXProduct.Text = PXProduct.Text + ", ";
                }
                PXProduct.Text = PXProduct.Text + wc.Description;
                firstproduct   = true;
            }

            PXKBName.Text        = "Article: " + wp.Name + ' ';
            PXCreateDate.Text    = "Create Date: " + wp.CreatedDateTime;
            PXLastPublished.Text = "Last Modified: " + wpl.LastPublishedDateTime + ' ';
            PXViews.Text         = "Views: " + kbrs.Views.ToString() + ' ';

            PXRating.Text = "Rating: ";
            if (kbrs != null && kbrs.Markcount != null && kbrs.Markcount != 0 && kbrs.Marksummary != null && kbrs.Marksummary != 0)
            {
                int    AvRate      = (int)((int)kbrs.Marksummary / (int)kbrs.Markcount);
                Int32  Marksummary = (int)kbrs.Marksummary;
                Int32  Markcount   = (int)kbrs.Markcount;
                double dAvRate     = (double)Marksummary / (double)Markcount;
                PXdAvRate.Text = "(" + Math.Round(dAvRate, 2).ToString() + ")";
                switch (AvRate)
                {
                case 0:
                    PXImage1.ImageUrl = "main@FavoritesGray";
                    PXImage2.ImageUrl = "main@FavoritesGray";
                    PXImage3.ImageUrl = "main@FavoritesGray";
                    PXImage4.ImageUrl = "main@FavoritesGray";
                    PXImage5.ImageUrl = "main@FavoritesGray";
                    break;

                case 1:
                    PXImage1.ImageUrl = "main@Favorites";
                    PXImage2.ImageUrl = "main@FavoritesGray";
                    PXImage3.ImageUrl = "main@FavoritesGray";
                    PXImage4.ImageUrl = "main@FavoritesGray";
                    PXImage5.ImageUrl = "main@FavoritesGray";
                    break;

                case 2:
                    PXImage1.ImageUrl = "main@Favorites";
                    PXImage2.ImageUrl = "main@Favorites";
                    PXImage3.ImageUrl = "main@FavoritesGray";
                    PXImage4.ImageUrl = "main@FavoritesGray";
                    PXImage5.ImageUrl = "main@FavoritesGray";
                    break;

                case 3:
                    PXImage1.ImageUrl = "main@Favorites";
                    PXImage2.ImageUrl = "main@Favorites";
                    PXImage3.ImageUrl = "main@Favorites";
                    PXImage4.ImageUrl = "main@FavoritesGray";
                    PXImage5.ImageUrl = "main@FavoritesGray";
                    break;

                case 4:
                    PXImage1.ImageUrl = "main@Favorites";
                    PXImage2.ImageUrl = "main@Favorites";
                    PXImage3.ImageUrl = "main@Favorites";
                    PXImage4.ImageUrl = "main@Favorites";
                    PXImage5.ImageUrl = "main@FavoritesGray";
                    break;

                case 5:
                    PXImage1.ImageUrl = "main@Favorites";
                    PXImage2.ImageUrl = "main@Favorites";
                    PXImage3.ImageUrl = "main@Favorites";
                    PXImage4.ImageUrl = "main@Favorites";
                    PXImage5.ImageUrl = "main@Favorites";
                    break;

                default:
                    PXImage1.ImageUrl = "main@FavoritesGray";
                    PXImage2.ImageUrl = "main@FavoritesGray";
                    PXImage3.ImageUrl = "main@FavoritesGray";
                    PXImage4.ImageUrl = "main@FavoritesGray";
                    PXImage5.ImageUrl = "main@FavoritesGray";
                    break;
                }
            }
        }
    }
示例#31
0
		///<summary>Updates one WikiPage in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.</summary>
		public static void Update(WikiPage wikiPage,WikiPage oldWikiPage){
			string command="";
			if(wikiPage.UserNum != oldWikiPage.UserNum) {
				if(command!=""){ command+=",";}
				command+="UserNum = "+POut.Long(wikiPage.UserNum)+"";
			}
			if(wikiPage.PageTitle != oldWikiPage.PageTitle) {
				if(command!=""){ command+=",";}
				command+="PageTitle = '"+POut.String(wikiPage.PageTitle)+"'";
			}
			if(wikiPage.KeyWords != oldWikiPage.KeyWords) {
				if(command!=""){ command+=",";}
				command+="KeyWords = '"+POut.String(wikiPage.KeyWords)+"'";
			}
			if(wikiPage.PageContent != oldWikiPage.PageContent) {
				if(command!=""){ command+=",";}
				command+="PageContent = '"+POut.String(wikiPage.PageContent)+"'";
			}
			//DateTimeSaved not allowed to change
			if(command==""){
				return;
			}
			command="UPDATE wikipage SET "+command
				+" WHERE WikiPageNum = "+POut.Long(wikiPage.WikiPageNum);
			Db.NonQ(command);
		}
    protected void Rate_PageRate(object sender, EventArgs e)
    {
        Filltables();
        Guid currentwikipage = new Guid(pageid);

        PXGraph article = PXGraph.CreateInstance(typeof(KBArticleMaint));

        PXCache response        = article.Caches[typeof(KBResponse)];
        PXCache responsesummary = article.Caches[typeof(KBResponseSummary)];

        PXResult <WikiPage, WikiPageLanguage, WikiRevision> result = (PXResult <WikiPage, WikiPageLanguage, WikiRevision>) PXSelectJoin
                                                                     <WikiPage,
                                                                      InnerJoin <WikiPageLanguage, On <WikiPageLanguage.pageID, Equal <WikiPage.pageID> >,
                                                                                 InnerJoin <WikiRevision, On <WikiRevision.pageID, Equal <WikiPage.pageID> > > >,
                                                                      Where <WikiPage.pageID, Equal <Required <WikiPage.pageID> > >,
                                                                      OrderBy <Desc <WikiRevision.pageRevisionID> > > .SelectWindowed(new PXGraph(), 0, 1, currentwikipage);

        Guid userId = PXAccess.GetUserID();
        PXResult <KBResponseSummary> resultsummary = (PXResult <KBResponseSummary>) PXSelect <KBResponseSummary, Where <KBResponseSummary.pageID, Equal <Required <KBResponseSummary.pageID> > > >
                                                     .SelectWindowed(article, 0, 1, currentwikipage);

        PXResult <KBResponse> resnonse = (PXResult <KBResponse>) PXSelect <KBResponse,
                                                                           Where <KBResponse.userID, Equal <Required <KBResponse.userID> >,
                                                                                  And <KBResponse.pageID, Equal <Required <KBResponse.pageID> > > > > .SelectWindowed(article, 0, 1, userId, currentwikipage);

        if (result != null)
        {
            WikiPage         wp  = result[typeof(WikiPage)] as WikiPage;
            WikiPageLanguage wpl = result[typeof(WikiPageLanguage)] as WikiPageLanguage;

            KBResponseSummary kbrs        = responsesummary.CreateInstance() as KBResponseSummary;
            KBResponse        newresnonse = response.CreateInstance() as KBResponse;

            if (resultsummary != null)
            {
                kbrs = resultsummary[typeof(KBResponseSummary)] as KBResponseSummary;
            }

            if (resnonse != null)
            {
                newresnonse = resnonse[typeof(KBResponse)] as KBResponse;
                if (wp != null && wpl != null && newresnonse.NewMark != null)
                {
                    if (newresnonse.OldMark != 0)
                    {
                        kbrs.Marksummary = kbrs.Marksummary - newresnonse.OldMark;
                        kbrs.Marksummary = kbrs.Marksummary + newresnonse.NewMark;
                    }
                    else
                    {
                        kbrs.Markcount   = kbrs.Markcount + 1;
                        kbrs.Marksummary = kbrs.Marksummary + newresnonse.NewMark;
                    }

                    int    AvRate      = (int)((int)kbrs.Marksummary / (int)kbrs.Markcount);
                    Int32  Marksummary = (int)kbrs.Marksummary;
                    Int32  Markcount   = (int)kbrs.Markcount;
                    double dAvRate     = (double)Marksummary / (double)Markcount;
                    kbrs.AvRate = dAvRate;

                    responsesummary.Update(kbrs);
                    responsesummary.PersistUpdated(kbrs);
                    responsesummary.Clear();


                    newresnonse.PageID                 = currentwikipage;
                    newresnonse.RevisionID             = 1;
                    newresnonse.OldMark                = newresnonse.NewMark;
                    newresnonse.Date                   = PXTimeZoneInfo.Now;
                    newresnonse.Summary                = "";
                    newresnonse.CreatedByID            = wp.CreatedByID;
                    newresnonse.CreatedByScreenID      = "WP00000";
                    newresnonse.CreatedDateTime        = wp.CreatedDateTime;
                    newresnonse.LastModifiedByID       = wp.LastModifiedByID;
                    newresnonse.LastModifiedByScreenID = "WP00000";
                    newresnonse.LastModifiedDateTime   = wp.LastModifiedDateTime;

                    response.Update(newresnonse);
                    response.PersistUpdated(newresnonse);
                    response.Clear();
                }
            }

            else
            {
                if (wp != null && wpl != null && newresnonse.NewMark != null)
                {
                    newresnonse.PageID                 = currentwikipage;
                    newresnonse.RevisionID             = 1;
                    newresnonse.OldMark                = newresnonse.NewMark;
                    newresnonse.Date                   = PXTimeZoneInfo.Now;
                    newresnonse.UserID                 = userId;
                    newresnonse.Summary                = "";
                    newresnonse.CreatedByID            = wp.CreatedByID;
                    newresnonse.CreatedByScreenID      = "WP00000";
                    newresnonse.CreatedDateTime        = wp.CreatedDateTime;
                    newresnonse.LastModifiedByID       = wp.LastModifiedByID;
                    newresnonse.LastModifiedByScreenID = "WP00000";
                    newresnonse.LastModifiedDateTime   = wp.LastModifiedDateTime;

                    if (kbrs == null || kbrs.PageID == null)
                    {
                        kbrs.PageID                 = currentwikipage;
                        kbrs.CreatedByID            = wp.CreatedByID;
                        kbrs.CreatedByScreenID      = "WP00000";
                        kbrs.CreatedDateTime        = wp.CreatedDateTime;
                        kbrs.LastModifiedByID       = wp.LastModifiedByID;
                        kbrs.LastModifiedByScreenID = "WP00000";
                        kbrs.LastModifiedDateTime   = wp.LastModifiedDateTime;
                        kbrs.Markcount              = 1;
                        kbrs.Marksummary            = newresnonse.NewMark;

                        int    AvRate      = (int)((int)kbrs.Marksummary / (int)kbrs.Markcount);
                        Int32  Marksummary = (int)kbrs.Marksummary;
                        Int32  Markcount   = (int)kbrs.Markcount;
                        double dAvRate     = (double)Marksummary / (double)Markcount;
                        kbrs.AvRate = dAvRate;

                        responsesummary.Insert(kbrs);
                        responsesummary.PersistInserted(kbrs);
                        responsesummary.Clear();
                    }
                    else
                    {
                        kbrs.Markcount   = kbrs.Markcount + 1;
                        kbrs.Marksummary = kbrs.Marksummary + newresnonse.NewMark;
                        responsesummary.Update(kbrs);
                        responsesummary.PersistUpdated(kbrs);
                        responsesummary.Clear();
                    }
                    response.Insert(newresnonse);
                    response.PersistInserted(newresnonse);
                    response.Clear();
                }
            }

            string path = PXUrl.SiteUrlWithPath();
            path += path.EndsWith("/") ? "" : "/";
            var url = string.Format("{0}Wiki/{1}?pageid={2}",
                                    path, this.ResolveClientUrl("~/Wiki/ShowWiki.aspx"), pageid);
            url = url + "&rateid=" + Rate.Value;
            throw new Exception("Redirect0:" + url);
        }
    }
 public FeatParser(Feat feat, WikiPage wikiPage, WikiExport export)
 {
     this.feat = feat;
     this.wikiPage = wikiPage;
     this.export = export;
 }
    protected void ViewCount()
    {
        if (pageid != null)
        {
            Guid currentwikipage = new Guid(pageid);

            PXGraph article         = PXGraph.CreateInstance(typeof(KBArticleMaint));
            PXCache responsesummary = article.Caches[typeof(KBResponseSummary)];
            PXCache responses       = article.Caches[typeof(KBResponse)];

            PXResult <WikiPage, WikiPageLanguage, WikiRevision> result = (PXResult <WikiPage, WikiPageLanguage, WikiRevision>) PXSelectJoin <WikiPage,
                                                                                                                                             InnerJoin <WikiPageLanguage, On <WikiPageLanguage.pageID, Equal <WikiPage.pageID> >,
                                                                                                                                                        InnerJoin <WikiRevision, On <WikiRevision.pageID, Equal <WikiPage.pageID> > > >,
                                                                                                                                             Where <WikiPage.pageID, Equal <Required <WikiPage.pageID> > > >
                                                                         .SelectWindowed(new PXGraph(), 0, 1, currentwikipage);

            Guid userId = PXAccess.GetUserID();
            PXResult <KBResponseSummary> resultsummary = (PXResult <KBResponseSummary>) PXSelect <KBResponseSummary, Where <KBResponseSummary.pageID, Equal <Required <KBResponseSummary.pageID> > > >
                                                         .SelectWindowed(article, 0, 1, currentwikipage);

            PXResult <KBResponse> resnonse = (PXResult <KBResponse>) PXSelect <KBResponse,
                                                                               Where <KBResponse.userID, Equal <Required <KBResponse.userID> >,
                                                                                      And <KBResponse.pageID, Equal <Required <KBResponse.pageID> > > > >
                                             .SelectWindowed(article, 0, 1, userId, currentwikipage);

            if (result != null)
            {
                WikiPage         wp  = result[typeof(WikiPage)] as WikiPage;
                WikiPageLanguage wpl = result[typeof(WikiPageLanguage)] as WikiPageLanguage;

                KBResponseSummary kbrs        = responsesummary.CreateInstance() as KBResponseSummary;
                KBResponse        newresnonse = responses.CreateInstance() as KBResponse;

                if (resultsummary != null)
                {
                    kbrs = resultsummary[typeof(KBResponseSummary)] as KBResponseSummary;
                }

                if (resnonse != null)
                {
                    newresnonse = resnonse[typeof(KBResponse)] as KBResponse;
                }

                if (wp != null && wpl != null)
                {
                    if (kbrs == null || kbrs.PageID == null)
                    {
                        kbrs.PageID                 = currentwikipage;
                        kbrs.Views                  = 1;
                        kbrs.Markcount              = 0;
                        kbrs.Marksummary            = 0;
                        kbrs.CreatedByID            = wp.CreatedByID;
                        kbrs.CreatedByScreenID      = "WP00000";
                        kbrs.CreatedDateTime        = wp.CreatedDateTime;
                        kbrs.LastModifiedByID       = wp.LastModifiedByID;
                        kbrs.LastModifiedByScreenID = "WP00000";
                        kbrs.LastModifiedDateTime   = wp.LastModifiedDateTime;
                        kbrs.tstamp                 = wp.tstamp;
                        responsesummary.Insert(kbrs);
                        responsesummary.PersistInserted(kbrs);
                        responsesummary.Clear();
                    }
                    else
                    {
                        kbrs.Views++;
                        responsesummary.Update(kbrs);
                        responsesummary.PersistUpdated(kbrs);
                        responsesummary.Clear();
                    }

                    if (newresnonse == null || newresnonse.PageID == null)
                    {
                        newresnonse.PageID                 = currentwikipage;
                        newresnonse.RevisionID             = 1;
                        newresnonse.OldMark                = 0;
                        newresnonse.NewMark                = 0;
                        newresnonse.Date                   = PXTimeZoneInfo.Now;
                        newresnonse.UserID                 = userId;
                        newresnonse.Summary                = "";
                        newresnonse.CreatedByID            = wp.CreatedByID;
                        newresnonse.CreatedByScreenID      = "WP00000";
                        newresnonse.CreatedDateTime        = wp.CreatedDateTime;
                        newresnonse.LastModifiedByID       = wp.LastModifiedByID;
                        newresnonse.LastModifiedByScreenID = "WP00000";
                        newresnonse.LastModifiedDateTime   = wp.LastModifiedDateTime;
                        newresnonse.tstamp                 = wp.tstamp;
                        responses.Insert(newresnonse);
                        responses.PersistInserted(newresnonse);
                        responses.Clear();
                    }
                }
            }
        }
    }
示例#35
0
 public async Task UpdatePageContent(string content, string message, WikiPage page)
 {
     page.Content = content;
     await page.UpdateContentAsync(message);
 }
示例#36
0
 /// <summary>
 /// Creates the or update wiki page asynchronous.
 /// </summary>
 /// <param name="redmineManager">The redmine manager.</param>
 /// <param name="projectId">The project identifier.</param>
 /// <param name="pageName">Name of the page.</param>
 /// <param name="wikiPage">The wiki page.</param>
 /// <returns></returns>
 public static Task <WikiPage> CreateOrUpdateWikiPageAsync(this RedmineManager redmineManager, string projectId,
                                                           string pageName, WikiPage wikiPage)
 {
     return(delegate { return redmineManager.CreateOrUpdateWikiPage(projectId, pageName, wikiPage); });
 }
示例#37
0
		protected override void PerformDelete(WikiPage page)
		{
			WikiActions.Delete(page, GetCorrectGraphType);
		}
        /// <summary>
        /// Transform the page
        /// </summary>
        /// <param name="pageTransformationInformation">Information about the page to transform</param>
        /// <returns>The path to created modern page</returns>
        public string Transform(PageTransformationInformation pageTransformationInformation)
        {
            #region Input validation
            if (pageTransformationInformation.SourcePage == null)
            {
                throw new ArgumentNullException("SourcePage cannot be null");
            }

            // Validate page and it's eligibility for transformation
            if (!pageTransformationInformation.SourcePage.FieldExistsAndUsed(Constants.FileRefField) || !pageTransformationInformation.SourcePage.FieldExistsAndUsed(Constants.FileLeafRefField))
            {
                throw new ArgumentException("Page is not valid due to missing FileRef or FileLeafRef value");
            }

            string pageType = pageTransformationInformation.SourcePage.PageType();

            if (pageType.Equals("ClientSidePage", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Page already is a modern client side page...no need to transform it.");
            }

            if (pageType.Equals("AspxPage", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Page is an basic aspx page...can't currently transform that one, sorry!");
            }

            if (pageType.Equals("PublishingPage", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Page transformation for publishing pages is currently not supported.");
            }
            #endregion

            #region Telemetry
            DateTime transformationStartDateTime = DateTime.Now;
            clientContext.ClientTag = $"SPDev:PageTransformator";
            clientContext.Load(clientContext.Web, p => p.Description, p => p.Id);
            clientContext.ExecuteQuery();
            #endregion

            #region Page creation
            // If no targetname specified then we'll come up with one
            if (string.IsNullOrEmpty(pageTransformationInformation.TargetPageName))
            {
                if (string.IsNullOrEmpty(pageTransformationInformation.TargetPagePrefix))
                {
                    pageTransformationInformation.SetDefaultTargetPagePrefix();
                }

                pageTransformationInformation.TargetPageName = $"{pageTransformationInformation.TargetPagePrefix}{pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString()}";
            }

            // Check if page name is free to use
            bool           pageExists = false;
            ClientSidePage targetPage = null;
            try
            {
                targetPage = clientContext.Web.LoadClientSidePage(pageTransformationInformation.TargetPageName);
                pageExists = true;
            }
            catch (ArgumentException) { }

            if (pageExists)
            {
                if (!pageTransformationInformation.Overwrite)
                {
                    throw new ArgumentException($"There already exists a page with name {pageTransformationInformation.TargetPageName}.");
                }
                else
                {
                    targetPage.ClearPage();
                }
            }
            else
            {
                // Create a new client side page
                targetPage = clientContext.Web.AddClientSidePage(pageTransformationInformation.TargetPageName);
            }
            #endregion

            #region Home page handling
            bool replacedByOOBHomePage = false;
            // Check if the transformed page is the web's home page
            clientContext.Web.EnsureProperties(w => w.RootFolder.WelcomePage);
            var homePageUrl  = clientContext.Web.RootFolder.WelcomePage;
            var homepageName = Path.GetFileName(clientContext.Web.RootFolder.WelcomePage);
            if (homepageName.Equals(pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString(), StringComparison.InvariantCultureIgnoreCase))
            {
                targetPage.LayoutType = ClientSidePageLayoutType.Home;
                if (pageTransformationInformation.ReplaceHomePageWithDefaultHomePage)
                {
                    targetPage.KeepDefaultWebParts = true;
                    replacedByOOBHomePage          = true;
                }
            }
            #endregion

            #region Article page handling
            if (!replacedByOOBHomePage)
            {
                #region Configure header from target page
                if (pageTransformationInformation.PageHeader == null || pageTransformationInformation.PageHeader.Type == ClientSidePageHeaderType.None)
                {
                    targetPage.RemovePageHeader();
                }
                else if (pageTransformationInformation.PageHeader.Type == ClientSidePageHeaderType.Default)
                {
                    targetPage.SetDefaultPageHeader();
                }
                else if (pageTransformationInformation.PageHeader.Type == ClientSidePageHeaderType.Custom)
                {
                    targetPage.SetCustomPageHeader(pageTransformationInformation.PageHeader.ImageServerRelativeUrl, pageTransformationInformation.PageHeader.TranslateX, pageTransformationInformation.PageHeader.TranslateY);
                }
                #endregion

                #region Analysis of the source page
                // Analyze the source page
                Tuple <PageLayout, List <WebPartEntity> > pageData = null;

                if (pageType.Equals("WikiPage", StringComparison.InvariantCultureIgnoreCase))
                {
                    pageData = new WikiPage(pageTransformationInformation.SourcePage, pageTransformation).Analyze();

                    // Wiki pages can contain embedded images and videos, which is not supported by the target RTE...split wiki text blocks so the transformator can handle the images and videos as separate web parts
                    pageData = new Tuple <PageLayout, List <WebPartEntity> >(pageData.Item1, new WikiTransformatorSimple().TransformPlusSplit(pageData.Item2, pageTransformationInformation.HandleWikiImagesAndVideos));
                }
                else if (pageType.Equals("WebPartPage", StringComparison.InvariantCultureIgnoreCase))
                {
                    pageData = new WebPartPage(pageTransformationInformation.SourcePage, pageTransformation).Analyze(true);
                }
                #endregion

                #region Page title configuration
                // Set page title
                if (pageType.Equals("WikiPage", StringComparison.InvariantCultureIgnoreCase))
                {
                    SetPageTitle(pageTransformationInformation, targetPage);
                }
                else if (pageType.Equals("WebPartPage"))
                {
                    bool titleFound      = false;
                    var  titleBarWebPart = pageData.Item2.Where(p => p.Type == WebParts.TitleBar).FirstOrDefault();
                    if (titleBarWebPart != null)
                    {
                        if (titleBarWebPart.Properties.ContainsKey("HeaderTitle") && !string.IsNullOrEmpty(titleBarWebPart.Properties["HeaderTitle"]))
                        {
                            targetPage.PageTitle = titleBarWebPart.Properties["HeaderTitle"];
                            titleFound           = true;
                        }
                    }

                    if (!titleFound)
                    {
                        SetPageTitle(pageTransformationInformation, targetPage);
                    }
                }

                if (pageTransformationInformation.PageTitleOverride != null)
                {
                    targetPage.PageTitle = pageTransformationInformation.PageTitleOverride(targetPage.PageTitle);
                }
                #endregion

                #region Page layout configuration
                // Use the default layout transformator
                ILayoutTransformator layoutTransformator = new LayoutTransformator(targetPage);

                // Do we have an override?
                if (pageTransformationInformation.LayoutTransformatorOverride != null)
                {
                    layoutTransformator = pageTransformationInformation.LayoutTransformatorOverride(targetPage);
                }

                // Apply the layout to the page
                layoutTransformator.Transform(pageData.Item1);
                #endregion

                #region Page Banner creation
                if (!pageTransformationInformation.TargetPageTakesSourcePageName)
                {
                    if (pageTransformationInformation.ModernizationCenterInformation != null && pageTransformationInformation.ModernizationCenterInformation.AddPageAcceptBanner)
                    {
                        // Bump the row values for the existing web parts as we've inserted a new section
                        foreach (var section in targetPage.Sections)
                        {
                            section.Order = section.Order + 1;
                        }

                        // Add new section for banner part
                        targetPage.Sections.Insert(0, new CanvasSection(targetPage, CanvasSectionTemplate.OneColumn, 0));

                        // Bump the row values for the existing web parts as we've inserted a new section
                        foreach (var webpart in pageData.Item2)
                        {
                            webpart.Row = webpart.Row + 1;
                        }


                        var sourcePageUrl         = pageTransformationInformation.SourcePage[Constants.FileRefField].ToString();
                        var orginalSourcePageName = pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString();
                        clientContext.Web.EnsureProperty(p => p.Url);
                        Uri host = new Uri(clientContext.Web.Url);

                        string path = $"{host.Scheme}://{host.DnsSafeHost}{sourcePageUrl.Replace(pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString(), "")}";

                        // Add "fake" banner web part that then will be transformed onto the page
                        Dictionary <string, string> props = new Dictionary <string, string>(2)
                        {
                            { "SourcePage", $"{path}{orginalSourcePageName}" },
                            { "TargetPage", $"{path}{pageTransformationInformation.TargetPageName}" }
                        };

                        WebPartEntity bannerWebPart = new WebPartEntity()
                        {
                            Type       = WebParts.PageAcceptanceBanner,
                            Column     = 1,
                            Row        = 1,
                            Title      = "",
                            Order      = 0,
                            Properties = props,
                        };
                        pageData.Item2.Insert(0, bannerWebPart);
                    }
                }
                #endregion

                #region Content transformation
                // Use the default content transformator
                IContentTransformator contentTransformator = new ContentTransformator(targetPage, pageTransformation);

                // Do we have an override?
                if (pageTransformationInformation.ContentTransformatorOverride != null)
                {
                    contentTransformator = pageTransformationInformation.ContentTransformatorOverride(targetPage, pageTransformation);
                }

                // Run the content transformator
                contentTransformator.Transform(pageData.Item2);
                #endregion
            }
            #endregion

            #region Page persisting + permissions
            #region Save the page
            // Persist the client side page
            targetPage.Save(pageTransformationInformation.TargetPageName);

            // Tag the file with a page modernization version stamp
            try
            {
                string path           = pageTransformationInformation.SourcePage[Constants.FileRefField].ToString().Replace(pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString(), "");
                var    targetPageUrl  = $"{path}{pageTransformationInformation.TargetPageName}";
                var    targetPageFile = this.clientContext.Web.GetFileByServerRelativeUrl(targetPageUrl);
                this.clientContext.Load(targetPageFile, p => p.Properties);
                this.clientContext.ExecuteQueryRetry();
                targetPageFile.Properties["sharepointpnp_pagemodernization"] = this.version;
                targetPageFile.Update();
                this.clientContext.ExecuteQueryRetry();
            }
            catch (Exception ex)
            {
                // Eat exceptions as this is not critical for the generated page
            }

            // finally publish the created/updated page
            targetPage.Publish();
            #endregion

            #region Permission handling
            if (pageTransformationInformation.KeepPageSpecificPermissions)
            {
                pageTransformationInformation.SourcePage.EnsureProperty(p => p.HasUniqueRoleAssignments);
                if (pageTransformationInformation.SourcePage.HasUniqueRoleAssignments)
                {
                    // Copy the unique permissions from source to target
                    // Get the unique permissions
                    this.clientContext.Load(pageTransformationInformation.SourcePage, a => a.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName,
                                                                                                                     roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name, roleDef => roleDef.Description)));
                    this.clientContext.ExecuteQueryRetry();

                    // Get target page information
                    this.clientContext.Load(targetPage.PageListItem, p => p.HasUniqueRoleAssignments, a => a.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName,
                                                                                                                                     roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name, roleDef => roleDef.Description)));
                    this.clientContext.ExecuteQueryRetry();

                    // Break permission inheritance on the target page if not done yet
                    if (!targetPage.PageListItem.HasUniqueRoleAssignments)
                    {
                        targetPage.PageListItem.BreakRoleInheritance(false, false);
                        this.clientContext.ExecuteQueryRetry();
                    }

                    // Apply new permissions
                    foreach (var roleAssignment in pageTransformationInformation.SourcePage.RoleAssignments)
                    {
                        var principal = this.clientContext.Web.SiteUsers.GetByLoginName(roleAssignment.Member.LoginName);
                        if (principal != null)
                        {
                            var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(this.clientContext);
                            foreach (var roleDef in roleAssignment.RoleDefinitionBindings)
                            {
                                roleDefinitionBindingCollection.Add(roleDef);
                            }

                            targetPage.PageListItem.RoleAssignments.Add(principal, roleDefinitionBindingCollection);
                        }
                    }
                    this.clientContext.ExecuteQueryRetry();
                }
            }
            #endregion

            #region Page name switching
            // All went well so far...swap pages if that's needed
            if (pageTransformationInformation.TargetPageTakesSourcePageName)
            {
                //Load the source page
                SwapPages(pageTransformationInformation);
            }
            #endregion

            #region Telemetry
            if (!pageTransformationInformation.SkipTelemetry && this.pageTelemetry != null)
            {
                TimeSpan duration = DateTime.Now.Subtract(transformationStartDateTime);
                this.pageTelemetry.LogTransformationDone(duration);
                this.pageTelemetry.Flush();
            }
            #endregion

            #region Return final page url
            if (!pageTransformationInformation.TargetPageTakesSourcePageName)
            {
                string path          = pageTransformationInformation.SourcePage[Constants.FileRefField].ToString().Replace(pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString(), "");
                var    targetPageUrl = $"{path}{pageTransformationInformation.TargetPageName}";
                return(targetPageUrl);
            }
            else
            {
                return(pageTransformationInformation.SourcePage[Constants.FileRefField].ToString());
            }
            #endregion

            #endregion
        }
示例#39
0
 private void ShowWiki(string copaPID)
 {
     WikiPage wikiPage = WikiOperations.GetWikiPage(copaPID.Trim());
     if (wikiPage == null)
     {
         wikiPage = new WikiPage();
         wikiPage.PageName = copaPID.Trim();
         wikiPage.PageContent = "There is no Wiki page on record for this protein, please feel free to create one.";
         wikiPage.ModifiedBy = User.Identity.IsAuthenticated ? User.Identity.Name : "Anonymous";
         wikiPage.LastModified = DateTime.Now;
         wikiPage.Created = DateTime.Now;
         wikiPage.IsPrivate = User.Identity.IsAuthenticated ? true : false;
         wikiPage.AllowAnonEdit = User.Identity.IsAuthenticated ? false : true;
     }
     SetPageContent(wikiPage);
 }
 private void gridMain_CellDoubleClick(object sender, UI.ODGridClickEventArgs e)
 {
     JumpToPage   = ListWikiPages[e.Row];
     DialogResult = DialogResult.OK;
 }
示例#41
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="PageUpdated" /> class.
 /// </summary>
 /// <param name="page"> The page. </param>
 public PageUpdated(WikiPage page)
 {
     Page = page;
 }
示例#42
0
        /// <summary>
        /// Transform the page
        /// </summary>
        /// <param name="pageTransformationInformation">Information about the page to transform</param>
        public void Transform(PageTransformationInformation pageTransformationInformation)
        {
            #region Input validation
            if (pageTransformationInformation.SourcePage == null)
            {
                throw new ArgumentNullException("SourcePage cannot be null");
            }

            // Validate page and it's eligibility for transformation
            if (!pageTransformationInformation.SourcePage.FieldExistsAndUsed(Constants.FileRefField) || !pageTransformationInformation.SourcePage.FieldExistsAndUsed(Constants.FileLeafRefField))
            {
                throw new ArgumentException("Page is not valid due to missing FileRef or FileLeafRef value");
            }

            string pageType = pageTransformationInformation.SourcePage.PageType();

            if (pageType.Equals("ClientSidePage", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Page is a client side page...guess you don't want to transform it...");
            }

            if (pageType.Equals("AspxPage", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Page is an basic aspx page...can't transform that one, sorry!");
            }
            #endregion

            #region Telemetry
            clientContext.ClientTag = $"SPDev:PageTransformator";
            clientContext.Load(clientContext.Web, p => p.Description, p => p.Id);
            clientContext.ExecuteQuery();
            #endregion

            #region Page creation
            // If no targetname specified then we'll come up with one
            if (string.IsNullOrEmpty(pageTransformationInformation.TargetPageName))
            {
                if (string.IsNullOrEmpty(pageTransformationInformation.TargetPagePrefix))
                {
                    pageTransformationInformation.SetDefaultTargetPagePrefix();
                }

                pageTransformationInformation.TargetPageName = $"{pageTransformationInformation.TargetPagePrefix}{pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString()}";
            }

            // Check if page name is free to use
            bool           pageExists = false;
            ClientSidePage targetPage = null;
            try
            {
                targetPage = clientContext.Web.LoadClientSidePage(pageTransformationInformation.TargetPageName);
                pageExists = true;
            }
            catch (ArgumentException) { }

            if (pageExists)
            {
                if (!pageTransformationInformation.Overwrite)
                {
                    throw new ArgumentException($"There already exists a page with name {pageTransformationInformation.TargetPageName}.");
                }
                else
                {
                    targetPage.ClearPage();
                }
            }
            else
            {
                // Create a new client side page
                targetPage = clientContext.Web.AddClientSidePage(pageTransformationInformation.TargetPageName);
            }
            #endregion

            #region Home page handling
            bool replacedByOOBHomePage = false;
            // Check if the transformed page is the web's home page
            clientContext.Web.EnsureProperties(w => w.RootFolder.WelcomePage);
            var homePageUrl  = clientContext.Web.RootFolder.WelcomePage;
            var homepageName = Path.GetFileName(clientContext.Web.RootFolder.WelcomePage);
            if (homepageName.Equals(pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString(), StringComparison.InvariantCultureIgnoreCase))
            {
                targetPage.LayoutType = ClientSidePageLayoutType.Home;
                if (pageTransformationInformation.ReplaceHomePageWithDefaultHomePage)
                {
                    targetPage.KeepDefaultWebParts = true;
                    replacedByOOBHomePage          = true;
                }
            }
            #endregion

            #region Article page handling
            if (!replacedByOOBHomePage)
            {
                #region Configure header from target page
                if (pageTransformationInformation.PageHeader == null || pageTransformationInformation.PageHeader.Type == ClientSidePageHeaderType.None)
                {
                    targetPage.RemovePageHeader();
                }
                else if (pageTransformationInformation.PageHeader.Type == ClientSidePageHeaderType.Default)
                {
                    targetPage.SetDefaultPageHeader();
                }
                else if (pageTransformationInformation.PageHeader.Type == ClientSidePageHeaderType.Custom)
                {
                    targetPage.SetCustomPageHeader(pageTransformationInformation.PageHeader.ImageServerRelativeUrl, pageTransformationInformation.PageHeader.TranslateX, pageTransformationInformation.PageHeader.TranslateY);
                }
                #endregion

                #region Analysis of the source page
                // Analyze the source page
                Tuple <PageLayout, List <WebPartEntity> > pageData = null;

                if (pageType.Equals("WikiPage", StringComparison.InvariantCultureIgnoreCase))
                {
                    pageData = new WikiPage(pageTransformationInformation.SourcePage, pageTransformation).Analyze();

                    // Wiki pages can contain embedded images and videos, which is not supported by the target RTE...split wiki text blocks so the transformator can handle the images and videos as separate web parts
                    if (pageTransformationInformation.HandleWikiImagesAndVideos)
                    {
                        pageData = new Tuple <PageLayout, List <WebPartEntity> >(pageData.Item1, new WikiTransformator().TransformPlusSplit(pageData.Item2));
                    }
                }
                else if (pageType.Equals("WebPartPage", StringComparison.InvariantCultureIgnoreCase))
                {
                    pageData = new WebPartPage(pageTransformationInformation.SourcePage, pageTransformation).Analyze(true);
                }
                #endregion

                #region Page title configuration
                // Set page title
                if (pageType.Equals("WikiPage", StringComparison.InvariantCultureIgnoreCase) && pageTransformationInformation.SourcePage.FieldExistsAndUsed(Constants.FileTitleField))
                {
                    targetPage.PageTitle = pageTransformationInformation.SourcePage[Constants.FileTitleField].ToString();
                }
                else if (pageType.Equals("WebPartPage"))
                {
                    var titleBarWebPart = pageData.Item2.Where(p => p.Type == WebParts.TitleBar).FirstOrDefault();
                    if (titleBarWebPart != null)
                    {
                        if (titleBarWebPart.Properties.ContainsKey("HeaderTitle") && !string.IsNullOrEmpty(titleBarWebPart.Properties["HeaderTitle"]))
                        {
                            targetPage.PageTitle = titleBarWebPart.Properties["HeaderTitle"];
                        }
                    }
                }

                if (pageTransformationInformation.PageTitleOverride != null)
                {
                    targetPage.PageTitle = pageTransformationInformation.PageTitleOverride(targetPage.PageTitle);
                }
                #endregion

                #region Page layout configuration
                // Use the default layout transformator
                ILayoutTransformator layoutTransformator = new LayoutTransformator(targetPage);

                // Do we have an override?
                if (pageTransformationInformation.LayoutTransformatorOverride != null)
                {
                    layoutTransformator = pageTransformationInformation.LayoutTransformatorOverride(targetPage);
                }

                // Apply the layout to the page
                layoutTransformator.Transform(pageData.Item1);
                #endregion

                #region Content transformation
                // Use the default content transformator
                IContentTransformator contentTransformator = new ContentTransformator(targetPage, pageTransformation);

                // Do we have an override?
                if (pageTransformationInformation.ContentTransformatorOverride != null)
                {
                    contentTransformator = pageTransformationInformation.ContentTransformatorOverride(targetPage, pageTransformation);
                }

                // Run the content transformator
                contentTransformator.Transform(pageData.Item2);
                #endregion
            }
            #endregion

            #region Page persisting
            // Persist the client side page
            targetPage.Save(pageTransformationInformation.TargetPageName);
            targetPage.Publish();

            // All went well so far...swap pages if that's needed
            if (pageTransformationInformation.TargetPageTakesSourcePageName)
            {
                //Load the source page
                var sourcePageUrl         = pageTransformationInformation.SourcePage[Constants.FileRefField].ToString();
                var orginalSourcePageName = pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString();

                string path = sourcePageUrl.Replace(pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString(), "");

                var sourcePage = this.clientContext.Web.GetFileByServerRelativeUrl(sourcePageUrl);
                this.clientContext.Load(sourcePage);
                this.clientContext.ExecuteQueryRetry();

                if (string.IsNullOrEmpty(pageTransformationInformation.SourcePagePrefix))
                {
                    pageTransformationInformation.SetDefaultSourcePagePrefix();
                }
                var newSourcePageUrl = $"{pageTransformationInformation.SourcePagePrefix}{pageTransformationInformation.SourcePage[Constants.FileLeafRefField].ToString()}";

                // Rename source page using the sourcepageprefix
                sourcePage.MoveTo($"{path}{newSourcePageUrl}", MoveOperations.None);
                this.clientContext.ExecuteQueryRetry();

                //Load the created target page
                var targetPageUrl  = $"{path}{pageTransformationInformation.TargetPageName}";
                var targetPageFile = this.clientContext.Web.GetFileByServerRelativeUrl(targetPageUrl);
                this.clientContext.Load(targetPageFile);
                this.clientContext.ExecuteQueryRetry();

                // Rename the target page to the original source page name
                targetPageFile.MoveTo($"{path}{orginalSourcePageName}", MoveOperations.Overwrite);
                this.clientContext.ExecuteQueryRetry();
            }
            #endregion
        }
示例#43
0
 public void OutputFilenameIsPageNamePlusHtmlExtension()
 {
     WikiPage page = new WikiPage("SomePage", "content ignored", 0);
     Assert.AreEqual(page.GetOutputFilename(),("SomePage.html"));
 }
示例#44
0
 /// <summary>
 /// Creates the or update wiki page asynchronous.
 /// </summary>
 /// <param name="redmineManager">The redmine manager.</param>
 /// <param name="projectId">The project identifier.</param>
 /// <param name="pageName">Name of the page.</param>
 /// <param name="wikiPage">The wiki page.</param>
 /// <returns></returns>
 public static Task <WikiPage> CreateOrUpdateWikiPageAsync(this RedmineManager redmineManager, string projectId, string pageName, WikiPage wikiPage)
 {
     return(Task.Factory.StartNew(() => redmineManager.CreateOrUpdateWikiPage(projectId, pageName, wikiPage), TaskCreationOptions.LongRunning));
 }
示例#45
0
 public void TransformsWordsSmashedTogetherIntoWikiLinks()
 {
     WikiPage page = new WikiPage("PageName", "Link to AnotherPage.", 0);
     AssertContainsString(page.AsHtml(),"Link to <a href=\"AnotherPage.html\">AnotherPage</a>.");
 }
示例#46
0
 private bool CanEditPage(WikiPage wikiPage)
 {
     return(IsWikiAdmin || wikiPage.Author.Login == CurrentUser.Login);
 }
示例#47
0
 public void WikiLinksCannotAppearInTheMiddleOfOtherWords()
 {
     WikiPage page = new WikiPage("PageName", "This should notBeLinked.", 0);
     AssertContainsString(page.AsHtml(),"should notBeLinked.");
     AssertContainsString( false, page.AsHtml(), "<a");
 }
示例#48
0
 private void webBrowserWiki_Navigating(object sender, WebBrowserNavigatingEventArgs e)
 {
     //For debugging, we need to remember that the following happens when you click on an internal link:
     //1. This method fires. url includes 'wiki:'
     //2. This causes LoadWikiPage method to fire.  It loads the document text.
     //3. Which causes this method to fire again.  url is "about:blank".
     //This doesn't seem to be a problem.  We wrote it so that it won't go into an infinite loop, but it's something to be aware of.
     if (e.Url.ToString() == "about:blank" || e.Url.ToString().StartsWith("about:blank#"))
     {
         //This is a typical wiki page OR this is an internal bookmark.
         //We want to let the browser control handle the "navigation" so that it correctly loads the page OR simply auto scrolls to the div.
     }
     else if (e.Url.ToString().StartsWith("about:"))
     {
         //All other URLs that start with about: and do not have the required "blank#" are treated as malformed URLs.
         e.Cancel = true;
         return;
     }
     else if (e.Url.ToString().StartsWith("wiki:"))             //user clicked on an internal link
     //It is invalid to have more than one space in a row in URLs.
     //When there is more than one space in a row, WebBrowserNavigatingEventArgs will convert the spaces into '&nbsp'
     //In order for our internal wiki page links to work, we need to always replace the '&nbsp' chars with spaces again.
     {
         string   wikiPageTitle   = Regex.Replace(e.Url.ToString(), @"\u00A0", " ").Substring(5);
         WikiPage wikiPageDeleted = WikiPages.GetByTitle(wikiPageTitle, isDeleted: true);            //Should most likely be null.
         WikiPage wpExisting;
         if (wikiPageDeleted != null && HasExistingWikiPage(wikiPageDeleted, out wpExisting))
         {
             //Now replace any references to wikiPageDeleted with the non deleted wp(wpExisting).
             WikiPages.UpdateWikiPageReferences(WikiPageCur.WikiPageNum, wikiPageDeleted.WikiPageNum, wpExisting.WikiPageNum);
             //Continue to load the page.
         }
         else if (wikiPageDeleted != null)
         {
             if (MessageBox.Show(Lan.g(this, "WikiPage '") + wikiPageTitle + Lan.g(this, "' is currently archived. Would you like to restore it?"),
                                 "", MessageBoxButtons.OKCancel) != DialogResult.OK)
             {
                 e.Cancel = true;
                 return;
             }
             else
             {
                 //User wants to restore the WikiPage.
                 WikiPages.WikiPageRestore(wikiPageDeleted, Security.CurUser.UserNum);
             }
         }
         historyNavBack--;                //We have to decrement historyNavBack to tell whether or not we need to branch our page history or add to page history
         LoadWikiPage(wikiPageTitle);
         e.Cancel = true;
         return;
     }
     else if (e.Url.ToString().Contains("wikifile:") && !ODBuild.IsWeb())
     {
         string fileName = e.Url.ToString().Substring(e.Url.ToString().LastIndexOf("wikifile:") + 9).Replace("/", "\\");
         if (!File.Exists(fileName))
         {
             MessageBox.Show(Lan.g(this, "File does not exist: ") + fileName);
             e.Cancel = true;
             return;
         }
         try {
             System.Diagnostics.Process.Start(fileName);
         }
         catch (Exception ex) {
             ex.DoNothing();
         }
         e.Cancel = true;
         return;
     }
     else if (e.Url.ToString().Contains("folder:") && !ODBuild.IsWeb())
     {
         string folderName = e.Url.ToString().Substring(e.Url.ToString().LastIndexOf("folder:") + 7).Replace("/", "\\");
         if (!Directory.Exists(folderName))
         {
             MessageBox.Show(Lan.g(this, "Folder does not exist: ") + folderName);
             e.Cancel = true;
             return;
         }
         try {
             System.Diagnostics.Process.Start(folderName);
         }
         catch (Exception ex) {
             ex.DoNothing();
         }
         e.Cancel = true;
         return;
     }
     else if (e.Url.ToString().Contains("wikifilecloud:"))
     {
         string fileName = e.Url.ToString().Substring(e.Url.ToString().LastIndexOf("wikifilecloud:") + 14);
         if (!FileAtoZ.Exists(fileName))
         {
             MessageBox.Show(Lan.g(this, "File does not exist: ") + fileName);
             e.Cancel = true;
             return;
         }
         try {
             FileAtoZ.StartProcess(fileName);
         }
         catch (Exception ex) {
             ex.DoNothing();
         }
         e.Cancel = true;
         return;
     }
     else if (e.Url.ToString().Contains("foldercloud:"))
     {
         string folderName = e.Url.ToString().Substring(e.Url.ToString().LastIndexOf("foldercloud:") + 12);
         if (!FileAtoZ.DirectoryExists(folderName))
         {
             MessageBox.Show(Lan.g(this, "Folder does not exist: ") + folderName);
             e.Cancel = true;
             return;
         }
         try {
             FileAtoZ.OpenDirectory(folderName);
         }
         catch (Exception ex) {
             ex.DoNothing();
         }
         e.Cancel = true;
         return;
     }
     else if (e.Url.ToString().StartsWith("http"))             //navigating outside of wiki by clicking a link
     {
         try {
             System.Diagnostics.Process.Start(e.Url.ToString());
         }
         catch (Exception ex) {
             ex.DoNothing();
         }
         e.Cancel = true;              //Stops the page from loading in FormWiki.
         return;
     }
 }
示例#49
0
		///<summary>Updates one WikiPage in the database.</summary>
		public static void Update(WikiPage wikiPage){
			string command="UPDATE wikipage SET "
				+"UserNum      =  "+POut.Long  (wikiPage.UserNum)+", "
				+"PageTitle    = '"+POut.String(wikiPage.PageTitle)+"', "
				+"KeyWords     = '"+POut.String(wikiPage.KeyWords)+"', "
				+"PageContent  = '"+POut.String(wikiPage.PageContent)+"', "
				//DateTimeSaved not allowed to change
				+"WHERE WikiPageNum = "+POut.Long(wikiPage.WikiPageNum);
			Db.NonQ(command);
		}
示例#50
0
        /// <summary>
        ///     Creates the or update wiki page asynchronous.
        /// </summary>
        /// <param name="redmineManager">The redmine manager.</param>
        /// <param name="projectId">The project identifier.</param>
        /// <param name="pageName">Name of the page.</param>
        /// <param name="wikiPage">The wiki page.</param>
        /// <returns></returns>
        public static async Task <WikiPage> CreateOrUpdateWikiPageAsync(this RedmineManager redmineManager, string projectId, string pageName, WikiPage wikiPage)
        {
            var data = redmineManager.Serializer.Serialize(wikiPage);

            if (string.IsNullOrEmpty(data))
            {
                return(null);
            }

            var url = UrlHelper.GetWikiCreateOrUpdaterUrl(redmineManager, projectId, pageName);

            url = Uri.EscapeUriString(url);

            var response = await WebApiAsyncHelper.ExecuteUpload(redmineManager, url, HttpVerbs.PUT, data).ConfigureAwait(false);

            return(redmineManager.Serializer.Deserialize <WikiPage>(response));
        }
示例#51
0
 internal async Task QueuePageForWritingAsync(WikiPage page, string content, string summary)
 {
     await batchBlock.SendAsync(new QueuedWritingTask(page, content, summary));
 }
示例#52
0
        ///<summary>Before calling this, make sure to increment/decrement the historyNavBack index to keep track of the position in history.  If loading a new page, decrement historyNavBack before calling this function.  </summary>
        private void LoadWikiPage(string pageTitle)
        {
            //This is called from 11 different places, any time the program needs to refresh a page from the db.
            //It's also called from the browser_Navigating event when a "wiki:" link is clicked.
            WikiPage wpage = WikiPages.GetByTitle(pageTitle);

            if (wpage == null)
            {
                string errorMsg = "";
                if (!WikiPages.IsWikiPageTitleValid(pageTitle, out errorMsg))
                {
                    MsgBox.Show(this, "That page does not exist and cannot be made because the page title contains invalid characters.");
                    return;
                }
                if (!MsgBox.Show(this, MsgBoxButtons.YesNo, "That page does not exist. Would you like to create it?"))
                {
                    return;
                }
                Action <string> onWikiSaved = new Action <string>((pageTitleNew) => {
                    //Insert the pageTitleNew where the pageTitle exists in the existing WikiPageCur
                    //(guaranteed to be unique because all INVALID WIKIPAGE LINK's have an ID at the end)
                    string pageContent      = WikiPages.GetWikiPageContentWithWikiPageTitles(WikiPageCur.PageContent);
                    WikiPageCur.PageContent = pageContent.Replace(pageTitle, pageTitleNew);
                    WikiPageCur.PageContent = WikiPages.ConvertTitlesToPageNums(WikiPageCur.PageContent);
                    if (!WikiPageCur.IsDraft)
                    {
                        WikiPageCur.PageContentPlainText = MarkupEdit.ConvertToPlainText(WikiPageCur.PageContent);
                    }
                    WikiPages.Update(WikiPageCur);
                });
                AddWikiPage(onWikiSaved);
                return;
            }
            WikiPageCur = wpage;
            try {
                webBrowserWiki.DocumentText = MarkupEdit.TranslateToXhtml(WikiPageCur.PageContent, false);
            }
            catch (Exception ex) {
                webBrowserWiki.DocumentText = "";
                MessageBox.Show(this, Lan.g(this, "This page is broken and cannot be viewed.  Error message:") + " " + ex.Message);
            }
            Text = "Wiki - " + WikiPageCur.PageTitle;
            #region historyMaint
            //This region is duplicated in webBrowserWiki_Navigating() for external links.  Modifications here will need to be reflected there.
            int indexInHistory = historyNav.Count - (1 + historyNavBack); //historyNavBack number of pages before the last page in history.  This is the index of the page we are loading.
            if (historyNav.Count == 0)                                    //empty history
            {
                historyNavBack = 0;
                historyNav.Add("wiki:" + pageTitle);
            }
            else if (historyNavBack < 0)           //historyNavBack could be negative here.  This means before the action that caused this load, we were not navigating through history, simply set back to 0 and add to historyNav[] if necessary.
            {
                historyNavBack = 0;
                if (historyNav[historyNav.Count - 1] != "wiki:" + pageTitle)
                {
                    historyNav.Add("wiki:" + pageTitle);
                }
            }
            else if (historyNavBack >= 0 && historyNav[indexInHistory] != "wiki:" + pageTitle) //branching from page in history
            {
                historyNav.RemoveRange(indexInHistory, historyNavBack + 1);                    //remove "forward" history. branching off in a new direction
                historyNavBack = 0;
                historyNav.Add("wiki:" + pageTitle);
            }
            #endregion
        }
示例#53
0
		///<summary>Inserts one WikiPage into the database.  Provides option to use the existing priKey.</summary>
		public static long Insert(WikiPage wikiPage,bool useExistingPK){
			if(!useExistingPK && PrefC.RandomKeys) {
				wikiPage.WikiPageNum=ReplicationServers.GetKey("wikipage","WikiPageNum");
			}
			string command="INSERT INTO wikipage (";
			if(useExistingPK || PrefC.RandomKeys) {
				command+="WikiPageNum,";
			}
			command+="UserNum,PageTitle,KeyWords,PageContent,DateTimeSaved) VALUES(";
			if(useExistingPK || PrefC.RandomKeys) {
				command+=POut.Long(wikiPage.WikiPageNum)+",";
			}
			command+=
				     POut.Long  (wikiPage.UserNum)+","
				+"'"+POut.String(wikiPage.PageTitle)+"',"
				+"'"+POut.String(wikiPage.KeyWords)+"',"
				+"'"+POut.String(wikiPage.PageContent)+"',"
				+    DbHelper.Now()+")";
			if(useExistingPK || PrefC.RandomKeys) {
				Db.NonQ(command);
			}
			else {
				wikiPage.WikiPageNum=Db.NonQ(command,true);
			}
			return wikiPage.WikiPageNum;
		}
示例#54
0
        /// <inheritdoc />
        protected override void ProcessRecord()
        {
            var page = new WikiPage(WikiSite, Title);

            WriteObject(page);
        }
示例#55
0
        //Uploads a file to the Wiki
        private async Task UploadFile(string fileName, IEnumerable <DataGridViewRow> demons)
        {
            if (Connected && File.Exists(fileName))
            {
                //Generate our Page Name
                var pageName = Path.GetFileNameWithoutExtension(fileName);
                pageName = pageName.Replace("-Demons", "/Demons").Replace("[", "(").Replace("]", ")").Replace("-Sword", "/Sword").Replace("-Shield", "/Shield");

                //If we are a skill check if demon shares our name
                if (demons != null)
                {
                    if (pageName.Contains("/Demons"))
                    {
                        if (demons.Any(d => (string)d.Cells[0].Value + "/Demons" == pageName))
                        {
                            pageName = pageName.Replace("/Demons", "") + " (Skill)/Demons";
                        }
                    }
                    else
                    {
                        if (demons.Any(d => (string)d.Cells[0].Value == pageName))
                        {
                            pageName = pageName + " (Skill)";
                        }
                    }
                }

                Callback.AppendTextBox("Processing.. " + pageName + "\n");

                var page = new WikiPage(Site, pageName);
                await page.RefreshAsync(PageQueryOptions.FetchContent).ConfigureAwait(false);

                var content = File.ReadAllText(fileName);
                if (page.Content == null || page.Content.Trim() != content.Replace("\r", "").Trim())
                {
                    bool repeat = true;
                    var  count  = 0;
                    while (repeat)
                    {
                        count++;
                        if (count >= 5)
                        {
                            Callback.AppendTextBox("Can't update page. Skipping: <https://dx2wiki.com/index.php/" + Uri.EscapeUriString(pageName) + "> \n");
                            repeat = false;
                        }
                        else
                        {
                            try
                            {
                                page.Content = content;
                                bool worked = await page.UpdateContentAsync("Updated by " + ConfigurationManager.AppSettings["username"] + ". This was done by a bot.", false, true, AutoWatchBehavior.Default).ConfigureAwait(false);

                                if (worked)
                                {
                                    Callback.AppendTextBox("Updated: <https://dx2wiki.com/index.php/" + Uri.EscapeUriString(pageName) + "> \n");
                                    File.Delete(fileName);
                                    Callback.AppendTextBox("File Removed: " + fileName + "\n");
                                }
                                else
                                {
                                    Callback.AppendTextBox("Could not upload: <https://dx2wiki.com/index.php/" + Uri.EscapeUriString(pageName) + "> \n");
                                }

                                repeat = false;
                            }
                            catch (Exception e)
                            {
                                Callback.AppendTextBox(e.Message + "\n" + e.StackTrace + "\n");
                                Callback.AppendTextBox("Retrying.. <https://dx2wiki.com/index.php/" + Uri.EscapeUriString(pageName) + ">\n");
                            }
                        }
                    }
                }
                else
                {
                    Callback.AppendTextBox("No Change Required: <https://dx2wiki.com/index.php/" + Uri.EscapeUriString(pageName) + "> \n");
                    File.Delete(fileName);
                    Callback.AppendTextBox("File Removed: " + fileName + "\n");
                }
            }
        }
示例#56
0
    protected void form_DataBinding(object sender, EventArgs e)
    {
        WikiReader graph   = (WikiReader)this.DS.DataGraph;
        PXCache    cache   = graph.Views[this.DS.PrimaryView].Cache;
        WikiPage   current = cache.Current as WikiPage;

        if (current != null)
        {
            WikiRevision currentrevision =
                PXSelect <WikiRevision,
                          Where <WikiRevision.pageID,
                                 Equal <Required <WikiRevision.pageID> > >, OrderBy <Desc <WikiRevision.pageRevisionID> > > .SelectWindowed(new PXGraph(), 0, 1, current.PageID);

            if (this.PublicUrlEditor != null)
            {
                this.PublicUrlEditor.Text = string.Empty;
            }

            if (current.WikiID != null)
            {
                if (Master is IPXMasterPage)
                {
                    (Master as IPXMasterPage).ScreenTitle = current.Title;
                }
                if (Master is IPXMasterPage)
                {
                    (Master as IPXMasterPage).BranchAvailable = false;
                }
                graph.Filter.Current.WikiID = current.WikiID;
                WikiDescriptor wiki    = graph.wikis.SelectWindowed(0, 1, current.WikiID);
                PXWikiShow     content = MainForm.FindControl("edContent") as PXWikiShow;
                if (wiki != null)
                {
                    if (!string.IsNullOrEmpty(wiki.PubVirtualPath))
                    {
                        if (PublicUrlEditor != null)
                        {
                            PublicUrlEditor.Text = Request.GetExternalUrl().ToString();
                            int index = PublicUrlEditor.Text.IndexOf("Wiki");
                            if (index > -1)
                            {
                                PublicUrlEditor.Text = PublicUrlEditor.Text.Remove(0, index);
                                PublicUrlEditor.Text = wiki.PubVirtualPath + "/" + PublicUrlEditor.Text;
                            }
                        }
                    }
                    if (!Page.IsPostBack)
                    {
                        PXAuditJournal.Register("WI000000", Wiki.Link(wiki.Name, current.Name));
                    }
                }

                if (content != null)
                {
                    PXDBContext wikiContext = (PXDBContext)content.WikiContext;

                    if (currentrevision != null)
                    {
                        wikiContext.Text = currentrevision.Content;
                    }
                    if (_pageDBContextType == null)
                    {
                        wikiContext.ContentWidth  = current.Width.GetValueOrDefault(0);
                        wikiContext.ContentHeight = current.Height.GetValueOrDefault(0);
                        wikiContext.PageTitle     = current.Title;
                    }

                    wikiContext.WikiID = current.WikiID.Value != Guid.Empty ? current.WikiID.Value : current.PageID.Value;

                    if (current.PageID != null && (_pageDBContextType == null &&
                                                   (PXSiteMap.WikiProvider.GetAccessRights(current.PageID.Value) >= PXWikiRights.Update &&
                                                    current.PageRevisionID > 0)))
                    {
                        wikiContext.LastModified        = current.PageRevisionDateTime;
                        wikiContext.LastModifiedByLogin = cache.GetStateExt(current, "PageRevisionCreatedByID").ToString();
                    }
                    if (current.PageID != null && PXSiteMap.WikiProvider.GetAccessRights(current.PageID.Value) >= PXWikiRights.Update)
                    {
                        wikiContext.RenderSectionLink = true;
                    }
                    else
                    {
                        wikiContext.HideBrokenLink    = true;
                        wikiContext.RedirectAvailable = true;
                    }

                    if (this.WikiTextPanel != null)
                    {
                        this.WikiTextPanel.Caption = current.Title;
                    }
                    if (this.WikiTextEditor != null)
                    {
                        this.WikiTextEditor.Text = graph.ConvertGuidToLink(current.Content);
                    }
                }
                if (this.LinkEditor != null)
                {
                    this.LinkEditor.Text = "[" + (wiki != null && wiki.Name != null ? wiki.Name + "\\" : string.Empty) + current.Name + "]";
                }
            }
        }
        this.Page.ClientScript.RegisterClientScriptBlock(GetType(), "varreg", "var printLink=\"" + ResolveUrl("~/Wiki/Print.aspx") + "?" + Request.QueryString + "\";", true);

        if (this.LinkEditor != null)
        {
            LinkEditor.ReadOnly = true;
        }
        if (this.UrlEditor != null)
        {
            UrlEditor.Text     = Request.GetExternalUrl().ToString();
            UrlEditor.ReadOnly = true;
        }
        if (this.PublicUrlEditor != null)
        {
            PublicUrlEditor.Enabled  = !string.IsNullOrEmpty(PublicUrlEditor.Text);
            PublicUrlEditor.ReadOnly = true;
        }
    }
示例#57
0
 private WikiPage instantiateWikiPage()
 {
     WikiPage wikiPage = new WikiPage();
     wikiPage.ModifiedBy = User.Identity.IsAuthenticated ? User.Identity.Name : "Anonymous";
     if (nameEdit.Text != "")
         wikiPage.ModifiedBy = nameEdit.Text;
     else
         wikiPage.ModifiedBy = "Anonymous";
     wikiPage.PageContent = ftbEdit.Text;
     wikiPage.PageName = m_PageName;
     wikiPage.IsPrivate = false;//User.Identity.IsAuthenticated ? chkPrivate.Checked : false;
     wikiPage.AllowAnonEdit = true;//User.Identity.IsAuthenticated ? chkAnonEdit.Checked : true;
     wikiPage.LastModified = DateTime.Now;
     wikiPage.Created = DateTime.Now;
     return wikiPage;
 }
示例#58
0
 public QueuedWritingTask(WikiPage page, string newContent, string summary)
 {
     Page       = page;
     NewContent = newContent;
     Summary    = summary;
 }
示例#59
0
        public async Task <WikipediaArticle> GetArticleAsync(string language, string name)
        {
            if (rateLimiter.IsRatelimited())
            {
                return(null);
            }

            var article = new WikipediaArticle
            {
                Url = $"https://{language}.wikipedia.org/wiki/{name}"
            };

            var page = new WikiPage(wikipediaSite, name);

            await page.RefreshAsync(new WikiPageQueryProvider
            {
                Properties =
                {
                    new ExtractsPropertyProvider
                    {
                        MaxCharacters    = 1024,
                        AsPlainText      = true,
                        IntroductionOnly = true
                    }
                }
            });

            var extractGroup = page.GetPropertyGroup <ExtractsPropertyGroup>();

            article.Name = page.Title;
            article.Url  = WikiLink.Parse(wikipediaSite, name).TargetUrl;

            article.Description = extractGroup.Extract;

            if (article.Description.Length >= 1024)
            {
                var split = article.Description.Split(". ").ToList();
                article.Description = string.Join(". ", split.Take(4)) + ".";
            }

            var response = await HttpWebClient.ReturnStringAsync(new System.Uri($"https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&sites={language}wiki&props=claims&titles={name}"));

            var jsonresp  = JObject.Parse(response);
            var container = (JObject)jsonresp["entities"].First.Value <JProperty>().Value;
            var claims    = container["claims"];

            //P18/P154/P242/P109/P1621
            JToken snak = null;

            if (claims["P18"] is not null)
            {
                snak = claims["P18"];
            }
            else if (claims["P154"] is not null)
            {
                snak = claims["P154"];
            }
            else if (claims["P242"] is not null)
            {
                snak = claims["P242"];
            }
            else if (claims["P109"] is not null)
            {
                snak = claims["P109"];
            }
            else if (claims["P1621"] is not null)
            {
                snak = claims["P1621"];
            }

            if (snak is not null)
            {
                var val = snak.First["mainsnak"]["datavalue"]["value"].ToObject <string>();

                val = val.Replace(" ", "_");

                var md5 = val.CreateMD5(true);;

                article.ImageUrl = $"https://upload.wikimedia.org/wikipedia/commons/{md5[0]}/{md5[0]}{md5[1]}/{val}";
            }

            return(article);
        }
示例#60
0
        static async Task HelloWikiWorld()
        {
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddConsole(LogLevel.Information, true);
            // Create a MediaWiki API client.
            var wikiClient = new WikiClient
            {
                // UA of Client Application. The UA of WikiClientLibrary will
                // be append to the end of this when sending requests.
                ClientUserAgent = "ConsoleTestApplication1/1.0",
                Logger          = loggerFactory.CreateLogger <WikiClient>(),
            };
            // Create a MediaWiki Site instance with the URL of API endpoint.
            var site = new WikiSite(wikiClient, "https://test2.wikipedia.org/w/api.php")
            {
                Logger = loggerFactory.CreateLogger <WikiSite>()
            };
            // Waits for the WikiSite to initialize
            await site.Initialization;

            // Access site information via Site.SiteInfo
            Console.WriteLine("API version: {0}", site.SiteInfo.Generator);
            // Access user information via Site.UserInfo
            Console.WriteLine("Hello, {0}!", site.AccountInfo.Name);
            // Site login
            Console.WriteLine("We will edit [[Project:Sandbox]].");
            if (Confirm($"Do you want to login into {site.SiteInfo.SiteName}?"))
            {
LOGIN_RETRY:
                try
                {
                    await site.LoginAsync(Input("User name"), Input("Password"));
                }
                catch (OperationFailedException ex)
                {
                    Console.WriteLine(ex.ErrorMessage);
                    goto LOGIN_RETRY;
                }
                Console.WriteLine("You have successfully logged in as {0}.", site.AccountInfo.Name);
                Console.WriteLine("You're in the following groups: {0}.", string.Join(",", site.AccountInfo.Groups));
            }
            // Find out more members in Site class, such as
            //  page.Namespaces
            //  page.InterwikiMap

            // Page Operations
            // Fetch information and content
            var page = new WikiPage(site, site.SiteInfo.MainPage);

            Console.WriteLine("Retrieving {0}...", page);
            await page.RefreshAsync(PageQueryOptions.FetchContent);

            Console.WriteLine("Last touched at {0}.", page.LastTouched);
            Console.WriteLine("Last revision {0} by {1} at {2}.", page.LastRevisionId,
                              page.LastRevision.UserName, page.LastRevision.TimeStamp);
            Console.WriteLine("Content length: {0} bytes ----------", page.ContentLength);
            Console.WriteLine(page.Content);
            // Purge the page
            if (await page.PurgeAsync())
            {
                Console.WriteLine("  The page has been purged successfully.");
            }
            // Edit the page
            page = new WikiPage(site, "Project:Sandbox");
            await page.RefreshAsync(PageQueryOptions.FetchContent);

            if (!page.Exists)
            {
                Console.WriteLine("Warning: The page {0} doesn't exist.", page);
            }
            page.Content += "\n\n'''Hello''' ''world''!";
            await page.UpdateContentAsync("Test edit from WikiClientLibrary.");

            Console.WriteLine("{0} has been saved. RevisionId = {1}.", page, page.LastRevisionId);
            // Find out more operations in Page class, such as
            //  page.MoveAsync()
            //  page.DeleteAsync()
            // Logout
            await site.LogoutAsync();

            Console.WriteLine("You have successfully logged out.");
        }