public override void Execute(params object[] args)
        {
            int  year;
            int  month;
            bool large;

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

                year  = dialog.Year;
                month = dialog.Month;
                large = dialog.Large;
            }

            using (var one = new OneNote(out page, out ns))
            {
                var root = MakeCalendar(year, month, large);
                page.AddNextParagraph(root);

                var header = MakeHeader(year, month);
                page.AddNextParagraph(header);

                one.Update(page);
            }
        }
Example #2
0
        private void CopyPages(string sectionId, OneNote one)
        {
            using (var progress = new 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();
                    one.Update(page);

                    progress.Increment();
                }
            }
        }
Example #3
0
        private void WordImporter(string filepath, bool append)
        {
            using (var word = new Word())
            {
                var html = word.ConvertFileToHtml(filepath);


                if (append)
                {
                    using (var one = new OneNote(out var page, out _))
                    {
                        page.AddHtmlContent(html);
                        one.Update(page);
                    }
                }
                else
                {
                    using (var one = new OneNote())
                    {
                        one.CreatePage(one.CurrentSectionId, out var pageId);
                        var page = one.GetPage(pageId);

                        page.Title = Path.GetFileName(filepath);
                        page.AddHtmlContent(html);
                        one.Update(page);
                        one.NavigateTo(page.PageId);
                    }
                }
            }
        }
Example #4
0
        /// <summary>
        /// Adds a new footnote to the page, possibly renumbering existing footnotes
        /// to ensure all foonotes are in sequential order from top to bottom.
        /// </summary>
        public async Task AddFootnote()
        {
            // find the selected run, the insertion point
            var element = page.Root.Elements(ns + "Outline")
                          .Where(e => e.Attributes("selected").Any())
                          .Descendants(ns + "T")
                          .LastOrDefault(e => e.Attribute("selected")?.Value == "all");

            if (element == null)
            {
                UIHelper.ShowError(one.Window, Resx.Error_BodyContext);
                return;
            }

            // containing paragraph of selected run
            var parent = element.Parent;

            // ensure RTL is set appropriately
            var lang = parent.Attribute("lang")?.Value;

            if (!string.IsNullOrEmpty(lang))
            {
                var culture = new CultureInfo(lang);
                if (culture.TextInfo.IsRightToLeft)
                {
                    parent.SetAttributeValue("RTL", "true");
                }
            }

            // rtl paragraph, rtl page, or rtl Windows language
            rightToLeft = parent.Attribute("RTL")?.Value == "true" || page.IsRightToLeft();

            if (!EnsureFootnoteFooter())
            {
                UIHelper.ShowError(one.Window, Resx.Error_BodyContext);
                return;
            }

            var label = await WriteFootnoteText(parent.Attribute("objectID").Value);

            if (WriteFootnoteRef(label))
            {
                await RefreshLabels();

                await one.Update(page);
            }
        }
Example #5
0
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        #region InsertPagesTables
        private void InsertPagesTable(OneNote one)
        {
            var section   = one.GetSection();
            var sectionId = section.Attribute("ID").Value;

            one.CreatePage(sectionId, out var pageId);

            var page = one.GetPage(pageId);
            var ns   = page.Namespace;

            page.Title = string.Format(Resx.InsertTocCommand_TOCSections, section.Attribute("name").Value);

            var container = new XElement(ns + "OEChildren");

            var elements = section.Elements(ns + "Page");

            foreach (var element in elements)
            {
                var text  = new StringBuilder();
                var level = int.Parse(element.Attribute("pageLevel").Value);
                while (level > 0)
                {
                    text.Append(". . ");
                    level--;
                }

                var link = one.GetHyperlink(element.Attribute("ID").Value, string.Empty);

                var name = element.Attribute("name").Value;
                text.Append($"<a href=\"{link}\">{name}</a>");

                container.Add(new XElement(ns + "OE",
                                           new XElement(ns + "T", new XCData(text.ToString())
                                                        )));
            }

            var title = page.Root.Elements(ns + "Title").FirstOrDefault();

            title.AddAfterSelf(new XElement(ns + "Outline", container));
            one.Update(page);

            // move TOC page to top of section...

            // get current section again after new page is created
            section = one.GetSection();

            var entry = section.Elements(ns + "Page")
                        .FirstOrDefault(e => e.Attribute("ID").Value == pageId);

            entry.Remove();
            section.AddFirst(entry);
            one.UpdateHierarchy(section);

            one.NavigateTo(pageId);
        }
Example #6
0
        private void ResizeOne(XElement image)
        {
            var size   = image.Element(ns + "Size");
            int width  = (int)decimal.Parse(size.Attribute("width").Value, CultureInfo.InvariantCulture);
            int height = (int)decimal.Parse(size.Attribute("height").Value, CultureInfo.InvariantCulture);

            using (var dialog = new Dialogs.ResizeImagesDialog(width, height))
            {
                dialog.SetOriginalSize(GetOriginalSize(image, ns));

                var result = dialog.ShowDialog(owner);
                if (result == DialogResult.OK)
                {
                    size.Attribute("width").Value  = dialog.WidthPixels.ToString(CultureInfo.InvariantCulture);
                    size.Attribute("height").Value = dialog.HeightPixels.ToString(CultureInfo.InvariantCulture);

                    one.Update(page);
                }
            }
        }
Example #7
0
        public override void 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 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;

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

            logger.StopClock();
            logger.WriteTime("removed page numbering");
        }
Example #8
0
        /// <summary>
        /// Adds a new footnote to the page, possibly renumbering existing footnotes
        /// to ensure all foonotes are in sequential order from top to bottom.
        /// </summary>
        public void AddFootnote()
        {
            var element = page.Root.Elements(ns + "Outline")
                          .Where(e => e.Attributes("selected").Any())
                          .Descendants(ns + "T")
                          .LastOrDefault(e => e.Attribute("selected")?.Value == "all");

            if (element == null)
            {
                element = page.Root.Elements(ns + "Outline").LastOrDefault();
            }

            if (element == null)
            {
                logger.WriteLine($"{nameof(FootnoteEditor.AddFootnote)} could not find a selected outline");
                SystemSounds.Exclamation.Play();
                return;
            }

            // last selected paragraph OE
            element = element.Parent;

            if (!EnsureFootnoteFooter())
            {
                logger.WriteLine($"{nameof(FootnoteEditor.AddFootnote)} could not add footnote footer");
                SystemSounds.Exclamation.Play();
                return;
            }

            var label = WriteFootnoteText(element.Attribute("objectID").Value);

            if (WriteFootnoteRef(label))
            {
                RefreshLabels();

                one.Update(page);
            }
        }
Example #9
0
        private static void SetTimestampVisibility(OneNote one, Page page, bool visible)
        {
            var modified = false;
            var title    = page.Root.Element(page.Namespace + "Title");

            if (title != null)
            {
                modified |= SetTimestampAttribute(title, "showDate", visible);
                modified |= SetTimestampAttribute(title, "showTime", visible);

                if (modified)
                {
                    one.Update(page);
                }
            }
        }
Example #10
0
        private void CropImage(XElement element)
        {
            var data   = element.Element(ns + "Data");
            var binhex = Convert.FromBase64String(data.Value);

            using (var stream = new MemoryStream(binhex, 0, binhex.Length))
            {
                using (var image = Image.FromStream(stream))
                {
                    var size = element.Element(ns + "Size");
                    size.ReadAttributeValue("width", out float width, image.Width);
                    size.ReadAttributeValue("height", out float height, image.Height);

                    var scales = new SizeF(width / image.Width, height / image.Height);

                    using (var dialog = new CropImageDialog(image))
                    {
                        var result = dialog.ShowDialog(owner);
                        if (result == DialogResult.OK)
                        {
                            var bytes = (byte[])new ImageConverter()
                                        .ConvertTo(dialog.Image, typeof(byte[]));

                            data.Value = Convert.ToBase64String(bytes);

                            var setWidth  = (int)Math.Round(dialog.Image.Width * scales.Width);
                            var setHeight = (int)Math.Round(dialog.Image.Height * scales.Height);
#if Logging
                            logger.WriteLine(
                                $"DONE crop:{dialog.Image.Width}x{dialog.Image.Height} " +
                                $"scales:({scales.Width},{scales.Height}) " +
                                $"oldsize:{width}x{height} setsiz:{setWidth}x{setHeight}"
                                );
#endif
                            size.SetAttributeValue("width", $"{setWidth:0.0}");
                            size.SetAttributeValue("height", $"{setHeight:0.0}");
                            size.SetAttributeValue("isSetByUser", "true");

                            one.Update(page);
                        }
                    }
                }
            }
        }
Example #11
0
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        #region InsertSectionsTable
        private void InsertSectionsTable(OneNote one, bool includePages)
        {
            var section   = one.GetSection();
            var sectionId = section.Attribute("ID").Value;

            one.CreatePage(sectionId, out var pageId);

            var page = one.GetPage(pageId);
            var ns   = page.Namespace;

            var scope    = includePages ? OneNote.Scope.Pages : OneNote.Scope.Sections;
            var notebook = one.GetNotebook(scope);

            page.Title = string.Format(Resx.InsertTocCommand_TOCNotebook, notebook.Attribute("name").Value);

            var container = new XElement(ns + "OEChildren");

            BuildSectionTable(one, ns, container, notebook.Elements(), includePages, 1);

            var title = page.Root.Elements(ns + "Title").FirstOrDefault();

            title.AddAfterSelf(new XElement(ns + "Outline", container));
            one.Update(page);

            // move TOC page to top of section...

            // get current section again after new page is created
            section = one.GetSection();

            var entry = section.Elements(ns + "Page")
                        .FirstOrDefault(e => e.Attribute("ID").Value == pageId);

            entry.Remove();
            section.AddFirst(entry);
            one.UpdateHierarchy(section);

            one.NavigateTo(pageId);
        }
Example #12
0
        private void ApplyNumbering(
            List <PageBasics> pages, ref int index, int level, bool numeric, string prefix)
        {
            int counter = 1;

            while (index < pages.Count && pages[index].Level == level)
            {
                var page = one.GetPage(pages[index].ID, OneNote.PageDetail.Basic);

                var cdata = page.Root.Element(ns + "Title")
                            .Element(ns + "OE")
                            .Element(ns + "T")
                            .GetCData();

                progress.SetMessage(string.Format(Properties.Resources.NumberingPage_Message, pages[index].Name));
                progress.Increment();

                var text = cdata.Value;
                if (cleaner != null)
                {
                    cleaner.RemoveNumbering(cdata.Value, out text);
                }

                cdata.Value = BuildPrefix(counter, numeric, level, prefix) + " " + text;
                one.Update(page);

                index++;
                counter++;

                if (index < pages.Count && pages[index].Level > level)
                {
                    ApplyNumbering(
                        pages, ref index, pages[index].Level,
                        numeric, $"{prefix}{counter - 1}.");
                }
            }
        }
Example #13
0
        public override void Execute(params object[] args)
        {
            delta = (int)args[0];             // +/-1

            using (var one = new OneNote(out page, out ns))
            {
                if (page == null)
                {
                    return;
                }

                // determine if range is selected or entire page

                selected = page.Root.Element(ns + "Outline").Descendants(ns + "T")
                           .Where(e => e.Attributes("selected").Any(a => a.Value.Equals("all")))
                           .Any(e => e.GetCData().Value.Length > 0);

                var count = 0;

                if (selected)
                {
                    count += AlterSelections();
                }
                else
                {
                    count += AlterByName();
                    count += AlterElementsByValue();
                    count += AlterCDataByValue();
                }

                if (count > 0)
                {
                    one.Update(page);
                }
            }
        }
Example #14
0
        public override void Execute(params object[] args)
        {
            using (one = new OneNote(out var page, out var ns))
            {
                // Find first selected cell as anchor point to locate table into which
                // the formula should be inserted; By filtering on selected=all, we avoid
                // including the parent table of a selected nested table.

                var anchor = page.Root.Descendants(ns + "Cell")
                             // first dive down to find the selected T
                             .Elements(ns + "OEChildren").Elements(ns + "OE")
                             .Elements(ns + "T")
                             .Where(e => e.Attribute("selected")?.Value == "all")
                             // now move back up to the Cell
                             .Select(e => e.Parent.Parent.Parent)
                             .FirstOrDefault();

                if (anchor == null)
                {
                    UIHelper.ShowInfo(one.Window, Resx.FormulaCommand_SelectOne);
                    return;
                }

                var table = new Table(anchor.FirstAncestor(ns + "Table"));
                var cells = table.GetSelectedCells(out var range).ToList();

                if (range == TableSelectionRange.Rectangular)
                {
                    UIHelper.ShowInfo(one.Window, Resx.FormulaCommand_Linear);
                    return;
                }

                using (var dialog = new Dialogs.FormulaDialog())
                {
                    // display selected cell names
                    dialog.SetCellNames(
                        string.Join(", ", cells.Select(c => c.Coordinates)));                         // + $" ({rangeType})");

                    var cell = cells.First();

                    // display formula of first cell if any
                    var formula = new Formula(cell);
                    if (formula.Valid)
                    {
                        dialog.Format        = formula.Format;
                        dialog.Formula       = formula.Expression;
                        dialog.DecimalPlaces = formula.DecimalPlaces;
                    }

                    var tagIndex = page.GetTagDefIndex(BoltSymbol);
                    if (!string.IsNullOrEmpty(tagIndex))
                    {
                        if (cell.HasTag(tagIndex))
                        {
                            dialog.Tagged = true;
                        }
                    }

                    if (dialog.ShowDialog(owner) != DialogResult.OK)
                    {
                        return;
                    }

                    if (dialog.Tagged)
                    {
                        tagIndex = page.AddTagDef(BoltSymbol, Resx.AddFormulaCommand_Calculated);
                    }

                    StoreFormula(cells,
                                 dialog.Formula, dialog.Format, dialog.DecimalPlaces,
                                 range, tagIndex);

                    var processor = new Processor(table);
                    processor.Execute(cells);

                    one.Update(page);
                }
            }
        }
Example #15
0
        private void PowerPointImporter(string filepath, bool append, bool split)
        {
            string outpath;

            using (var powerpoint = new PowerPoint())
            {
                outpath = powerpoint.ConvertFileToImages(filepath);
            }

            if (outpath == null)
            {
                logger.WriteLine($"failed to create output path");
                return;
            }

            if (split)
            {
                using (var one = new OneNote())
                {
                    var section   = one.CreateSection(Path.GetFileNameWithoutExtension(filepath));
                    var sectionId = section.Attribute("ID").Value;
                    var ns        = one.GetNamespace(section);

                    one.NavigateTo(sectionId);

                    int i = 1;
                    foreach (var file in Directory.GetFiles(outpath, "*.jpg"))
                    {
                        one.CreatePage(sectionId, out var pageId);
                        var page = one.GetPage(pageId);
                        page.Title = $"Slide {i}";
                        var container = page.EnsureContentContainer();

                        LoadImage(container, ns, file);

                        one.Update(page);

                        i++;
                    }

                    logger.WriteLine("created section");
                }
            }
            else
            {
                using (var one = new OneNote())
                {
                    Page page;
                    if (append)
                    {
                        page = one.GetPage();
                    }
                    else
                    {
                        one.CreatePage(one.CurrentSectionId, out var pageId);
                        page       = one.GetPage(pageId);
                        page.Title = Path.GetFileName(filepath);
                    }

                    var container = page.EnsureContentContainer();

                    foreach (var file in Directory.GetFiles(outpath, "*.jpg"))
                    {
                        using (var image = Image.FromFile(file))
                        {
                            LoadImage(container, page.Namespace, file);
                        }
                    }

                    one.Update(page);

                    if (!append)
                    {
                        one.NavigateTo(page.PageId);
                    }
                }
            }

            try
            {
                Directory.Delete(outpath, true);
            }
            catch (Exception exc)
            {
                logger.WriteLine($"Error cleaning up {outpath}", exc);
            }
        }
Example #16
0
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        #region InsertHeadingsTable
        /// <summary>
        /// Inserts a table of contents at the top of the current page,
        /// of all headings on the page
        /// </summary>
        /// <param name="addTopLinks"></param>
        /// <param name="one"></param>
        private void InsertHeadingsTable(OneNote one, bool addTopLinks)
        {
            var page = one.GetPage();
            var ns   = page.Namespace;

            var headings = page.GetHeadings(one);

            var top = page.Root.Element(ns + "Outline")?.Element(ns + "OEChildren");

            if (top == null)
            {
                return;
            }

            var title = page.Root.Elements(ns + "Title").Elements(ns + "OE").FirstOrDefault();

            if (title == null)
            {
                return;
            }

            var titleLink     = one.GetHyperlink(page.PageId, title.Attribute("objectID").Value);
            var titleLinkText = $"<a href=\"{titleLink}\"><span style='font-style:italic'>{Resx.InsertTocCommand_Top}</span></a>";

            var dark      = page.GetPageColor(out _, out _).GetBrightness() < 0.5;
            var textColor = dark ? "#FFFFFF" : "#000000";

            var toc = new List <XElement>
            {
                // "Table of Contents"
                new XElement(ns + "OE",
                             new XAttribute("style", $"font-size:16.0pt;color:{textColor}"),
                             new XElement(ns + "T",
                                          new XCData($"<span style='font-weight:bold'>{Resx.InsertTocCommand_TOC}</span>")
                                          )
                             )
            };

            // use the minimum intent level
            var minlevel = headings.Min(e => e.Style.Index);

            foreach (var heading in headings)
            {
                var text  = new StringBuilder();
                var count = minlevel;
                while (count < heading.Style.Index)
                {
                    text.Append(". . ");
                    count++;
                }

                if (!string.IsNullOrEmpty(heading.Link))
                {
                    var linkColor = dark ? " style='color:#5B9BD5'" : string.Empty;
                    text.Append($"<a href=\"{heading.Link}\"{linkColor}>{heading.Text}</a>");
                }
                else
                {
                    text.Append(heading.Text);
                }

                toc.Add(new XElement(ns + "OE",
                                     new XAttribute("style", $"color:{textColor}"),
                                     new XElement(ns + "T", new XCData(text.ToString()))
                                     ));

                if (addTopLinks)
                {
                    var table = new Table(ns);
                    table.AddColumn(400, true);
                    table.AddColumn(100, true);
                    var row = table.AddRow();
                    row.Cells.ElementAt(0).SetContent(heading.Root);
                    row.Cells.ElementAt(1).SetContent(
                        new XElement(ns + "OE",
                                     new XAttribute("alignment", "right"),
                                     new XElement(ns + "T", new XCData(titleLinkText)))
                        );

                    // heading.Root is the OE
                    heading.Root.ReplaceNodes(table.Root);
                }
            }

            // empty line after the TOC
            toc.Add(new XElement(ns + "OE", new XElement(ns + "T", new XCData(string.Empty))));
            top.AddFirst(toc);

            one.Update(page);
        }
Example #17
0
        public override void Execute(params object[] args)
        {
            using (var one = new OneNote())
            {
                var section = one.GetSection();
                ns = one.GetNamespace(section);

                // find first selected - active page

                var active =
                    section.Elements(ns + "Page")
                    .FirstOrDefault(e => e.Attributes("isCurrentlyViewed").Any(a => a.Value.Equals("true")));

                if (active == null)
                {
                    UIHelper.ShowInfo(one.Window, "At least two pages must be selected to merge");
                    return;
                }

                var selections =
                    section.Elements(ns + "Page")
                    .Where(e =>
                           !e.Attributes("isCurrentlyViewed").Any() &&
                           e.Attributes("selected").Any(a => a.Value.Equals("all")));

                if (active == null)
                {
                    UIHelper.ShowInfo(one.Window, "At least two pages must be selected to merge");
                    return;
                }


                // get first selected (active) page and reference its quick styles, outline, size

                page = one.GetPage(active.Attribute("ID").Value);

                quickmap = page.GetQuickStyleMap();

                var offset = GetPageBottomOffset();

                // track running bottom as we add new outlines
                var maxOffset = offset;

                // find maximum z-offset
                var z = page.Root.Elements(ns + "Outline").Elements(ns + "Position")
                        .Attributes("z").Max(a => int.Parse(a.Value)) + 1;

                // merge each of the subsequently selected pages into the active page

                foreach (var selection in selections.ToList())
                {
                    var childPage = one.GetPage(selection.Attribute("ID").Value);

                    var map = page.MergeQuickStyles(childPage);

                    var childOutlines = childPage.Root.Elements(ns + "Outline");
                    if (childOutlines == null || !childOutlines.Any())
                    {
                        break;
                    }

                    var topOffset = childOutlines.Elements(ns + "Position")
                                    .Min(p => double.Parse(p.Attribute("y").Value, CultureInfo.InvariantCulture));

                    foreach (var childOutline in childOutlines)
                    {
                        // adjust position relative to new parent page outlines
                        var position = childOutline.Elements(ns + "Position").FirstOrDefault();
                        var y        = double.Parse(position.Attribute("y").Value, CultureInfo.InvariantCulture)
                                       - topOffset + offset + OutlineMargin;

                        position.Attribute("y").Value = y.ToString("#0.0", CultureInfo.InvariantCulture);

                        // keep track of lowest bottom
                        var size   = childOutline.Elements(ns + "Size").FirstOrDefault();
                        var bottom = y + double.Parse(size.Attribute("height").Value, CultureInfo.InvariantCulture);
                        if (bottom > maxOffset)
                        {
                            maxOffset = bottom;
                        }

                        position.Attribute("z").Value = z.ToString();
                        z++;

                        // remove its IDs so the page can apply its own
                        childOutline.Attributes("objectID").Remove();
                        childOutline.Descendants().Attributes("objectID").Remove();

                        page.ApplyStyleMapping(map, childOutline);

                        page.Root.Add(childOutline);
                    }

                    if (maxOffset > offset)
                    {
                        offset = maxOffset;
                    }
                }

                // update page and section hierarchy

                one.Update(page);

                foreach (var selection in selections)
                {
                    one.DeleteHierarchy(selection.Attribute("ID").Value);
                }
            }
        }