Exemple #1
0
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        // Invoked by the ProgressDialog OnShown callback
        private async Task Execute(UI.ProgressDialog progress, CancellationToken token)
        {
            logger.Start();
            logger.StartClock();

            using (var one = new OneNote())
            {
                var hierarchy = await GetHierarchy(one);

                var ns = one.GetNamespace(hierarchy);

                var pageList = hierarchy.Descendants(ns + "Page")
                               .Where(e => e.Attribute("isInRecycleBin") == null);

                var pageCount = pageList.Count();
                progress.SetMaximum(pageCount);
                progress.SetMessage($"Scanning {pageCount} pages");

                // OneNote likes to inject \n\r before the href attribute so match any spaces
                var editor = new Regex(
                    $"(<a\\s+href=[^>]+{keys}[^>]+>)([^<]*)(</a>)",
                    RegexOptions.Compiled | RegexOptions.Multiline);

                foreach (var item in pageList)
                {
                    progress.Increment();
                    progress.SetMessage(item.Attribute("name").Value);

                    var xml = one.GetPageXml(item.Attribute("ID").Value, OneNote.PageDetail.Basic);

                    // initial string scan before instantiating entire XElement DOM
                    if (xml.Contains(keys))
                    {
                        var page = new Page(XElement.Parse(xml));

                        var blocks = page.Root.DescendantNodes().OfType <XCData>()
                                     .Where(n => n.Value.Contains(keys))
                                     .ToList();

                        foreach (var block in blocks)
                        {
                            block.Value = editor.Replace(block.Value, $"$1{title}$3");
                        }

                        await one.Update(page);

                        updates++;
                    }

                    if (token.IsCancellationRequested)
                    {
                        logger.WriteLine("cancelled");
                        break;
                    }
                }
            }

            logger.WriteTime("refresh complete");
            logger.End();
        }
Exemple #2
0
        public override async Task Execute(params object[] args)
        {
            using (one = new OneNote(out parentPage, out var ns, OneNote.PageDetail.Selection))
            {
                var candidates = GetHyperlinks(parentPage);
                if (!candidates.Any())
                {
                    UIHelper.ShowMessage(Resx.CrawlWebCommand_NoHyperlinks);
                    return;
                }

                using (var dialog = new CrawlWebPageDialog(candidates))
                {
                    if (dialog.ShowDialog(owner) != DialogResult.OK)
                    {
                        return;
                    }

                    selections = dialog.GetSelectedHyperlinks();
                }

                // reverse so we create subpages in correct order
                selections.Reverse();

                importer = new ImportWebCommand();
                importer.SetLogger(logger);

                var progress = new UI.ProgressDialog(DownloadSelectedSubpages);
                progress.SetMaximum(selections.Count);
                await progress.RunModeless();
            }
        }
Exemple #3
0
        private void ExportMany(OneNote one, List <string> pageIDs)
        {
            OneNote.ExportFormat format;
            string path;

            using (var dialog = new ExportDialog(pageIDs.Count))
            {
                if (dialog.ShowDialog(owner) != DialogResult.OK)
                {
                    return;
                }

                path   = dialog.FolderPath;
                format = dialog.Format;
            }

            string ext = null;

            switch (format)
            {
            case OneNote.ExportFormat.HTML: ext = ".htm"; break;

            case OneNote.ExportFormat.PDF: ext = ".pdf"; break;

            case OneNote.ExportFormat.Word: ext = ".docx"; break;

            case OneNote.ExportFormat.XML: ext = ".xml"; break;

            case OneNote.ExportFormat.OneNote: ext = ".one"; break;
            }

            string formatName = format.ToString();

            using (var progress = new UI.ProgressDialog())
            {
                progress.SetMaximum(pageIDs.Count);
                progress.Show(owner);

                foreach (var pageID in pageIDs)
                {
                    var page     = one.GetPage(pageID, OneNote.PageDetail.BinaryData);
                    var filename = Path.Combine(path, page.Title.Replace(' ', '_') + ext);

                    progress.SetMessage(filename);
                    progress.Increment();

                    if (format == OneNote.ExportFormat.XML)
                    {
                        SaveAsXML(page.Root, filename);
                    }
                    else
                    {
                        SaveAs(one, page.PageId, filename, format, formatName);
                    }
                }
            }

            UIHelper.ShowMessage(string.Format(Resx.SaveAsMany_Success, pageIDs.Count, path));
        }
Exemple #4
0
        private bool Execute(string workPath)
        {
            using (source = new CancellationTokenSource())
            {
                using (progressDialog = new UI.ProgressDialog(source))
                {
                    var timeout = plugin.Timeout == 0 ? Plugin.MaxTimeout : plugin.Timeout;

                    progressDialog.SetMaximum(timeout);
                    progressDialog.SetMessage(string.Format(
                                                  Resx.Plugin_Running, plugin.Command, plugin.Arguments, workPath));

                    Process process = null;

                    try
                    {
                        // process should run in an STA thread otherwise it will conflict with
                        // the OneNote MTA thread environment
                        var thread = new Thread(() =>
                        {
                            process = StartPlugin(workPath);
                        });

                        thread.SetApartmentState(ApartmentState.STA);
                        thread.IsBackground = true;
                        thread.Start();

                        progressDialog.StartTimer();
                        var result = progressDialog.ShowDialog(owner);

                        if (result == DialogResult.Cancel)
                        {
                            logger.WriteLine("clicked cancel");
                            process.Kill();
                            return(false);
                        }
                    }
                    catch (Exception exc)
                    {
                        logger.WriteLine("error running Execute(string)", exc);
                    }
                    finally
                    {
                        if (process != null)
                        {
                            process.Dispose();
                            process = null;
                        }
                    }
                }
            }

            return(true);
        }
        public override async Task Execute(params object[] args)
        {
            logger.StartClock();

            using (var one = new OneNote())
            {
                var section = one.GetSection();
                if (section != null)
                {
                    var ns = one.GetNamespace(section);

                    var pageIds = section.Elements(ns + "Page")
                                  .Select(e => e.Attribute("ID").Value)
                                  .ToList();

                    using (var progress = new UI.ProgressDialog())
                    {
                        progress.SetMaximum(pageIds.Count);
                        progress.Show(owner);

                        foreach (var pageId in pageIds)
                        {
                            var page = one.GetPage(pageId, OneNote.PageDetail.Basic);
                            var name = page.Root.Attribute("name").Value;

                            progress.SetMessage(string.Format(
                                                    Properties.Resources.RemovingPageNumber_Message, name));

                            progress.Increment();

                            if (string.IsNullOrEmpty(name))
                            {
                                continue;
                            }

                            if (RemoveNumbering(name, out string clean))
                            {
                                page.Root
                                .Element(ns + "Title")
                                .Element(ns + "OE")
                                .Element(ns + "T")
                                .GetCData().Value = clean;

                                await one.Update(page);
                            }
                        }
                    }
                }
            }

            logger.StopClock();
            logger.WriteTime("removed page numbering");
        }
        public override async Task Execute(params object[] args)
        {
            using (var dialog = new NumberPagesDialog())
            {
                if (dialog.ShowDialog(owner) == DialogResult.OK)
                {
                    using (one = new OneNote())
                    {
                        var section = one.GetSection();
                        ns = one.GetNamespace(section);

                        var pages = section.Elements(ns + "Page")
                                    .Select(e => new PageBasics
                        {
                            ID    = e.Attribute("ID").Value,
                            Name  = e.Attribute("name").Value,
                            Level = int.Parse(e.Attribute("pageLevel").Value)
                        })
                                    .ToList();

                        if (pages?.Count > 0)
                        {
                            logger.StartClock();

                            var index = 0;

                            if (dialog.CleanupNumbering)
                            {
                                cleaner = new RemovePageNumbersCommand();
                            }

                            using (progress = new UI.ProgressDialog())
                            {
                                progress.SetMaximum(pages.Count);
                                progress.Show(owner);

                                await ApplyNumbering(
                                    pages, index, pages[0].Level,
                                    dialog.NumericNumbering, string.Empty);

                                progress.Close();
                            }

                            logger.StopClock();
                            logger.WriteTime("numbered pages");
                        }
                    }
                }
            }
        }
Exemple #7
0
        private Dictionary <string, string> GetHyperlinks(
            UI.ProgressDialog progress, CancellationToken token)
        {
            var catalog = fullCatalog ? OneNote.Scope.Notebooks : scope;

            return(one.BuildHyperlinkCache(catalog, token,
                                           (count) =>
            {
                progress.SetMaximum(count);
                progress.SetMessage($"Scanning {count} page references");
            },
                                           () =>
            {
                progress.Increment();
            }));
        }
Exemple #8
0
        private async Task <Dictionary <string, OneNote.HyperlinkInfo> > GetHyperlinks(
            UI.ProgressDialog progress, CancellationToken token)
        {
            var catalog = fullCatalog ? OneNote.Scope.Notebooks : scope;

            return(await one.BuildHyperlinkMap(catalog, token,
                                               async (count) =>
            {
                progress.SetMaximum(count);
                progress.SetMessage($"Scanning {count} page references");
                await Task.Yield();
            },
                                               async() =>
            {
                progress.Increment();
                await Task.Yield();
            }));
        }
Exemple #9
0
        public async Task IndexPages(List <string> pageIds)
        {
            string indexId = null;

            using (var progress = new UI.ProgressDialog())
            {
                progress.SetMaximum(pageIds.Count);
                progress.Show(owner);

                // create a new page to get a new ID
                one.CreatePage(sectionId, out indexId);
                var indexPage = one.GetPage(indexId);

                indexPage.Title = "Page Index";

                var container = indexPage.EnsureContentContainer();

                foreach (var pageId in pageIds)
                {
                    // get the page to copy
                    var page = one.GetPage(pageId);
                    var ns   = page.Namespace;

                    progress.SetMessage(page.Title);
                    progress.Increment();

                    var link = one.GetHyperlink(page.PageId, string.Empty);

                    container.Add(new XElement(ns + "OE",
                                               new XElement(ns + "T",
                                                            new XCData($"<a href=\"{link}\">{page.Title}</a>"))
                                               ));
                }

                await one.Update(indexPage);
            }

            // navigate after progress dialog is closed otherwise it will hang!
            if (indexId != null)
            {
                await one.NavigateTo(indexId);
            }
        }
Exemple #10
0
        public async Task BuildHyperlinkMap(
            OneNote.Scope scope, UI.ProgressDialog progress, CancellationToken token)
        {
            logger.WriteLine("building hyperlink map");

            map = await one.BuildHyperlinkMap(
                scope,
                token,
                async (count) =>
            {
                progress.SetMaximum(count);
                progress.SetMessage($"Scanning {count} page references");
                await Task.Yield();
            },
                async() =>
            {
                progress.Increment();
                await Task.Yield();
            });
        }
Exemple #11
0
        // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
        // Our trusty little worker

        private bool RunBackgroundTask(string path, Action action)
        {
            using (var source = new CancellationTokenSource())
            {
                using (progressDialog = new UI.ProgressDialog(source))
                {
                    progressDialog.SetMaximum(MaxWait);
                    progressDialog.SetMessage($"Importing {path}...");

                    try
                    {
                        // process should run in an STA thread otherwise it will conflict with
                        // the OneNote MTA thread environment
                        var thread = new Thread(() =>
                        {
                            action();
                        });

                        thread.SetApartmentState(ApartmentState.STA);
                        thread.IsBackground = true;
                        thread.Start();

                        progressDialog.StartTimer();
                        var result = progressDialog.ShowDialog(owner);

                        if (result == DialogResult.Cancel)
                        {
                            logger.WriteLine("clicked cancel");
                            thread.Abort();
                            return(false);
                        }
                    }
                    catch (Exception exc)
                    {
                        logger.WriteLine("error importing", exc);
                    }
                }
            }

            return(true);
        }
Exemple #12
0
        public async Task CopyPages(List <string> pageIds)
        {
            string lastId = null;

            using (var progress = new UI.ProgressDialog())
            {
                progress.SetMaximum(pageIds.Count);
                progress.Show(owner);

                foreach (var pageId in pageIds)
                {
                    if (one.GetParent(pageId) == sectionId)
                    {
                        continue;
                    }

                    // get the page to copy
                    var page = one.GetPage(pageId);
                    progress.SetMessage(page.Title);

                    // create a new page to get a new ID
                    one.CreatePage(sectionId, out var newPageId);

                    // set the page ID to the new page's ID
                    page.Root.Attribute("ID").Value = newPageId;
                    // remove all objectID values and let OneNote generate new IDs
                    page.Root.Descendants().Attributes("objectID").Remove();
                    await one.Update(page);

                    lastId = newPageId;

                    progress.Increment();
                }
            }

            // navigate after progress dialog is closed otherwise it will hang!
            if (lastId != null)
            {
                await one.NavigateTo(lastId);
            }
        }
        private async Task Toggle(bool pageOnly, bool showTimestamps)
        {
            using (var one = new OneNote())
            {
                if (pageOnly)
                {
                    var page = one.GetPage();
                    await SetTimestampVisibility(one, page, showTimestamps);
                }
                else
                {
                    var section = one.GetSection();
                    if (section != null)
                    {
                        var ns = one.GetNamespace(section);

                        var pageIds = section.Elements(ns + "Page")
                                      .Select(e => e.Attribute("ID").Value)
                                      .ToList();

                        using (var progress = new UI.ProgressDialog())
                        {
                            progress.SetMaximum(pageIds.Count);
                            progress.Show(owner);

                            foreach (var pageId in pageIds)
                            {
                                var page = one.GetPage(pageId, OneNote.PageDetail.Basic);
                                var name = page.Root.Attribute("name").Value;

                                progress.SetMessage(name);
                                progress.Increment();

                                await SetTimestampVisibility(one, page, showTimestamps);
                            }
                        }
                    }
                }
            }
        }
Exemple #14
0
        public override async Task Execute(params object[] args)
        {
            using (one = new OneNote())
            {
                var section = one.GetSection();
                var ns      = one.GetNamespace(section);

                var infos = section.Elements(ns + "Page")
                            .Select(e => new PageInfo
                {
                    ID   = e.Attribute("ID").Value,
                    Name = e.Attribute("name").Value,
                    Date = e.Attribute("dateTime").Value
                })
                            .ToList();

                if (infos?.Count > 0)
                {
                    logger.StartClock();

                    using (progress = new UI.ProgressDialog())
                    {
                        progress.SetMaximum(infos.Count);
                        progress.Show(owner);

                        foreach (var info in infos)
                        {
                            progress.SetMessage(info.Name);
                            await StampPage(info);
                        }

                        progress.Close();
                    }

                    logger.StopClock();
                    logger.WriteTime("datestamp pages");
                }
            }
        }
Exemple #15
0
        private void ReportPages(XElement container, XElement section, string folderPath, string skipId)
        {
            var name  = section.Attribute("name").Value;
            var title = folderPath == null ? name : Path.Combine(folderPath, name);

            progress.SetMessage($"{title} pages...");

            container.Add(new Paragraph($"{title} Section Pages").SetQuickStyle(heading1Index));
            if (!shownPageSummary)
            {
                container.Add(new Paragraph(Resx.AnalyzeCommand_PageSummary));
                shownPageSummary = true;
            }
            container.Add(new Paragraph(string.Empty));

            var table = new Table(ns, 0, 1)
            {
                HasHeaderRow   = true,
                BordersVisible = true
            };

            table.SetColumnWidth(0, 450);

            var pages = section.Elements(ns + "Page")
                        .Where(e => e.Attribute("ID").Value != skipId);

            progress.SetMaximum(pages.Count());

            foreach (var page in pages)
            {
                ReportPage(table, page.Attribute("ID").Value);
            }

            container.Add(
                new Paragraph(table.Root),
                new Paragraph(string.Empty)
                );
        }
Exemple #16
0
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        // Invoked by the ProgressDialog OnShown callback
        private async Task Execute(UI.ProgressDialog progress, CancellationToken token)
        {
            logger.Start();
            logger.StartClock();

            archivist = new Archivist(one, zipPath);
            await archivist.BuildHyperlinkMap(
                bookScope?OneNote.Scope.Sections : OneNote.Scope.Pages,
                progress,
                token);

            // use this temp folder as a sandbox for each page
            var t = Path.GetTempFileName();

            tempdir = Path.Combine(Path.GetDirectoryName(t), Path.GetFileNameWithoutExtension(t));
            PathFactory.EnsurePathExists(tempdir);
            logger.WriteLine($"building archive {zipPath}");

            progress.SetMaximum(totalCount);
            progress.SetMessage($"Archiving {totalCount} pages");

            using (var stream = new FileStream(zipPath, FileMode.Create))
            {
                using (archive = new ZipArchive(stream, ZipArchiveMode.Create))
                {
                    await Archive(progress, hierarchy, hierarchy.Attribute("name").Value);
                }
            }

            Directory.Delete(tempdir, true);

            progress.Close();
            UIHelper.ShowMessage(string.Format(Resx.ArchiveCommand_archived, pageCount, zipPath));

            logger.WriteTime("archive complete");
            logger.End();
        }
Exemple #17
0
        private void Export(List <string> pageIDs)
        {
            OneNote.ExportFormat format;
            string path;
            bool   withAttachments;
            bool   useUnderscores;

            // dialog...

            using (var dialog = new ExportDialog(pageIDs.Count))
            {
                if (dialog.ShowDialog(owner) != DialogResult.OK)
                {
                    return;
                }

                path            = dialog.FolderPath;
                format          = dialog.Format;
                withAttachments = dialog.WithAttachments;
                useUnderscores  = dialog.UseUnderscores;
            }

            // prepare...

            string ext = null;

            switch (format)
            {
            case OneNote.ExportFormat.HTML: ext = ".htm"; break;

            case OneNote.ExportFormat.PDF: ext = ".pdf"; break;

            case OneNote.ExportFormat.Word: ext = ".docx"; break;

            case OneNote.ExportFormat.XML: ext = ".xml"; break;

            case OneNote.ExportFormat.Markdown: ext = ".md"; break;

            case OneNote.ExportFormat.OneNote: ext = ".one"; break;
            }

            // export...

            using (var progress = new UI.ProgressDialog())
            {
                progress.SetMaximum(pageIDs.Count);
                progress.Show(owner);

                var archivist = new Archivist(one);

                foreach (var pageID in pageIDs)
                {
                    var page = one.GetPage(pageID, OneNote.PageDetail.BinaryData);

                    var title = useUnderscores
                                                ? PathFactory.CleanFileName(page.Title).Replace(' ', '_')
                                                : page.Title;

                    var filename = Path.Combine(path, title + ext);

                    progress.SetMessage(filename);
                    progress.Increment();

                    if (format == OneNote.ExportFormat.HTML)
                    {
                        if (withAttachments)
                        {
                            archivist.ExportHTML(page, ref filename);
                        }
                        else
                        {
                            archivist.Export(page.PageId, filename, OneNote.ExportFormat.HTML);
                        }
                    }
                    else if (format == OneNote.ExportFormat.XML)
                    {
                        archivist.ExportXML(page.Root, filename, withAttachments);
                    }
                    else if (format == OneNote.ExportFormat.Markdown)
                    {
                        archivist.ExportMarkdown(page, filename, withAttachments);
                    }
                    else
                    {
                        archivist.Export(page.PageId, filename, format, withAttachments);
                    }
                }
            }

            SaveDefaultPath(path);

            UIHelper.ShowMessage(string.Format(Resx.SaveAsMany_Success, pageIDs.Count, path));
        }
Exemple #18
0
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        // Invoked by the ProgressDialog OnShown callback
        private async Task Execute(UI.ProgressDialog progress, CancellationToken token)
        {
            logger.Start();
            logger.StartClock();

            using (one = new OneNote())
            {
                if (page == null)
                {
                    page = one.GetPage();
                    ns   = page.Namespace;
                }

                PageNamespace.Set(ns);

                var title = Unstamp(page.Title);

                string startId = string.Empty;
                switch (scope)
                {
                case OneNote.Scope.Sections: startId = one.CurrentNotebookId; break;

                case OneNote.Scope.Pages: startId = one.CurrentSectionId; break;
                }

                logger.WriteLine($"searching for '{title}'");
                var results = one.Search(startId, title, unindexed);

                if (token.IsCancellationRequested)
                {
                    logger.WriteLine("cancelled");
                    return;
                }

                //logger.WriteLine(results);

                var referals = FlattenPages(results, page.PageId);

                var total = referals.Count();
                if (total == 0)
                {
                    UIHelper.ShowInfo(Resx.LinkReferencesCommand_noref);
                    return;
                }

                // initialize search-and-replace editor...

                var whatText = $@"\b{SearchAndReplaceEditor.EscapeEscapes(title)}\b";
                var pageLink = one.GetHyperlink(page.PageId, string.Empty);

                var withElement = new XElement("A",
                                               new XAttribute("href", pageLink),
                                               page.Title
                                               );

                var editor = new SearchAndReplaceEditor(whatText, withElement,
                                                        useRegex: true,
                                                        caseSensitive: false
                                                        );

                // process pages...

                progress.SetMaximum(total);
                progress.SetMessage($"Linking for {total} pages");

                var updates = 0;
                foreach (var referal in referals)
                {
                    progress.Increment();
                    progress.SetMessage(referal.Attribute(NameAttr).Value);

                    var refpage = one.GetPage(referal.Attribute("ID").Value, OneNote.PageDetail.Basic);

                    logger.WriteLine($"searching for '{whatText}' on {refpage.Title}");

                    var count = editor.SearchAndReplace(refpage);
                    if (count > 0)
                    {
                        await one.Update(refpage);

                        referal.SetAttributeValue(LinkedAttr, "true");
                        referal.SetAttributeValue(SynopsisAttr, GetSynopsis(refpage));
                        updates++;
                    }
                    else
                    {
                        logger.WriteLine($"search not found on {referal.Attribute(NameAttr).Value}");
                    }

                    if (token.IsCancellationRequested)
                    {
                        logger.WriteLine("cancelled");
                        break;
                    }
                }

                if (updates > 0)
                {
                    // even if cancellation is request, must update page with referals that were
                    // modified, otherwise, there will be referal pages that link to this page
                    // without this page referring back!

                    AppendReferalBlock(page, referals);
                    await one.Update(page);
                }
            }

            logger.WriteTime("linking complete");
            logger.End();
        }
Exemple #19
0
        public async Task MovePages(List <string> pageIds)
        {
            var sections = new Dictionary <string, XElement>();
            var section  = one.GetSection(sectionId);
            var ns       = one.GetNamespace(section);

            var updated = false;

            using (var progress = new UI.ProgressDialog())
            {
                progress.SetMaximum(pageIds.Count);
                progress.Show(owner);

                foreach (var pageId in pageIds)
                {
                    // find the section that currently owns the page
                    var parentId = one.GetParent(pageId);
                    if (parentId == sectionId)
                    {
                        continue;
                    }

                    // load the owning section
                    XElement parent;
                    if (sections.ContainsKey(parentId))
                    {
                        parent = sections[parentId];
                    }
                    else
                    {
                        parent = one.GetSection(parentId);
                        sections.Add(parentId, parent);
                    }

                    // get the Page reference within the owing section
                    var element = parent.Elements(ns + "Page")
                                  .FirstOrDefault(e => e.Attribute("ID").Value == pageId);

                    if (element != null)
                    {
                        progress.SetMessage(element.Attribute("name").Value);

                        // remove page from current owner
                        element.Remove();

                        // remove misc attributes; OneNote will recreate them
                        element.Attributes()
                        .Where(a => a.Name != "ID" && a.Name != "name")
                        .Remove();

                        // add page to target section
                        section.Add(element);

                        updated = true;
                    }

                    progress.Increment();
                }
            }

            // updated at least one
            if (updated)
            {
                // update each source section
                foreach (var s in sections.Values)
                {
                    one.UpdateHierarchy(s);
                }

                sections.Clear();

                // update target section
                one.UpdateHierarchy(section);

                // navigate after progress dialog is closed otherwise it will hang!
                await one.NavigateTo(sectionId);
            }
        }
Exemple #20
0
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        // Invoked by the ProgressDialog OnShown callback
        private async Task Execute(UI.ProgressDialog progress, CancellationToken token)
        {
            logger.Start();
            logger.StartClock();

            using (one = new OneNote())
            {
                var hierarchy = GetHierarchy();

                if (token.IsCancellationRequested)
                {
                    logger.WriteLine("cancelled");
                    return;
                }

                try
                {
                    var hyperlinks = await GetHyperlinks(progress, token);

                    if (token.IsCancellationRequested)
                    {
                        logger.WriteLine("cancelled");
                        return;
                    }

                    var elements = hierarchy.Descendants(ns + "Page").ToList();
                    var titles   = new Dictionary <string, string>();

                    logger.WriteLine($"building map for {elements.Count} pages");
                    progress.SetMaximum(elements.Count);
                    progress.SetMessage($"Building map for {elements.Count} pages");

                    foreach (var element in elements)
                    {
                        progress.Increment();

                        if (token.IsCancellationRequested)
                        {
                            return;
                        }

                        var parentId = element.Attribute("ID").Value;
                        var xml      = one.GetPageXml(parentId);
                        var matches  = regex.Matches(xml);

                        if (matches.Count == 0)
                        {
                            element.Remove();
                            continue;
                        }

                        var parent = new Page(XElement.Parse(xml));

                        var name = element.Parent.Attribute("name").Value;
                        progress.SetMessage($"Scanning {name}/{parent.Title}");

                        // prevent duplicates
                        var refs = new List <string>();

                        foreach (Match match in matches)
                        {
                            var pid = match.Groups[1].Value;
                            if (refs.Contains(pid))
                            {
                                // already captured this pid
                                continue;
                            }

                            if (!hyperlinks.ContainsKey(pid))
                            {
                                logger.WriteLine($"not found in scope: {pid} on {name}/{parent.Title}");
                                continue;
                            }

                            var hyperlink = hyperlinks[pid];
                            if (hyperlink.PageID != parentId)
                            {
                                string title;
                                if (titles.ContainsKey(hyperlink.PageID))
                                {
                                    title = titles[hyperlink.PageID];
                                }
                                else
                                {
                                    var p = one.GetPage(hyperlink.PageID, OneNote.PageDetail.Basic);
                                    title = p.Title;
                                    titles.Add(hyperlink.PageID, title);
                                }

                                element.Add(new XElement("Ref",
                                                         new XAttribute("title", title),
                                                         new XAttribute("ID", hyperlink.PageID)
                                                         ));

                                //logger.WriteLine($" - {title}");

                                refs.Add(pid);
                            }
                        }
                    }

                    if (titles.Count == 0)
                    {
                        UIHelper.ShowMessage("No linked pages were found");
                        return;
                    }

                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    Prune(hierarchy);
                    await BuildMapPage(hierarchy);
                }
                catch (Exception exc)
                {
                    logger.WriteLine(exc);
                }
            }

            logger.WriteTime("map complete");
            logger.End();
        }
        private async Task Callback(string targetId)
        {
            if (string.IsNullOrEmpty(targetId))
            {
                // cancelled
                return;
            }

            logger.Start($"..target folder {targetId}");

            try
            {
                using (var one = new OneNote())
                {
                    // user might choose a sectiongroup or a notebook; GetSection will get either
                    var target = one.GetSection(targetId);
                    if (target == null)
                    {
                        logger.WriteLine("invalid target section");
                        return;
                    }

                    // source folder will be in current notebook
                    var notebook = await one.GetNotebook(OneNote.Scope.Pages);

                    var ns = one.GetNamespace(notebook);

                    // use current page to ascend back to closest folder to handle nesting...
                    var element = notebook.Descendants(ns + "Page")
                                  .FirstOrDefault(e => e.Attribute("ID").Value == one.CurrentPageId);

                    var folder = element.FirstAncestor(ns + "SectionGroup");
                    if (folder == null)
                    {
                        logger.WriteLine("error finding ancestor folder");
                        return;
                    }

                    if (folder.DescendantsAndSelf().Any(e => e.Attribute("ID").Value == targetId))
                    {
                        logger.WriteLine("cannot copy a folder into itself or one of its children");

                        MessageBox.Show(
                            Resx.CopyFolderCommand_InvalidTarget,
                            Resx.OneMoreTab_Label,
                            MessageBoxButtons.OK, MessageBoxIcon.Information,
                            MessageBoxDefaultButton.Button1,
                            MessageBoxOptions.DefaultDesktopOnly);

                        return;
                    }

                    logger.WriteLine(
                        $"copying folder {folder.Attribute("name").Value} " +
                        $"to {target.Attribute("name").Value}");

                    // clone structure of folder; this does not assign ID values
                    var clone = CloneFolder(folder, ns);

                    // update target so OneNote will apply new ID values
                    target.Add(clone);
                    one.UpdateHierarchy(target);

                    // re-fetch target to find newly assigned ID values
                    var upTarget = one.GetSection(targetId);

                    var cloneID = upTarget.Elements()
                                  .Where(e => !e.Attributes().Any(a => a.Name == "isRecycleBin"))
                                  .Select(e => e.Attribute("ID").Value)
                                  .Except(
                        target.Elements()
                        .Where(e => e.Attributes().Any(a => a.Name == "ID") &&
                               !e.Attributes().Any(a => a.Name == "isRecycleBin"))
                        .Select(e => e.Attribute("ID").Value)
                        ).FirstOrDefault();

                    clone = upTarget.Elements().FirstOrDefault(e => e.Attribute("ID").Value == cloneID);

                    using (progress = new UI.ProgressDialog())
                    {
                        progress.SetMaximum(folder.Descendants(ns + "Page").Count());
                        progress.Show(owner);

                        // now with a new SectionGroup with a valid ID, copy all pages into it
                        await CopyPages(folder, clone, one, ns);
                    }
                }
            }
            catch (Exception exc)
            {
                logger.WriteLine(exc);
            }
            finally
            {
                logger.End();
            }
        }
Exemple #22
0
        public override async Task Execute(params object[] args)
        {
            using (one = new OneNote())
            {
                (backupPath, defaultPath, _) = one.GetFolders();

                if (!Directory.Exists(backupPath))
                {
                    UIHelper.ShowError(owner, Resx.AnalyzeCommand_NoBackups);
                    return;
                }

                using (var dialog = new AnalyzeDialog())
                {
                    if (dialog.ShowDialog(owner) != DialogResult.OK)
                    {
                        return;
                    }

                    showNotebookSummary = dialog.IncludeNotebookSummary;
                    showSectionSummary  = dialog.IncludeSectionSummary;
                    pageDetail          = dialog.Detail;
                    thumbnailSize       = dialog.ThumbnailSize;
                }

                one.CreatePage(one.CurrentSectionId, out var pageId);
                var page = one.GetPage(pageId);
                page.Title = Resx.AnalyzeCommand_Title;
                page.SetMeta(MetaNames.AnalysisReport, "true");

                ns = page.Namespace;
                PageNamespace.Set(ns);

                heading1Index = page.GetQuickStyle(Styles.StandardStyles.Heading1).Index;
                heading2Index = page.GetQuickStyle(Styles.StandardStyles.Heading2).Index;

                using (progress = new UI.ProgressDialog())
                {
                    progress.SetMaximum(5);
                    progress.Show(owner);

                    var container = page.EnsureContentContainer();
                    var notebooks = await one.GetNotebooks();

                    var prev = false;

                    if (showNotebookSummary)
                    {
                        ReportNotebooks(container, notebooks);
                        ReportOrphans(container, notebooks);
                        ReportCache(container);
                        prev = true;
                    }

                    if (showSectionSummary)
                    {
                        if (prev)
                        {
                            WriteHorizontalLine(page, container);
                        }

                        await ReportSections(container, notebooks);

                        prev = true;
                    }

                    if (pageDetail == AnalysisDetail.Current)
                    {
                        if (prev)
                        {
                            WriteHorizontalLine(page, container);
                        }

                        ReportPages(container, one.GetSection(), null, pageId);
                    }
                    else if (pageDetail == AnalysisDetail.All)
                    {
                        if (prev)
                        {
                            WriteHorizontalLine(page, container);
                        }

                        ReportAllPages(container, await one.GetNotebook(), null, pageId);
                    }

                    progress.SetMessage("Updating report...");
                    await one.Update(page);
                }

                await one.NavigateTo(pageId);
            }
        }