public void OnBeginShutdown(ref Array custom) { if (onApp != null) { onApp = null; } }
private void InitializeOneNoteApplication() { // create the OneNote Application with retry since starting the Application\OneNote.exe process can fail if a running OneNote process is in the midst of shutting down just as we try to initialize uint attemptCount = 0; uint attemptCountMax = 3; do { try { attemptCount++; _oneNoteApp = new OneNote.Application(); break; } catch (Exception) { if (attemptCount == attemptCountMax) { throw; } System.Threading.Thread.Sleep(1000); // give a second to let OneNote exit completely } } while (attemptCount < attemptCountMax); }
public SelectOneNotePage(ref Application onteApplication, HierarchyType hierarchyType) : this() { _onenoteApp = onteApplication; _hierarchyType = hierarchyType; }
public void OnDisconnection(ext_DisconnectMode RemoveMode, ref Array custom) { //application = null; onApp = null; GC.Collect(); GC.WaitForPendingFinalizers(); }
/* * Updates the notebook xml */ public void updateNotebookData() { Microsoft.Office.Interop.OneNote.Application onApplication = new Microsoft.Office.Interop.OneNote.Application(); onApplication.GetHierarchy(System.String.Empty, Microsoft.Office.Interop.OneNote.HierarchyScope.hsSections, out strXML); xmlDoc.LoadXml(strXML); }
public string GetCurrentPageViewed() { string strXML; var xdoc = new XmlDocument(); var onApp = new OneNote.Application(); onApp.GetHierarchy(null, OneNote.HierarchyScope.hsPages, out strXML); // Load the xml into a document xdoc.LoadXml(strXML); string OneNoteNamespace = "http://schemas.microsoft.com/office/onenote/2007/onenote"; var nsmgr = new XmlNamespaceManager(xdoc.NameTable); nsmgr.AddNamespace("one", OneNoteNamespace); // Find the page ID of the active page XmlElement xmlActivePage = (XmlElement)xdoc.SelectSingleNode("//one:Page[@isCurrentlyViewed=\"true\"]", nsmgr) ?? ((XmlElement)xdoc.SelectSingleNode("//one:Section[@isCurrentlyViewed=\"true\"]", nsmgr) ?? (XmlElement)xdoc.SelectSingleNode("//one:SectionGroup[@isCurrentlyViewed=\"true\"]", nsmgr)); string strActivePageID = xmlActivePage != null?xmlActivePage.GetAttribute("ID") : null; return(strActivePageID); }
public static void CreateTaskItem() { string notebookXml; var onenoteApp = new Microsoft.Office.Interop.OneNote.Application(); onenoteApp.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml); var doc = System.Xml.Linq.XDocument.Parse(notebookXml); var ns = doc.Root.Name.Namespace; XElement oe = new XElement(ns + "OE"); oe.SetAttributeValue("objectID", "{1070E934-A60F-0F9F-3352-98A3F112008F}{46}{B0}"); oe.Add(new XElement(ns + "T", new XCData("123"))); var page = new XDocument(new XElement(ns + "Page", new XElement(ns + "Outline", new XElement(ns + "OEChildren", oe)))); //var page = new XDocument(new XElement(ns + "Page", // new XElement(ns + "OEChildren", // oe))); page.Root.SetAttributeValue("ID", "{60FE03D2-2EB9-4049-971D-00AE34EAAD3B}{1}{E178567790977931809320135678447047691353931}"); page.Root.Element(ns + "Outline").SetAttributeValue("objectID", "{1070E934-A60F-0F9F-3352-98A3F112008F}{15}{B0}"); onenoteApp.UpdatePageContent(page.ToString(), DateTime.MinValue); }
private void publishDoc(string notebook, string section, string id, int position) { Microsoft.Office.Interop.OneNote.Application oneNoteInner; oneNoteInner = new Microsoft.Office.Interop.OneNote.Application(); Console.WriteLine(notebook + " " + section + " " + id); string path = section + ".docx"; if (Directory.Exists(location)) { Directory.CreateDirectory(location); } if (File.Exists(location + path)) { File.Delete(location + path); } try { oneNoteInner.Publish(id, location + path, PublishFormat.pfWord, ""); dgv.Rows[position].Cells[2].Value = DateTime.Now; } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public NotebookStats(string notebookName) { NotebookName = notebookName; _onenoteApp = new OneNote.Application(); initializeNotebookXmlDoc(); }
/* * Publishes this section as a Word document / .DOCX */ public void publishToDOCX() { //folderName = "\\" + exportFolderBox.Text + "\\"; Microsoft.Office.Interop.OneNote.Application oneNoteInner; oneNoteInner = new Microsoft.Office.Interop.OneNote.Application(); string path = this.fileName + ".docx"; if (Directory.Exists(SettingsManager.location)) { Directory.CreateDirectory(SettingsManager.location); } if (File.Exists(SettingsManager.location + path)) { File.Delete(SettingsManager.location + path); } try { Console.WriteLine(SettingsManager.location + path); oneNoteInner.Publish(this.ID, SettingsManager.location + path, PublishFormat.pfWord, ""); this.exportTime = DateTime.Now.ToString(); } catch (Exception ex) { this.exportTime = "Failed with exception code: " + ex.HResult; MessageBox.Show(ex.Message + " \n while trying to create file: " + SettingsManager.location + path); } }
public NotebookStats(string notebookName) { NotebookName = notebookName; _onenoteApp = new OneNote.Application(); initializeNotebookXmlDoc(); }
private void PublishPages(string directory) { Microsoft.Office.Interop.OneNote.Application app = new Microsoft.Office.Interop.OneNote.Application(); string xml; app.GetHierarchy("", HierarchyScope.hsNotebooks, out xml); XDocument doc = XDocument.Parse(xml); foreach (XElement e in doc.Root.Elements()) { string name = (string)e.Attribute("name"); if (name == "Money Specs") { // this is the one! string id = (string)e.Attribute("ID"); app.GetHierarchy(id, HierarchyScope.hsPages, out xml); doc = XDocument.Parse(xml); foreach (XElement section in doc.Root.Elements()) { string sectionName = (string)section.Attribute("name"); string sectionId = (string)section.Attribute("ID"); if (section.Name.LocalName == "Section" && sectionName == "Documentation") { pageIdMap = new Dictionary <string, PageInfo>(); foreach (XElement page in section.Elements()) { string pageName = (string)page.Attribute("name"); Console.Write("Publishing " + pageName + "..."); string pageId = (string)page.Attribute("ID"); string fileName = directory + "\\" + pageName + ".mht"; PageInfo info = new PageInfo() { Name = pageName, Id = pageId, FileName = fileName }; pageIdMap[pageName] = info; if (File.Exists(fileName)) { File.Delete(fileName); } app.Publish(pageId, fileName, PublishFormat.pfMHTML, ""); Console.WriteLine("done"); } } } } } }
public void OnBeginShutdown(ref Array custom) { //if (application != null) // application = null; if (onApp != null) { onApp = null; } }
private void oneToMht() { Microsoft.Office.Interop.OneNote.Application onenoteApp = new Microsoft.Office.Interop.OneNote.Application(); string sectionId; onenoteApp.OpenHierarchy(srcPath, null, out sectionId); try { //타이틀(제목) 확인을 위한 xml 생성. string xml; XmlDocument document = new XmlDocument(); onenoteApp.GetHierarchy(sectionId, HierarchyScope.hsPages, out xml); document.LoadXml(xml); XmlNodeList xnList = document.GetElementsByTagName("one:Page"); //접근할 노드 string pageId = ""; foreach (XmlNode xn in xnList) { title = xn.Attributes["name"].Value; // get page title pageId = xn.Attributes["ID"].Value; //get page id } document.RemoveAll(); onenoteApp.GetPageContent(pageId, out xml, PageInfo.piAll); document.LoadXml(xml); /*xnList = document.GetElementsByTagName("one:OEChildren/one:T"); //접근할 노드 * * contents = xnList[0].InnerText; * * foreach (XmlNode xn in xnList) * { * title = xn.Attributes["name"].Value; // get page title * pageId = xn.Attributes["ID"].Value; //get page id * * }*/ //document.Save(@"c:\1111.xml"); onenoteApp.Publish(sectionId, dstPath, Microsoft.Office.Interop.OneNote.PublishFormat.pfMHTML, ""); } catch { return; } }
protected virtual void Dispose(bool disposing) { if (disposing) { _oneNoteApp = null; // there is no Dispose or Close if (_insertCompleteEvent != null) { _insertCompleteEvent.Dispose(); _insertCompleteEvent = null; } } }
private bool NavigateTo(string ID) { try { OneNote.Application oneApp = new OneNote.Application(); oneApp.NavigateTo(ID, null, false); return(true); } catch { return(false); } }
private void Close() { if (app != null) { showForm.Close(); wordHandler.Close(); SaveSetting(); vsCodeHandler.Close(); app = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
private XNamespace m_namespace; // OneNote Name Space ,用得还是挺多的 public OneNoteOperation() { // 构造函数,初始化Application m_OneNoteApp = null; m_OneNote_XML = null; string onenote_xml; try{ m_OneNoteApp = new Microsoft.Office.Interop.OneNote.Application(); m_OneNoteApp.GetHierarchy(null, HierarchyScope.hsPages, out onenote_xml); m_OneNote_XML = XDocument.Parse(onenote_xml); m_namespace = m_OneNote_XML.Root.Name.NamespaceName; }catch { MessageBox.Show("没有安装OneNote吗?还是安装一下吧。"); m_OneNoteApp = null; m_OneNote_XML = null; } }
public bool InitializeDataSet(string fileName) { try { dsOneNote = new DataSet("OneNoteHierarchy"); var onApp = new OneNote.Application(); string strONXml; onApp.GetHierarchy(null, OneNote.HierarchyScope.hsPages, out strONXml); var srONXml = new StringReader(strONXml); dsOneNote.ReadXml(srONXml); workingSet = new WorkingSet(fileName); } catch (Exception) { MessageBox.Show("Error accessing OneNote. Please make sure you have OneNote installed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } return(true); }
private static string getNotebookNodeId(OneNote.Application onenoteApp, string notebookName) { string notebooksXml; onenoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsNotebooks, out notebooksXml); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(notebooksXml); XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable); nsManager.AddNamespace(@"one", OneNoteXmlNamespace); string notebookXpath = getNotebookXpath(notebookName); XmlNode notebookNode = xmlDoc.SelectSingleNode(notebookXpath, nsManager); if (notebookNode == null) { throw new ArgumentException(string.Format(@"Can not found ""{0}"" as notebook name.", notebookName), @"notebookName"); } return(notebookNode.Attributes[@"ID"].Value); }
//private readonly string oneNoteXMLHierarchy = ""; /// <summary> /// Constructor. Create instance of Microsoft.Office.Interop.OneNote.Application and get XML hierarchy. /// </summary> public OneNoteProvider() { this.oneNote = new Microsoft.Office.Interop.OneNote.Application(); }
public XpNeededForm(Application application) { InitializeComponent(); this.onenoteApplication = application; }
public MainForm(Application application) { InitializeComponent(); this.onenoteApplication = application; this.Load += MainForm_Load; }
private bool NavigateTo(string ID) { try { OneNote.Application oneApp = new OneNote.Application(); oneApp.NavigateTo(ID, null, false); return true; } catch { return false; } }
public void SetOneNoteApplication(Application application) { OneNoteApplication = application; }
public TestForm(OneNote.Application oneNote) { oneNoteApp = oneNote; InitializeComponent(); }
/// <summary> /// Coauther OneNote file WithoutConflict /// </summary> /// <param name="filename">The coauthered OneNote file name</param> public static void OneNoteCoauthorWithoutConflict(string oneNote) { string filename = oneNote.Split('\\').Last().Split('.').First(); // Upload a document SharepointClient.UploadFile(oneNote); // Refresh web address Browser.Goto(Browser.DocumentAddress); // Find document on site IWebElement document = Browser.webDriver.FindElement(By.CssSelector("a[href*='" + filename + ".one']")); string curWinHandle = Browser.webDriver.CurrentWindowHandle; // Open OneNote document in local Onenote App Browser.RClick(document); Thread.Sleep(1000); Browser.Wait(By.LinkText("Open in OneNote")); var elementOpenInOneNote = Browser.webDriver.FindElement(By.LinkText("Open in OneNote")); Browser.Click(elementOpenInOneNote); Utility.WaitForOneNoteDocumentOpenning(filename, false, true); Thread.Sleep(2000); SendKeys.SendWait("Local"); Thread.Sleep(3000); // Switch To Web Browser Browser.webDriver.SwitchTo().Window(curWinHandle); Thread.Sleep(2000); // Click OneNote file on Sharepoint Web Server Browser.Click(document); Thread.Sleep(3000); Browser.Wait(By.Id("WebApplicationFrame")); Browser.webDriver.SwitchTo().Frame("WebApplicationFrame"); // Wait for online edit saved Thread.Sleep(3000); Browser.Wait(By.XPath("//a[@id='lblSyncStatus-Medium']/span[2][text()='Saved']")); Thread.Sleep(3000); SendKeys.SendWait("Online"); Thread.Sleep(3000); Browser.Wait(By.XPath("//a[@id='lblSyncStatus-Medium']/span[2][text()='Saving...']")); Thread.Sleep(10000); Browser.Wait(By.XPath("//a[@id='lblSyncStatus-Medium']/span[2][text()='Saved']")); Thread.Sleep(5000); // Refresh web address Browser.Goto(Browser.DocumentAddress); Thread.Sleep(2000); document = Browser.webDriver.FindElement(By.CssSelector("a[href*='" + filename + ".one']")); // Open OneNote document in local Onenote App Browser.RClick(document); Thread.Sleep(1000); Browser.Wait(By.LinkText("Open in OneNote")); elementOpenInOneNote = Browser.webDriver.FindElement(By.LinkText("Open in OneNote")); Browser.Click(elementOpenInOneNote); //Utility.WaitForOneNoteDocumentOpenning(filename, false, true); ///////////////////////////////////////////////////////////////////////////////// // Get the opened OneNote process, and read the page title. OneNote.Application oneNoteApp = new OneNote.Application(); string oneNoteXml; var oneNoteWindow = oneNoteApp.Windows.CurrentWindow; oneNoteApp.GetPageContent(oneNoteWindow.CurrentPageId, out oneNoteXml); var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(oneNoteXml); var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); nsmgr.AddNamespace("one", "http://schemas.microsoft.com/office/onenote/2013/onenote"); string titleXpath = "//one:Page/one:Title/one:OE/one:T"; System.Xml.XmlCDataSection titleNode = xmlDoc.SelectSingleNode(titleXpath, nsmgr).FirstChild as System.Xml.XmlCDataSection; // If its title in local Onenote App is not updated and wait. while (!titleNode.Value.ToString().Contains("OnlineLocal")) { Thread.Sleep(5000); oneNoteWindow = oneNoteApp.Windows.CurrentWindow; oneNoteApp.GetPageContent(oneNoteWindow.CurrentPageId, out oneNoteXml); xmlDoc.LoadXml(oneNoteXml); titleNode = xmlDoc.SelectSingleNode(titleXpath, nsmgr).FirstChild as System.Xml.XmlCDataSection; } /////////////////////////////////////////////////////////////////////////////////// // Closed OneNote App. oneNoteApp.Windows.CurrentWindow.Active = true; SendKeys.SendWait("%{F4}"); // Delete the new upload document SharepointClient.DeleteFile(filename + ".one"); }
public Callback(ref Application onenoteApplication, HierarchyType hierarchyType) { _onenoteApp = onenoteApplication; _hierarchyType = hierarchyType; }
public void OnDisconnection(ext_DisconnectMode RemoveMode, ref Array custom) { onApp = null; GC.Collect(); GC.WaitForPendingFinalizers(); }
public void OnConnection(object Application, ext_ConnectMode ConnectMode, object AddInInst, ref Array custom) { onApp = (Microsoft.Office.Interop.OneNote.Application)Application; }
public MainForm(OneNote.Application oneNoteApp) { _oneNoteApp = oneNoteApp; InitializeComponent(); }
static void Main(string[] args) { OneNote.Application oneApp; // Obtain reference to OneNote application try { oneApp = new OneNote.Application(); } catch (Exception e) { Log.Error(string.Format("Could not obtain reference to OneNote ({0})", e.Message)); return; } // get till page level oneApp.GetHierarchy(null, OneNote.HierarchyScope.hsPages, out string outputXML); ONNotebookListing onListing = new ONNotebookListing(outputXML); if (Config.Current.ShowHelp || Config.Current.Arguments.Count == 0) { HelpHandler hh = new HelpHandler(); Log.Information(hh.Print()); return; } if (Config.Current.ListAllNotebook) { string[] notebookNames = onListing.ListAllNotebook(); foreach (var nb in notebookNames) { Console.WriteLine(nb); } return; } if (!string.IsNullOrEmpty(Config.Current.NotebookName)) { Log.Information("Query notebook information"); ONNotebook notebook = onListing.GetNotebook(Config.Current.NotebookName); if (notebook == null) { Log.Error("Cannot get desired notebook"); return; } Log.Information(string.Format("Notebook name: {0}", notebook.Name)); Log.Information(string.Format("Notebook ID: {0}", notebook.ID)); Log.Information(string.Format("Number section: {0}", notebook.Sections.Count)); Log.Information("Begin exporting ..."); Export2PDF export2PDF = new Export2PDF(); export2PDF.BasedPath = Config.Current.CacheFolder; export2PDF.OneNoteApplication = oneApp; export2PDF.CreateCacheFolder(notebook); if (Config.Current.ExportNotebook) { Log.Information(string.Format("Exporting entire notebook [{0}]", notebook.Name)); export2PDF.Export(Config.Current.OutputPath, notebook); } if (!string.IsNullOrEmpty(Config.Current.ExportSection)) { OneNote2PDF.Library.Data.ONSection section = notebook.GetSection(Config.Current.ExportSection); if (section == null) { Log.Error("Cannot find the specified section"); } else { Log.Information(string.Format("Exporting section [{0}] ...", section.Name)); export2PDF.Export(Config.Current.OutputPath, section); } } return; } }
private string GetOCRText(string base64img) { byte[] imageBytes = Convert.FromBase64String(base64img); MemoryStream stream = new MemoryStream(imageBytes, 0, imageBytes.Length); stream.Write(imageBytes, 0, imageBytes.Length); Image bitmap = Image.FromStream(stream, true); Console.WriteLine(bitmap.Width); Console.WriteLine(bitmap.Height); string pageToBeChange = "ocr"; string strNamespace = "http://schemas.microsoft.com/office/onenote/2010/onenote"; OneNote.Application onApplication = new OneNote.Application(); string notebookXml; onApplication.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml); XDocument doc = XDocument.Parse(notebookXml); XNamespace ns = doc.Root.Name.Namespace; XElement pageNode = doc.Descendants(ns + "Page").FirstOrDefault(); string existingPageId = pageNode.Attribute("ID").Value; string origPageXML; onApplication.GetPageContent(existingPageId, out origPageXML, OneNote.PageInfo.piAll); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(origPageXML); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); nsmgr.AddNamespace("one", strNamespace); XmlNodeList imageNodes = xmlDoc.SelectNodes("//one:Image", nsmgr); for (int i = 0; i < imageNodes.Count; i++) { if (imageNodes[i].Attributes["objectID"] != null) { onApplication.DeletePageContent(existingPageId, imageNodes[i].Attributes["objectID"].Value); } } string m_xmlImageContent = "<one:Image><one:Size width=\"{1}\" height=\"{2}\" isSetByUser=\"true\" /><one:Data>{0}</one:Data>" + //"<one:OCRData lang=\"zh-TW\">" + //"<one:OCRToken startPos=\"0\" region=\"0\" line=\"0\" x=\"5.27999973297119\" y=\"4.800000190734863\" width=\"48.72000122070312\" height=\"51.8400001525879\"/>" + //"</one:OCRData>" + "</one:Image>"; string m_xmlNewOutline = "<?xml version=\"1.0\"?><one:Page xmlns:one=\"{2}\" ID=\"{1}\"><one:Title><one:OE><one:T><![CDATA[{3}]]></one:T></one:OE></one:Title>{0}</one:Page>"; if (pageNode != null) { string imageXmlStr = string.Format(m_xmlImageContent, base64img, bitmap.Width, bitmap.Height); string pageChangesXml = string.Format(m_xmlNewOutline, new object[] { imageXmlStr, existingPageId, strNamespace, pageToBeChange }); onApplication.UpdatePageContent(pageChangesXml.ToString(), DateTime.MinValue); //onenoteApp.UpdateHierarchy(pageChangesXml); } long startTime = currentUnixTime(); string strPageContent = ""; while (strPageContent == "") { string strHierarchy; string strXML; var onApp = onApplication; // Get the hierarchy from the root to pages onApp.GetHierarchy(System.String.Empty, OneNote.HierarchyScope.hsPages, out strHierarchy); // Load the xml into a document xmlDoc = new XmlDocument(); xmlDoc.LoadXml(strHierarchy); //Create an XmlNamespaceManager for resolving namespaces. nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); nsmgr.AddNamespace("one", strNamespace); // Find the page ID of the active page XmlElement xmlActivePage = (XmlElement)xmlDoc.SelectSingleNode("//one:Page", nsmgr); string strActivePageID = xmlActivePage.GetAttribute("ID"); // Get the content from the active page onApp.GetPageContent(strActivePageID, out strXML, OneNote.PageInfo.piBinaryData); xmlDoc.LoadXml(strXML); //Get the data in the T nodes string strOcrContent = ""; strPageContent = ""; XmlNodeList elemList = xmlDoc.GetElementsByTagName("one:OCRText"); for (int i = 0; i < elemList.Count; i++) { strOcrContent = elemList[i].InnerText; //Get the contents of the <![CDATA[]] block strPageContent = strPageContent + strOcrContent; } if (currentUnixTime() > startTime + 3) { break; } } if (strPageContent == "") { return("<No OCR content on this page>"); } else { return(strPageContent); } }
/// <summary> /// Coauther OneNote file WithConflict /// </summary> /// <param name="oneNote"></param> public static void OneNoteCoauthorWithConflict(string oneNote) { string filename = oneNote.Split('\\').Last().Split('.').First(); // Upload a document SharepointClient.UploadFile(oneNote); // Refresh web address Browser.Goto(Browser.DocumentAddress); // Find document on site IWebElement onenote = Browser.webDriver.FindElement(By.CssSelector("a[href*='" + filename + ".one']")); string DocumentWinHandle = Browser.webDriver.CurrentWindowHandle; // Open OneNote document in local Onenote App Browser.RClick(onenote); Browser.Wait(By.LinkText("Open in OneNote")); var elementOpenInOneNote = Browser.webDriver.FindElement(By.LinkText("Open in OneNote")); Browser.Click(elementOpenInOneNote); Utility.WaitForOneNoteDocumentOpenning(filename, false, true); SendKeys.SendWait("Insert by onenote App"); Thread.Sleep(2000); // Click the document in root site Browser.RClick(onenote); Browser.Wait(By.LinkText("Open in OneNote Online")); var elementOpenOnline = Browser.webDriver.FindElement(By.LinkText("Open in OneNote Online")); Browser.Click(elementOpenOnline); //Browser.webDriver.FindElement(By.XPath("//a[@id='lblSyncStatus-Medium']/span[2][text()='Saved']")); Thread.Sleep(5000); SendKeys.SendWait("^a");; Thread.Sleep(1000); SendKeys.SendWait("{DELETE}"); // Switch To Web Browser Browser.webDriver.SwitchTo().Window(DocumentWinHandle); // Open OneNote document in local Onenote App Browser.RClick(onenote); Browser.Wait(By.LinkText("Open in OneNote")); elementOpenInOneNote = Browser.webDriver.FindElement(By.LinkText("Open in OneNote")); Browser.Click(elementOpenInOneNote); Thread.Sleep(2000); // Save current window handle string curWinHandle = Browser.webDriver.CurrentWindowHandle; SendKeys.SendWait("^a"); SendKeys.SendWait("{DELETE}"); Thread.Sleep(2000); Browser.RClick(onenote); Browser.Wait(By.LinkText("Open in OneNote Online")); elementOpenOnline = Browser.webDriver.FindElement(By.LinkText("Open in OneNote Online")); Browser.Click(elementOpenOnline); Thread.Sleep(40000); //var merge = Browser.webDriver.FindElement(By.XPath("//span[@class='WACBusinessBarBody'][text()='This page contains conflicting changes. Click here to show versions of the page with unmerged changes.']")); Browser.RClick(onenote); Browser.Wait(By.LinkText("Open in OneNote")); elementOpenInOneNote = Browser.webDriver.FindElement(By.LinkText("Open in OneNote")); Browser.Click(elementOpenInOneNote); Thread.Sleep(30000); //Delete conflict page version in OneNote local App. SendKeys.SendWait("+(^w)"); Thread.Sleep(2000); SendKeys.SendWait("+(^w)"); Thread.Sleep(2000); SendKeys.SendWait("{ENTER}"); Thread.Sleep(2000); // Get the opened OneNote process, and edit it OneNote.Application oneNoteApp = new OneNote.Application(); var oneNoteWindow = oneNoteApp.Windows.CurrentWindow; // Closed OneNote App. oneNoteApp.CloseNotebook(oneNoteWindow.CurrentNotebookId); SendKeys.SendWait("%{f4}"); // Delete the new upload document SharepointClient.DeleteFile(filename + ".one"); }
public void OnConnection(object Application, ext_ConnectMode ConnectMode, object AddInInst, ref Array custom) { onApp = (Microsoft.Office.Interop.OneNote.Application)Application; }
private void ImageRead(object sender, RoutedEventArgs e) { string strID, strXML, notebookXml; string pageToBeChange = "SandboxPage"; Microsoft.Office.Interop.OneNote.Application app = new Microsoft.Office.Interop.OneNote.Application(); //app.OpenHierarchy(@"C:\Users\kjlue_000\Documents\OneNote Notebooks\OCRSandbox\Ocr.one", // System.String.Empty, out strID, CreateFileType.cftNone); app.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml); var doc = XDocument.Parse(notebookXml); var ns = doc.Root.Name.Namespace; var pageNode = doc.Descendants(ns + "Page").Where(n => n.Attribute("name").Value == pageToBeChange).FirstOrDefault(); var existingPageId = pageNode.Attribute("ID").Value; Bitmap bitmap = ScreenCapture(); MemoryStream stream = new MemoryStream(); bitmap.Save(stream, ImageFormat.Jpeg); string fileString = Convert.ToBase64String(stream.ToArray()); String strImportXML; strImportXML = "<?xml version=\"1.0\"?>" + "<one:Page xmlns:one=\"http://schemas.microsoft.com/office/onenote/2013/onenote\" ID=\"" + existingPageId + "\">" + //{D2954871-2111-06B9-1AB9-882CD62848AA}{1}{E1833485368852652557020163191444754720811741}\">" + " <one:PageSettings RTL=\"false\" color=\"automatic\">" + " <one:PageSize>" + " <one:Automatic/>" + " </one:PageSize>" + " <one:RuleLines visible=\"false\"/>" + " </one:PageSettings>" + " <one:Title style=\"font-family:Calibri;font-size:17.0pt\" lang=\"en-US\">" + " <one:OE alignment=\"left\">" + " <one:T>" + " <![CDATA[SandboxPage]]>" + " </one:T>" + " </one:OE>" + " </one:Title>" + " <one:Outline >" + " <one:Position x=\"20\" y=\"50\"/>" + " <one:Size width=\"" + bitmap.Width + "\" height=\"" + bitmap.Height + "\" isSetByUser=\"true\"/>" + " <one:OEChildren>" + " <one:OE alignment=\"left\">" + //" <one:T>" + " <one:Image> <one:Data>" + fileString + "</one:Data></one:Image>" + //" <![CDATA[Sample Text]]>" + //" </one:T>" + " </one:OE>" + " </one:OEChildren>" + " </one:Outline>" + "</one:Page>"; app.UpdatePageContent(strImportXML); //app.SyncHierarchy(strID); //Give one note some time to ocr the texts app.GetPageContent(existingPageId, out strXML); doc = XDocument.Parse(strXML); int timeoutCounter = 0; while (doc.Descendants(ns + "OCRText").FirstOrDefault() == null) { System.Threading.Thread.Sleep(200); app.GetPageContent(existingPageId, out strXML); doc = XDocument.Parse(strXML); timeoutCounter++; if (timeoutCounter > 30) { textbox.Text = "OneNote timed out texify-ing image! try again? maybe?..."; return; } } string readText = doc.Descendants(ns + "OCRText").FirstOrDefault().Value; if (savedEnd != null) { readText = savedEnd + " " + readText; savedEnd = null; } Filters.CombineLines(ref readText); readText = readText.Replace('¡', 'i'); Filters.PsychologyFilter(ref readText); textbox.Text = readText; //Empty Page (I.E. Cleanup) doc = XDocument.Parse(strXML); var imageXML = doc.Descendants(ns + "Outline"); foreach (var item in imageXML) { string outlineID = item.Attribute("objectID").Value; if (outlineID != null) { app.DeletePageContent(existingPageId, outlineID); } } //Minimize then read this.WindowState = System.Windows.WindowState.Minimized; this.ReadText(sender, e); }
public void OnBeginShutdown(ref Array custom) { if (onApp != null) onApp = null; }
private void fnOCR(string v_strImgPath) { //获取图片的Base64编码 FileInfo file = new FileInfo(v_strImgPath); using (MemoryStream ms = new MemoryStream()) { Bitmap bp = new Bitmap(v_strImgPath); switch (file.Extension.ToLower()) { case ".jpg": bp.Save(ms, ImageFormat.Jpeg); break; case ".jpeg": bp.Save(ms, ImageFormat.Jpeg); break; case ".gif": bp.Save(ms, ImageFormat.Gif); break; case ".bmp": bp.Save(ms, ImageFormat.Bmp); break; case ".tiff": bp.Save(ms, ImageFormat.Tiff); break; case ".png": bp.Save(ms, ImageFormat.Png); break; case ".emf": bp.Save(ms, ImageFormat.Emf); break; default: this.labMsg.Content = "不支持的图片格式。"; return; } byte[] buffer = ms.GetBuffer(); string _Base64 = Convert.ToBase64String(buffer); //向Onenote2010中插入图片 var onenoteApp = new Microsoft.Office.Interop.OneNote.Application(); /*string sectionID; Console.WriteLine("wang"); onenoteApp.OpenHierarchy(AppDomain.CurrentDomain.BaseDirectory + "tmpPath/" + "newfile.one", null, out sectionID, Microsoft.Office.Interop.OneNote.CreateFileType.cftSection); string pageID = "{A975EE72-19C3-4C80-9C0E-EDA576DAB5C6}{1}{B0}"; // 格式 {guid}{tab}{??} onenoteApp.CreateNewPage(sectionID, out pageID, Microsoft.Office.Interop.OneNote.NewPageStyle.npsBlankPageNoTitle); */ var existingPageId = ""; //var pageNode; string notebookXml; if (existingPageId == "") { onenoteApp.GetHierarchy(null, Microsoft.Office.Interop.OneNote.HierarchyScope.hsPages, out notebookXml); //onenoteApp.GetHierarchy(pageID, HierarchyScope.hsPages, out notebookXml); var doc = XDocument.Parse(notebookXml); var ns = doc.Root.Name.Namespace; var sectionNode = doc.Descendants(ns + "Section").FirstOrDefault(); var sectionID = sectionNode.Attribute("ID").Value; onenoteApp.CreateNewPage(sectionID, out existingPageId); var pageNode = doc.Descendants(ns + "Page").FirstOrDefault(); if (pageNode != null) { //Image Type 只支持这些类型:auto|png|emf|jpg string ImgExtension = file.Extension.ToLower().Substring(1); switch (ImgExtension) { case "jpg": ImgExtension = "jpg"; break; case "png": ImgExtension = "png"; break; case "emf": ImgExtension = "emf"; break; default: ImgExtension = "auto"; break; } var page = new XDocument(new XElement(ns + "Page", new XAttribute("ID", existingPageId), new XElement(ns + "Outline", new XElement(ns + "OEChildren", new XElement(ns + "OE", new XElement(ns + "Image", new XAttribute("format", ImgExtension), new XAttribute("originalPageNumber", "0"), new XElement(ns + "Position", new XAttribute("x", "0"), new XAttribute("y", "0"), new XAttribute("z", "0")), new XElement(ns + "Size", new XAttribute("width", bp.Width.ToString()), new XAttribute("height", bp.Height.ToString())), new XElement(ns + "Data", _Base64))))))); //page.Root.SetAttributeValue("ID", existingPageId); onenoteApp.UpdatePageContent(page.ToString(), DateTime.MinValue); //线程休眠时间,单位毫秒,若图片很大,则延长休眠时间,保证Onenote OCR完毕 System.Threading.Thread.Sleep(Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["WaitTIme"])); string pageXml; onenoteApp.GetPageContent(existingPageId, out pageXml, Microsoft.Office.Interop.OneNote.PageInfo.piBinaryData);//piAll //获取OCR后的内容 FileStream tmpXml = new FileStream(System.Configuration.ConfigurationManager.AppSettings["tmpPath"] + @"\tmp.xml", FileMode.Create, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(tmpXml); sw.Write(pageXml); sw.Flush(); sw.Close(); tmpXml.Close(); FileStream tmpOnenote = new FileStream(System.Configuration.ConfigurationManager.AppSettings["tmpPath"] + @"\tmp.xml", FileMode.Open, FileAccess.ReadWrite); XmlReader reader = XmlReader.Create(tmpOnenote); XElement rdlc = XElement.Load(reader); XmlNameTable nameTable = reader.NameTable; XmlNamespaceManager mgr = new XmlNamespaceManager(nameTable); mgr.AddNamespace("one", ns.ToString()); StringReader sr = new StringReader(pageXml); XElement onenote = XElement.Load(sr); var xml = from o in onenote.XPathSelectElements("//one:Image", mgr) select o.XPathSelectElement("//one:OCRText", mgr).Value; this.txtOCRed.Text = (xml.First().ToString()).Replace(" ", ""); sr.Close(); reader.Close(); tmpOnenote.Close(); onenoteApp.DeleteHierarchy(existingPageId); //onenoteApp.DeleteHierarchy(sectionID, DateTime.MinValue, true); // 摧毁原始页面 } } /*Onenote 2010 中图片的XML格式 <one:Image format="" originalPageNumber="0" lastModifiedTime="" objectID=""> <one:Position x="" y="" z=""/> <one:Size width="" height=""/> <one:Data>Base64</one:Data> //以下标签由Onenote 2010自动生成,不要在程序中处理,目标是获取OCRText中的内容。 <one:OCRData lang="en-US"> <one:OCRText> <![CDATA[ OCR后的文字 ]]> </one:OCRText> <one:OCRToken startPos="0" region="0" line="0" x="4.251968383789062" y="3.685039281845092" width="31.18110275268555" height="7.370078563690185"/> <one:OCRToken startPos="7" region="0" line="0" x="39.40157318115234" y="3.685039281845092" width="13.32283401489258" height="8.78740119934082"/> <one:OCRToken startPos="12" region="0" line="1" x="4.251968383789062" y="17.85826683044434" width="23.52755928039551" height="6.803150177001953"/> <one:OCRToken startPos="18" region="0" line="1" x="32.031494140625" y="17.85826683044434" width="41.10236358642578" height="6.803150177001953"/> <one:OCRToken startPos="28" region="0" line="1" x="77.66928863525391" y="17.85826683044434" width="31.46456718444824" height="6.803150177001953"/> ................ </one:Image> */ /*ObjectID格式 The representation of an object to be used for identification of objects on a page. Not unique through OneNote, but unique on the page and the hierarchy. <xsd:simpleType name="ObjectID" "> <xsd:restriction base="xsd:string"> <xsd:pattern value="\{[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}\}\{[0-9]+\}\{[A-Z][0-9]+\}" /> </xsd:restriction> </xsd:simpleType> */ } }
public TestForm(OneNote.Application oneNote) { oneNoteApp = oneNote; InitializeComponent(); }
private void HighlightPage(Application application, string pageId, WordMatcher matcher) { string pageXml; application.GetPageContent(pageId, out pageXml); Debug.WriteLine(pageXml); XElement page = XElement.Parse(pageXml); XNamespace oneNS = page.Name.Namespace; XElement title = page.Element(oneNS + "Title"); XElement titleOE = title.Element(oneNS + "OE"); Debug.WriteLine("page:{0} by {1}", titleOE.Element(oneNS + "T").Value, titleOE.Attribute("author")); StatisticsDataSet.HighlightStatisticsRow statRow = null; // frmStatistics.BeforeProcessing(); foreach (XElement outline in page.Elements(oneNS + "Outline")) { foreach (XElement oeChildren in outline.Elements(oneNS + "OEChildren")) { foreach (XElement oe in oeChildren.Elements(oneNS + "OE")) { foreach (XElement t in oe.Elements(oneNS + "T")) { //Debug.WriteLine("before: "); //Debug.WriteLine(t.Value); string process = ProcessingWords(t.Value, matcher, statRow); t.RemoveNodes(); t.Add(new XCData(process)); } } } } //frmStatistics.AfterProcessing(); application.UpdatePageContent(page.ToString(SaveOptions.None)); }
public OnenotePage(OneNote.Application app) { this._app = app; this.LoadOrCreatePage(); }