The following (see the full code below) successfully adds a page in a section in Onenote. What I don't seem to be able to do is to get the lastly created page on top of the section. Here's the code that is puzzling me.
onenoteApp.GetHierarchy(sectionId, OneNote.HierarchyScope.hsPages, out string xmlPages);
var docPages = XDocument.Parse(xmlPages);
var lastNode = docPages.LastNode;
lastNode.Remove();
docPages.AddFirst(lastNode);
GetHIerachy() just loads xml into xmlPages.
The problem is stricly XML, I don't think OneNote is a problem (at this stage), as docPage.document (the xml string) is in the same state at the end as when docPages was Parsed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using OneNote = Microsoft.Office.Interop.OneNote;
namespace CreateOneNotePage
{
class Program
{
static OneNote.Application onenoteApp = new OneNote.Application();
static XNamespace ns = null;
static void Main(string[] args)
{
onenoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsNotebooks, out string xml);
GetNamespace();
string notebookId = GetObjectId(null, OneNote.HierarchyScope.hsNotebooks, "CreateOnenotePage");
string sectionId = GetObjectId(notebookId, OneNote.HierarchyScope.hsSections, "Projects");
string pageId = CreatePage(sectionId, "TEst" + DateTime.Now.ToString("hhmmss"));
Console.WriteLine(pageId);
Console.ReadKey();
}
private static void GetNamespace()
{
string xml;
onenoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsNotebooks, out xml);
var doc = XDocument.Parse(xml);
ns = doc.Root.Name.Namespace;
}
static string GetObjectId(string parentId, OneNote.HierarchyScope scope, string objectName)
{
string xml;
onenoteApp.GetHierarchy(parentId, scope, out xml);
var doc = XDocument.Parse(xml);
var nodeName = "";
switch (scope)
{
case (OneNote.HierarchyScope.hsNotebooks): nodeName = "Notebook"; break;
case (OneNote.HierarchyScope.hsPages): nodeName = "Page"; break;
case (OneNote.HierarchyScope.hsSections): nodeName = "Section"; break;
default:
return null;
}
var node = doc.Descendants(ns + nodeName).Where(n => n.Attribute("name").Value == objectName).FirstOrDefault();
return node.Attribute("ID").Value;
}
static string CreatePage(string sectionId,string pageName)
{
onenoteApp.CreateNewPage(sectionId, out string pageId);
onenoteApp.GetPageContent(pageId, out string xml, OneNote.PageInfo.piAll);
var doc = XDocument.Parse(xml);
var title = doc.Descendants(ns + "T").First();
title.Value = pageName;
onenoteApp.UpdatePageContent(doc.ToString());
onenoteApp.GetHierarchy(sectionId, OneNote.HierarchyScope.hsPages, out string xmlPages);
var docPages = XDocument.Parse(xmlPages);
var lastNode = docPages.LastNode;
lastNode.Remove();
docPages.AddFirst(lastNode);
onenoteApp.UpdateHierarchy(docPages.ToString());
return pageId;
}
}
}