public override void Execute(params object[] args) { using (var one = new OneNote()) { var section = one.GetSection(); var ns = one.GetNamespace(section); var pageIDs = section.Elements(ns + "Page") .Where(e => e.Attribute("selected")?.Value == "all") .Select(e => e.Attribute("ID").Value) .ToList(); if (pageIDs.Count > 1) { ExportMany(one, pageIDs); } else { var page = one.GetPage(); ExportOne(one, page); } } }
private void Callback(string sectionId) { if (string.IsNullOrEmpty(sectionId)) { // cancelled return; } var action = copying ? "copying" : "moving"; logger.Start($"..{action} {pageIds.Count} pages"); try { using (var one = new OneNote()) { if (copying) { CopyPages(sectionId, one); } else { MovePages(sectionId, one); } one.NavigateTo(sectionId); } } catch (Exception exc) { logger.WriteLine(exc); } finally { logger.End(); } }
public void OnStartupComplete(ref Array custom) { var cude = DescribeCustom(custom); logger.WriteLine($"OnStartupComplete(custom[{cude}])"); try { using (var one = new OneNote()) { factory = new CommandFactory(logger, ribbon, trash, // looks complicated but necessary for this to work new Win32WindowHandle(new IntPtr((long)one.WindowHandle))); } // command listener for Refresh links new CommandService(factory).Startup(); // reminder task scanner new Commands.ReminderService().Startup(); // hotkeys RegisterHotkeys(); // activate enablers and update check Task.Run(async() => { await SetGeneralOptions(); }); logger.WriteLine($"ready"); } catch (Exception exc) { Logger.Current.WriteLine("error starting add-on", exc); UIHelper.ShowError(Properties.Resources.StartupFailureMessage); } logger.End(); }
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); } } }
public void AddFavorite() { XElement root; if (File.Exists(path)) { root = XElement.Load(path, LoadOptions.None); } else { root = MakeMenuRoot(); } using (var one = new OneNote()) { var info = one.GetPageInfo(); var name = EmojiDialog.RemoveEmojis(info.Name); if (name.Length > 50) { name = name.Substring(0, 50) + "..."; } // similar to mongo ObjectId, a random-enough identifier for our needs var id = ((DateTimeOffset.Now.ToUnixTimeSeconds() << 32) + new Random().Next()).ToString("x"); root.Add(new XElement(ns + "splitButton", new XAttribute("id", $"omFavorite{id}"), new XElement(ns + "button", new XAttribute("id", $"omFavoriteLink{id}"), new XAttribute("onAction", "NavigateToFavorite"), new XAttribute("imageMso", "FileLinksToFiles"), new XAttribute("label", name), new XAttribute("tag", info.Link), new XAttribute("screentip", info.Path) ), new XElement(ns + "menu", new XAttribute("id", $"omFavoriteMenu{id}"), new XElement(ns + "button", new XAttribute("id", $"omFavoriteRemoveButton{id}"), new XAttribute("onAction", "RemoveFavorite"), new XAttribute("label", "Remove this item"), new XAttribute("imageMso", "HyperlinkRemove"), new XAttribute("tag", $"omFavorite{id}") ) ) )); // sort by name/label var items = from e in root.Elements(ns + "splitButton") let key = e.Element(ns + "button").Attribute("label").Value orderby key select e; root = MakeMenuRoot(); foreach (var item in items) { root.Add(item); } logger.WriteLine($"Saving favorite '{info.Path}' ({info.Link})"); } try { PathFactory.EnsurePathExists(PathFactory.GetAppDataPath()); root.Save(path, SaveOptions.None); ribbon.InvalidateControl("ribFavoritesMenu"); } catch (Exception exc) { logger.WriteLine($"Cannot save {path}"); logger.WriteLine(exc); } }
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); } } }
private void MovePages(string sectionId, OneNote one) { var sections = new Dictionary <string, XElement>(); var section = one.GetSection(sectionId); var ns = one.GetNamespace(section); var updated = false; using (var progress = new 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); } }
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Pages private void SortPages(SortDialog.Sortings sorting, SortDialog.Directions direction) { #region Notes /* * <one:Page ID="" name="Notes" pageLevel="1" /> * * Pages within a section are stored as a flat list of elements with * indented pages indicated by pageLevel only - they are not recursive children. * So the code below must group child pages with their parent so all parents * can be sorted correctly. Children are not sorted. */ #endregion Notes logger.StartClock(); using (var one = new OneNote()) { var root = one.GetSection(); var ns = one.GetNamespace(root); var pages = new List <PageNode>(); foreach (var child in root.Elements(ns + "Page")) { if (child.Attribute("pageLevel").Value == "1") { // found the next parent page pages.Add(new PageNode(child)); } else { // grouping child pages with the top parent pages[pages.Count - 1].Children.Add(child); } } if (direction == SortDialog.Directions.Descending) { if (sorting == SortDialog.Sortings.ByName) { pages = pages.OrderByDescending( p => EmojiDialog.RemoveEmojis(p.Page.Attribute("name").Value)).ToList(); } else { var key = sorting == SortDialog.Sortings.ByCreated ? "dateTime" : "lastModifiedTime"; pages = pages.OrderByDescending( p => p.Page.Attribute(key).Value).ToList(); } } else { if (sorting == SortDialog.Sortings.ByName) { pages = pages.OrderBy( p => EmojiDialog.RemoveEmojis(p.Page.Attribute("name").Value)).ToList(); } else { var key = sorting == SortDialog.Sortings.ByCreated ? "dateTime" : "lastModifiedTime"; pages = pages.OrderBy( p => p.Page.Attribute(key).Value).ToList(); } } root.RemoveNodes(); // recreate flat list foreach (var page in pages) { root.Add(page.Page); foreach (var child in page.Children) { root.Add(child); } } //logger.WriteLine(root.ToString()); one.UpdateHierarchy(root); } logger.WriteTime(nameof(SortPages)); }
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); } } }
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); } }
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #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); }
private void BuildSectionTable( OneNote one, XNamespace ns, XElement container, IEnumerable <XElement> elements, bool includePages, int level) { foreach (var element in elements) { var notBin = element.Attribute("isRecycleBin") == null; if (element.Name.LocalName == "SectionGroup" && notBin) { // SectionGroup var name = element.Attribute("name").Value; var indent = new XElement(ns + "OEChildren"); indent.Add(new XElement(ns + "OE", new XElement(ns + "T", new XCData($"<span style='font-weight:bold'>{name}</span>")) )); BuildSectionTable( one, ns, indent, element.Elements(), includePages, level + 1); container.Add( new XElement(ns + "OE", new XElement(ns + "T", new XCData(string.Empty))), new XElement(ns + "OE", indent) ); } else if (element.Name.LocalName == "Section" && notBin) { // Section var link = one.GetHyperlink(element.Attribute("ID").Value, string.Empty); var name = element.Attribute("name").Value; var pages = element.Elements(ns + "Page"); if (includePages && pages.Any()) { var indent = new XElement(ns + "OEChildren"); foreach (var page in pages) { var text = new StringBuilder(); var plevel = int.Parse(page.Attribute("pageLevel").Value); while (plevel > 0) { text.Append(". . "); plevel--; } var plink = one.GetHyperlink(element.Attribute("ID").Value, string.Empty); var pname = page.Attribute("name").Value; text.Append($"<a href=\"{plink}\">{pname}</a>"); indent.Add(new XElement(ns + "OE", new XElement(ns + "T", new XCData(text.ToString()) ))); } container.Add(new XElement(ns + "OE", new XElement(ns + "T", new XCData($"<a href=\"{link}\">{name}</a>")), indent )); } else { container.Add(new XElement(ns + "OE", new XElement(ns + "T", new XCData($"<a href=\"{link}\">{name}</a>") ))); } } } }