Example #1
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();
            }
        }
Example #2
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();
        }
Example #3
0
        public override async Task Execute(params object[] args)
        {
            if (args.Length > 0 && args[0] is string refresh && refresh == "refresh")
            {
                synopses   = args.Any(a => a as string == "synopsis");
                unindexed  = args.Any(a => a as string == "unindexed");
                refreshing = Refresh();
            }

            if (!refreshing)
            {
                using (var dialog = new LinkDialog())
                {
                    if (dialog.ShowDialog(owner) != System.Windows.Forms.DialogResult.OK)
                    {
                        return;
                    }

                    scope     = dialog.Scope;
                    synopses  = dialog.Synopsis;
                    unindexed = dialog.Unindexed;
                }
            }

            var progressDialog = new UI.ProgressDialog(Execute);
            await progressDialog.RunModeless();
        }
Example #4
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));
        }
Example #5
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");
                        }
                    }
                }
            }
        }
Example #8
0
        private async Task DownloadSelectedSubpages(
            UI.ProgressDialog progress, CancellationToken token)
        {
            var updated = false;

            foreach (var selection in selections)
            {
                progress.SetMessage(selection.Address);
                //logger.WriteLine($"fetching {selection.Address}");

                var page = await importer
                           .ImportSubpage(one, parentPage, new Uri(selection.Address), token);

                if (page != null)
                {
                    var pageUri = one.GetHyperlink(page.PageId, string.Empty);

                    // redirect primary reference on parent page to our new subpage
                    PatchCData(selection.CData, selection.Address, selection.Text, pageUri);

                    // redirect duplicate references on parent page
                    if (selection.RefCount > 1)
                    {
                        var ns    = parentPage.Namespace;
                        var regex = new Regex($@"<a\s+href=""{Regex.Escape(selection.Address)}""");

                        var cdatas = parentPage.Root.Elements(ns + "Outline")
                                     .DescendantNodes().OfType <XCData>()
                                     .Where(d => d != selection.CData && regex.IsMatch(d.Value));

                        foreach (var cdata in cdatas)
                        {
                            PatchCData(cdata, selection.Address, selection.Text, pageUri);
                        }
                    }

                    updated = true;
                }

                progress.Increment();
            }

            if (updated)
            {
                await one.Update(parentPage);

                await one.NavigateTo(parentPage.PageId);
            }
        }
Example #9
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();
            }));
        }
Example #10
0
        public override async Task Execute(params object[] args)
        {
            using (var dialog = new MapDialog())
            {
                if (dialog.ShowDialog(owner) != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }

                scope       = dialog.Scope;
                fullCatalog = dialog.FullCatalog;
            }

            var progressDialog = new UI.ProgressDialog(Execute);
            await progressDialog.RunModeless();
        }
Example #11
0
        public override async Task Execute(params object[] args)
        {
            using (var dialog = new RefreshPageLinksDialog())
            {
                if (dialog.ShowDialog(owner) != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }

                scope = dialog.Scope;
            }

            using (var one = new OneNote(out var page, out _))
            {
                // cleaned page title
                title = Unstamp(page.Title);

                // page's hyperlink section-id + page-id
                var uri   = one.GetHyperlink(page.PageId, string.Empty);
                var match = Regex.Match(uri, "section-id={[0-9A-F-]+}&page-id={[0-9A-F-]+}&");
                if (match.Success)
                {
                    // ampersands aren't escaped in hyperlinks but they will be in XML
                    keys = match.Groups[0].Value.Replace("&", "&amp;");
                }
                else
                {
                    logger.WriteLine($"error finding section/page IDs in page hyperlink");
                    return;
                }
            }

            var progressDialog = new UI.ProgressDialog(Execute);
            await progressDialog.RunModeless((s, a) =>
            {
                if (updates > 0)
                {
                    UIHelper.ShowInfo(string.Format(Resx.RefreshPageLinksCommand_updated, updates));
                }
                else
                {
                    UIHelper.ShowInfo(Resx.RefreshPageLinksCommand_none);
                }
            });
        }
Example #12
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();
            }));
        }
Example #13
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);
            }
        }
Example #14
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();
            });
        }
Example #15
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);
            }
        }
Example #16
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);
        }
Example #17
0
        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);
                            }
                        }
                    }
                }
            }
        }
Example #18
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");
                }
            }
        }
Example #19
0
        private async Task Archive(UI.ProgressDialog progress, XElement root, string path)
        {
            foreach (var element in root.Elements())
            {
                if (element.Name.LocalName == "Page")
                {
                    var page = one.GetPage(
                        element.Attribute("ID").Value, OneNote.PageDetail.BinaryData);

                    progress.SetMessage($"Archiving {page.Title}");
                    progress.Increment();

                    await ArchivePage(element, page, path);
                }
                else
                {
                    // SectionGroup or Section

                    element.ReadAttributeValue("locked", out bool locked, false);
                    if (locked)
                    {
                        continue;
                    }

                    element.ReadAttributeValue("isRecycleBin", out bool recycle, false);
                    if (recycle)
                    {
                        continue;
                    }

                    // append name of Section/Group to path to build zip folder path
                    var name = element.Attribute("name").Value;

                    await Archive(progress, element, Path.Combine(path, name));
                }
            }
        }
Example #20
0
        public override async Task Execute(params object[] args)
        {
            var scope = args[0] as string;

            using (one = new OneNote())
            {
                bookScope = scope == "notebook";

                hierarchy = bookScope
                                        ? one.GetNotebook(one.CurrentNotebookId, OneNote.Scope.Pages)
                                        : one.GetSection(one.CurrentSectionId);

                var ns = one.GetNamespace(hierarchy);

                totalCount = hierarchy.Descendants(ns + "Page").Count();
                if (totalCount == 0)
                {
                    UIHelper.ShowMessage(Resx.ArchiveCommand_noPages);
                    return;
                }

                var topName = hierarchy.Attribute("name").Value;
                zipPath = await SingleThreaded.Invoke(() =>
                {
                    // OpenFileDialog must run in STA thread
                    return(ChooseLocation(topName));
                });

                if (zipPath == null)
                {
                    return;
                }

                var progressDialog = new UI.ProgressDialog(Execute);
                await progressDialog.RunModeless();
            }
        }
Example #21
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();
        }
Example #22
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();
        }
Example #23
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));
        }
Example #24
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();
        }
Example #25
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);
            }
        }
Example #26
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);
            }
        }
Example #27
0
        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();
            }
        }