Example #1
0
        //将高亮代码插入到光标所在位置
        private void insertHighLightCodeAtCursor(string htmlContent, string pageId)
        {
            string pageXml;

            onApp.GetPageContent(pageId, out pageXml, PageInfo.piSelection);
            var doc      = XDocument.Parse(pageXml);
            var selected = doc.Descendants(ns + "Outline").Descendants(ns + "T")
                           .Where(n => n.Attribute("selected") != null && n.Attribute("selected").Value == "all")
                           .FirstOrDefault();

            selected.ReplaceNodes(new XCData(htmlContent));
            onApp.UpdatePageContent(doc.ToString(), DateTime.MinValue);
        }
Example #2
0
        // 获取指定page的XML内容
        public string get_page_content_by_id(string id)
        {
            string output = "";

            m_OneNoteApp.GetPageContent(id, out output, Microsoft.Office.Interop.OneNote.PageInfo.piBinaryData);
            return(output);
        }
Example #3
0
        /// <summary>
        /// 获取当前页面的内容和输出 xml 字符串.
        /// </summary>
        /// <returns>string</returns>
        private string GetActivePageContent()
        {
            string activeObjectID = this.GetActiveObjectID(_ObjectType.Page);
            string pageXmlOut     = "";

            oneNoteApp.GetPageContent(activeObjectID, out pageXmlOut);

            return(pageXmlOut);
        }
Example #4
0
        /// <summary>
        /// 插入代码到当前光标位置
        /// </summary>
        /// <param name="fileName">代码渲染后的文件位置</param>
        private void insertCodeToCurrentSide(string fileName)
        {
            string noteBookXml;

            onApp.GetHierarchy(null, HierarchyScope.hsPages, out noteBookXml);

            var doc = XDocument.Parse(noteBookXml);

            _ns = doc.Root.Name.Namespace;//获取OneNote XML文件的命名空间

            var pageNode = doc.Descendants(_ns + "Page")
                           .Where(n => n.Attribute("isCurrentlyViewed") != null && n.Attribute("isCurrentlyViewed").Value == "true")
                           .FirstOrDefault();

            string SelectedPageID = pageNode.Attribute("ID").Value;

            string SelectedPageContent;

            //获取当前页面的XML内容
            onApp.GetPageContent(SelectedPageID, out SelectedPageContent, PageInfo.piSelection);
            var SelectedPageXml = XDocument.Parse(SelectedPageContent);

            pageNode = SelectedPageXml.Descendants(_ns + "Page").FirstOrDefault();
            XElement pointNow = pageNode
                                .Descendants(_ns + "T").Where(n => n.Attribute("selected") != null && n.Attribute("selected").Value == "all")
                                .First();

            if (pointNow != null)
            {
                var isTitle = pointNow.Ancestors(_ns + "Title").FirstOrDefault();

                if (isTitle != null)
                {
                    MessageBox.Show("代码不能插入标题中");
                    return;
                }
            }
            else
            {
                return;
            }

            try
            {
                //将html内容转化为XML内容
                //更新当前页面的XML内容
                XmlBuild builder = new XmlBuild(fileName, _ns);
                builder.XmlReBuilding(ref pageNode, ref pointNow);

                onApp.UpdatePageContent(pageNode.ToString(), DateTime.MinValue);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Example #5
0
        private string GetPageContent()
        {
            string notebookXml;

            _oneNoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsPages, out notebookXml);

            var           doc      = XDocument.Parse(notebookXml);
            var           ns       = doc.Root.Name.Namespace;
            var           pageNode = doc.Descendants(ns + "Page").FirstOrDefault(n => n.Attribute("name").Value == GetPageTitle());
            StringBuilder sb       = new StringBuilder();

            if (pageNode != null)
            {
                string pageXml;
                _oneNoteApp.GetPageContent(pageNode.Attribute("ID").Value, out pageXml);
                sb.AppendLine(XDocument.Parse(pageXml).ToString());
            }
            return(sb.ToString());
        }
Example #6
0
        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;
            }
        }
Example #7
0
        internal void InsertImageIntoPage(OneNotePage page, string imageFilePath, string publishUrl, bool addTitle = false)
        {
            string xmlToInsert = _oneNoteXml.GetInsertSnipXml(page, GetBase64ImageString(imageFilePath), publishUrl, addTitle);

            _oneNoteApp.UpdatePageContent(xmlToInsert, System.DateTime.MinValue, _oneNoteXmlSchema);

            // navigate to inserted Snip
            string pageContentXmlAfterInsert;

            _oneNoteApp.GetPageContent(page.Id, out pageContentXmlAfterInsert, OneNote.PageInfo.piBasic, _oneNoteXmlSchema);

            string insertedSnipObjectId = _oneNoteXml.GetInsertedSnipObjectId(pageContentXmlAfterInsert);

            _oneNoteApp.NavigateTo(page.Id, insertedSnipObjectId);
        }
Example #8
0
        /// <summary>
        /// 取得滑鼠所在的點
        /// Get Mouse Point
        /// </summary>
        private string[] GetMousePointPosition(string pageID)
        {
            string pageXml;
            onApp.GetPageContent(pageID, out pageXml, PageInfo.piSelection);

            var node = XDocument.Parse(pageXml).Descendants(ns + "Outline")
                                               .Where(n => n.Attribute("selected") != null && n.Attribute("selected").Value == "partial")
                                               .FirstOrDefault();
            if (node != null)
            {
                var attrPos = node.Descendants(ns + "Position").FirstOrDefault();
                if (attrPos != null)
                {
                    var x = attrPos.Attribute("x").Value;
                    var y = attrPos.Attribute("y").Value;
                    return new string[] { x, y };
                }
            }
            return null;
        }
Example #9
0
        /// <summary>
        /// Take a xml string which follows the standard of
        /// </summary>
        /// <param name="outputXML"></param>
        public void BuildIndex(string outputXML)
        {
            var info     = XDocument.Parse(outputXML);
            var pageList = info.Descendants(One + "Page");

            int totalCount = pageList.Count();

            Console.WriteLine("All Count" + totalCount);
            double count = 0;

            foreach (var n in pageList)
            {
                count           += 1;
                progressRate     = count / totalCount;
                currentPageTitle = n.Attribute("name").Value;
                Console.Write("Adding " + currentPageTitle);
                var    pageID = n.Attribute("ID").Value;
                String xmlString;
                oneNote.GetPageContent(pageID, out xmlString);
                var doc = XDocument.Parse(xmlString);
                var des = doc.Descendants(One + "OE");
                Console.WriteLine("\t" + des.Count() + " Paragraphs");

                var documentList = new List <Tuple <string, string> >();
                foreach (var el in des)
                {
                    var parId = el.Attribute("objectID");
                    var text  = el.Element(One + "T");

                    if (parId == null || text == null || text.Value.Length <= 2)
                    {
                        continue;
                    }
                    var id  = parId.Value + " " + pageID;
                    var par = RemoveUnwantedTags(text.Value);
                    //Console.WriteLine(id + "\t" + par + "\n");
                    documentList.Add(new Tuple <string, string>(id, par));
                }
                lucene.AddDocument(documentList);
            }
        }
        /// <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");
        }
Example #11
0
        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);
            }
        }
        public static bool UpdateTaskList(string notebook, string section, string page, TaskItem newTask)
        {
            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;

            var notebookNodeList = doc.Descendants(ns + "Notebook").Where(n =>
                                                                          n.Attribute("name").Value.Contains(notebook));

            if (notebookNodeList == null)
            {
                return(false);
            }

            foreach (var notebookNode in notebookNodeList)
            {
                var sectionNode = notebookNode.Descendants(ns + "Section").Where(n =>
                                                                                 n.Attribute("name").Value.Contains(section)).FirstOrDefault();
                if (sectionNode != null)
                {
                    var pageNode = sectionNode.Descendants(ns + "Page")
                                   .Where(n => n.Attribute("name").Value.Contains(page))
                                   .FirstOrDefault();
                    if (pageNode != null)
                    {
                        string pageXml;
                        onenoteApp.GetPageContent(pageNode.Attribute("ID").Value, out pageXml);
                        var pageDoc   = XDocument.Parse(pageXml);
                        var taskTable = pageDoc.Descendants(ns + "Table").FirstOrDefault();
                        if (taskTable != null)
                        {
                            bool bfirst = true;
                            foreach (var taskRow in from row in taskTable.Descendants(ns + "Row") select row)
                            {
                                if (bfirst)
                                {
                                    bfirst = false;
                                    continue;
                                }

                                string strTaskId = "";
                                var    taskCells = taskRow.Descendants(ns + "Cell");
                                if (taskCells.Count() == 5)
                                {
                                    var taskId = taskCells.ElementAt(0).Descendants(ns + "OutlookTask").FirstOrDefault();
                                    if (taskId == null)
                                    {
                                        continue;
                                    }
                                    strTaskId = taskId.Attribute("guidTask").Value;
                                    if (strTaskId != newTask.TaskOneNoteId)
                                    {
                                        continue;
                                    }

                                    if (newTask.TaskTimeEdit > 0)
                                    {
                                        taskCells.ElementAt(1).Value = newTask.TaskTimeEdit.ToString();
                                    }
                                    if (newTask.TaskTimeUsage > 0)
                                    {
                                        taskCells.ElementAt(2).Value = newTask.TaskTimeUsage.ToString();
                                    }

                                    string strModifiedPage = pageDoc.ToString();

                                    onenoteApp.UpdatePageContent(strModifiedPage, DateTime.MinValue);
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }

            return(false);
        }
Example #13
0
        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 void CoauthorTableOfContents()
        {
            string oneWithFileData = ConfigurationManager.AppSettings["NotebookTableOfContents"];
            string filename        = oneWithFileData.Split('\\').Last().Split('.').First();

            // Upload a document
            SharepointClient.UploadFile(oneWithFileData);
            // Refresh web address
            Browser.Goto(Browser.DocumentAddress);
            // Find document on site
            IWebElement onetoc2           = Browser.webDriver.FindElement(By.CssSelector("a[href*='" + filename + ".onetoc2']"));
            string      DocumentWinHandle = Browser.webDriver.CurrentWindowHandle;

            // Open onetoc2 file in local Onenote App.
            Browser.RClick(onetoc2);
            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);
            // Create a new section in local Onenote App.
            SendKeys.SendWait("^t");
            Thread.Sleep(8000);

            // Refresh web address
            Browser.Goto(Browser.DocumentAddress);
            // Find new create onenote section document on site
            IWebElement onenote = Browser.webDriver.FindElement(By.CssSelector("a[href*='New Section 1.one']"));

            Browser.Click(onenote);
            Thread.Sleep(4000);
            SendKeys.SendWait("New Page");
            //Thread.Sleep(10000);
            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()='Saving...']"));
            Thread.Sleep(10000);
            Browser.Wait(By.XPath("//a[@id='lblSyncStatus-Medium']/span[2][text()='Saved']"));
            Thread.Sleep(2000);

            // Refresh web address
            Browser.Goto(Browser.DocumentAddress);
            Thread.Sleep(3000);
            onenote = Browser.webDriver.FindElement(By.CssSelector("a[href*='New Section 1.one']"));
            // Open OneNote document in local Onenote App
            Browser.RClick(onenote);
            Thread.Sleep(1000);
            Browser.Wait(By.LinkText("Open in OneNote"));
            elementOpenInOneNote = Browser.webDriver.FindElement(By.LinkText("Open in OneNote"));
            Browser.Click(elementOpenInOneNote);

            // 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.Contains("New Page"))
            {
                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 created section document
            SharepointClient.DeleteFile("New Section 1" + ".one");
            // Delete the new upload document
            SharepointClient.DeleteFile(filename + ".onetoc2");
            bool result = FormatConvert.SaveSAZ(TestBase.testResultPath, testName, out file);

            Assert.IsTrue(result, "The saz file should be saved successfully.");
            bool parsingResult = MessageParser.ParseMessageUsingWOPIInspector(file);

            Assert.IsTrue(parsingResult, "Case failed, check the details information in error.txt file.");
        }
        /// <summary>
        /// onenote 2010,注意需要先在onenote中创建笔记本,并且将至转换为onenote2007格式
        /// 推荐使用onenote2016(个人版即可),API与2010类似,(去掉XMLSchema.xs2007参数即可)其他可参考API参数命名。
        /// 注意1:一定要将dll属性中的“嵌入互操作类型”属性关闭
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public string Ocr_2010(string imgPath)
        {
            try
            {
                #region 确定section_path存在
                section_path = @"C:\Users\zhensheng\Desktop\打杂\ocr\ocr.one";
                if (string.IsNullOrEmpty(section_path))
                {
                    Console.WriteLine("请先建立笔记本");
                    File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", "需要先在onenote中创建笔记本,并且将至转换为onenote2007格式,且将.one文件得路径赋值给section_path");
                    return("");
                }
                #endregion

                #region 准备数据
                //后缀
                var imgType = Path.GetExtension(imgPath);
                imgPath = imgPath.Replace(".", "");

                var data = File.ReadAllBytes(imgPath);
                //根据大小确定重试次数
                int fileSize = Convert.ToInt32(data.Length / 1024 / 1024); // 文件大小 单位M

                string guid   = Guid.NewGuid().ToString();
                string pageID = "{" + guid + "}{1}{B0}";  // 格式 {guid}{tab}{??}

                string     pageXml;
                XNamespace ns;

                var onenoteApp = new Microsoft.Office.Interop.OneNote.Application();  //onenote提供的API
                if (onenoteApp == null)
                {
                    File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", "Microsoft.Office.Interop.OneNote.Application()创建失败");
                    return("");
                }

                //重试使用
                XmlNode xmlNode;
                int     retry = 0;

                #endregion

                do
                {
                    #region 创建页面并返回pageID
                    string sectionID;
                    onenoteApp.OpenHierarchy(section_path, null, out sectionID, CreateFileType.cftSection);
                    onenoteApp.CreateNewPage(sectionID, out pageID);
                    #endregion

                    #region 获取onenote页面xml结构格式
                    string notebookXml;
                    onenoteApp.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml, XMLSchema.xs2007);
                    var doc = XDocument.Parse(notebookXml);
                    ns = doc.Root.Name.Namespace;

                    #endregion

                    #region 将图片插入页面
                    Tuple <string, int, int> imgInfo = this.GetBase64(data, imgType);
                    var page = new XDocument(new XElement(ns + "Page",
                                                          new XElement(ns + "Outline",
                                                                       new XElement(ns + "OEChildren",
                                                                                    new XElement(ns + "OE",
                                                                                                 new XElement(ns + "Image",
                                                                                                              new XAttribute("format", imgType), 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", imgInfo.Item2), new XAttribute("height", imgInfo.Item3)),
                                                                                                              new XElement(ns + "Data", imgInfo.Item1)))))));

                    page.Root.SetAttributeValue("ID", pageID);
                    onenoteApp.UpdatePageContent(page.ToString(), DateTime.MinValue, XMLSchema.xs2007);
                    #endregion

                    #region 通过轮询访问获取OCR识别的结果,轮询超时次数为6次
                    int count = 0;
                    do
                    {
                        System.Threading.Thread.Sleep(waitTime * (fileSize > 1 ? fileSize : 1)); // 小于1M的都默认1M
                        onenoteApp.GetPageContent(pageID, out pageXml, PageInfo.piBinaryData, XMLSchema.xs2007);
                    }while (pageXml == "" && count++ < 6);
                    #endregion

                    #region  除页面
                    onenoteApp.DeleteHierarchy(pageID, DateTime.MinValue);
                    //onenoteApp = null;
                    #endregion

                    #region 从xml中提取OCR识别后的文档信息,然后输出到string中
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(pageXml);
                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                    nsmgr.AddNamespace("one", ns.ToString());
                    xmlNode = xmlDoc.SelectSingleNode("//one:Image//one:OCRText", nsmgr);
                    #endregion
                }
                //如果OCR没有识别出信息,则重试三次(个人测试2010失败率为0.2~0.3)
                while (xmlNode == null && retry++ < 3);
                if (xmlNode == null)
                {
                    File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", "OCR没有识别出值");
                    return("");
                }
                var localFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\" + Guid.NewGuid().ToString() + ".txt";
                File.WriteAllText(localFilePath, xmlNode.InnerText.ToString());
                Console.WriteLine(xmlNode.InnerText.ToString());

                return(localFilePath);
            }
            catch (Exception e)
            {
                File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", e.ToString());
                return("");
            }
        }
Example #16
0
        public static void Main()
        {
            //Create New Instance of OneNote Application
            var oneNote = new Application();


            //Get current active page (see commented for current NoteBook/Section)

            /* string thisNoteBook = oneNote.Windows.CurrentWindow.CurrentNotebookId;
             * string thisSection  = oneNote.Windows.CurrentWindow.CurrentSectionId;    */
            string thisPage = oneNote.Windows.CurrentWindow.CurrentPageId;


            //Get the content of the page
            string xmlPage;

            oneNote.GetPageContent(thisPage, out xmlPage);


            //Declarations for paste
            string returnStringText = null;
            string Pasteresult      = null;


            //Set Namespace from our page
            string ns = xmlPage.Substring(xmlPage.IndexOf("xmlns:") + 6, xmlPage.IndexOf("=\"http://") - (xmlPage.IndexOf("xmlns:") + 6)) + @":";


            //Find the start and end of the page so that we can insert
            //a new section in between for our pasted content
            int    start    = xmlPage.LastIndexOf("</" + ns + "Page>");
            string startstr = xmlPage.Substring(0, start);
            string endstr   = xmlPage.Substring(start, xmlPage.Length - start);


            //New section for our content
            //(this is essential when the page in OneNote is currently empty)
            string outline =
                "<" + ns + "Outline >" +
                "<" + ns + "Position x=\"35.0\" y=\"60.0\"/>" +                              //This puts it just under title
                "<" + ns + "Size width=\"750.75\" height=\"13.50\" isSetByUser=\"true\"/>" + //Makes the box nice and big
                "<" + ns + "OEChildren>" +
                "<" + ns + "OE>" +
                "<" + ns + "T>" +
                "<![CDATA[]]>" +
                "</" + ns + "T>" +
                "</" + ns + "OE>" +
                "</" + ns + "OEChildren>" +
                "</" + ns + "Outline>";


            //Form the new page and replace our original page
            string newpage = startstr + outline + endstr;

            xmlPage = newpage;


/*         (Below I've specifically opened a new STAThread to show you the code,
 *          if you are using a console project then you only need [STAThread])                                                                    */

            //Get Text in Clipboard using full STAThread

            //Declarations to get out of the thread
            string    PastedText   = null;
            bool      containsRTF  = false;
            bool      containsHTML = false;
            bool      containsTEXT = false;
            bool      skipReplaces = false;
            Exception threadEx     = null;

            //Open new Thread
            Thread staThread = new Thread(
                delegate()
            {
                try
                {
                    //Query our clipboard
                    containsRTF  = Clipboard.ContainsText(TextDataFormat.Rtf);
                    containsHTML = Clipboard.ContainsText(TextDataFormat.Html);
                    containsTEXT = Clipboard.ContainsText(TextDataFormat.Text);

                    //Get relevant data
                    if (containsRTF == true && containsHTML == false)
                    {
                        PastedText = Clipboard.GetText(TextDataFormat.Rtf);
                    }
                    else if (containsHTML == true)
                    {
                        PastedText = Clipboard.GetText(TextDataFormat.Html);
                    }
                    else if (containsTEXT == true)
                    {
                        PastedText = Clipboard.GetText(TextDataFormat.Text);
                    }
                }

                catch (Exception ex)
                {
                    threadEx = ex;
                }
            });

            staThread.SetApartmentState(ApartmentState.STA);
            staThread.Start();
            staThread.Join();


            //Does the clipboard contain Rich Text? (we put an extra && just to be sure it isn't html as they can sometimes get confused)
            if (containsRTF == true && containsHTML == false)
            {
                string XAML = ConvertRtfToXaml(PastedText);

                //Get HTML from Rich Text
                Pasteresult = ConvertXAMLtoHTML.convert(XAML);
            }

            //Does the clipboard contain HTML?
            else if (containsHTML == true)
            {
                //Get HTML from Clipboard
                returnStringText = PastedText;

                //Get rid of everything before <body> or the first <span>
                int pFrom = returnStringText.IndexOf("<BODY");
                if (pFrom == -1)
                {
                    pFrom = returnStringText.IndexOf("<body");
                }
                if (pFrom == -1)
                {
                    pFrom = returnStringText.IndexOf("<SPAN");
                }
                if (pFrom == -1)
                {
                    pFrom = returnStringText.IndexOf("<span");
                }

                //Get rid of everything after </body> or the last </span>
                int pTo = returnStringText.LastIndexOf("</BODY>");
                if (pTo == -1)
                {
                    pTo = returnStringText.LastIndexOf("</body>");
                }
                if (pTo == -1)
                {
                    pTo = returnStringText.LastIndexOf("</SPAN>");
                }
                if (pTo == -1)
                {
                    pTo = returnStringText.LastIndexOf("</span>");
                }

                Pasteresult = returnStringText.Substring(pFrom, pTo - pFrom + 7);
            }

            //Does the clipboard contain Plain Text?
            else if (containsTEXT == true)
            {
                //Get the Text
                Pasteresult = PastedText;

                //Replace any "<" or ">" to ensure that it isn't read as HTML
                Pasteresult = Pasteresult.Replace("<", "&lt;").Replace(">", "&gt;");

                //Skip the block of HTML tag replacements
                skipReplaces = true;
            }

            if (skipReplaces == false)
            {
                //Remove all un-supported HTML tags (leaving pretty much just <span>'s)
                //Also make sure the HTML tags that remain are all lower case or onenote will complain
                Pasteresult = Pasteresult.Replace("<body", "<span").Replace("</body", "</span").Replace("<BODY", "<span").Replace("</BODY", "</span");
                Pasteresult = Pasteresult.Replace("<div", "<span").Replace("</div", "</span").Replace("</LI", "</li");
                Pasteresult = Pasteresult.Replace("<DIV", "<span").Replace("</DIV", "</span").Replace("<LI", "<li");
                Pasteresult = Pasteresult.Replace("<SPAN", "<span").Replace("</SPAN", "</span").Replace("</DIV", "</span");
                Pasteresult = Pasteresult.Replace("STYLE=", "style=").Replace("<UL", "<ul").Replace("</UL", "</ul");
                Pasteresult = Pasteresult.Replace("<!--EndFragment-->", "").Replace("<!--StartFragment-->", "");
                Pasteresult = Pasteresult.Replace("class=MsoNormal", "").Replace("mso-fareast-language:EN-US", "");
                Pasteresult = Pasteresult.Replace("<o:p>", "").Replace("</o:p>", "");
                Pasteresult = Pasteresult.Replace(System.Environment.NewLine, " ");
                Pasteresult = Pasteresult.Replace("</b>", "</span>").Replace("</B>", "</span>");
                Pasteresult = Pasteresult.Replace("</i>", "</span>").Replace("</I>", "</span>");
                Pasteresult = Pasteresult.Replace("<br>", "<p>").Replace("<BR>", "<p>");

                //Do we have any paragraphs? If we do then we need to replace them with new XML CDATA sections
                int containsBs = Regex.Matches(Pasteresult, "<[b,B]").Count;

                //For each <b>
                while (containsBs > 0)
                {
                    string replace = "<span style='font-weight:bold'>";

                    //find the position of the <p>
                    int    pos    = Pasteresult.IndexOf("<B", StringComparison.CurrentCultureIgnoreCase);
                    string afterB = Pasteresult.Substring(pos);
                    int    end    = afterB.IndexOf(">") + 1;


                    //If there isn't any left then break
                    if (pos < 0)
                    {
                        break;
                    }
                    else
                    {
                        //Else replace the <p> with the new block
                        Pasteresult = Pasteresult.Substring(0, pos) + replace + Pasteresult.Substring(pos + end);
                    }

                    containsBs -= 1;
                }

                //Do we have any paragraphs? If we do then we need to replace them with new XML CDATA sections
                int containsIs = Regex.Matches(Pasteresult, "<[i,I]").Count;

                //For each <i>
                while (containsIs > 0)
                {
                    string replace = "<span style='font-style:italic'>";

                    //find the position of the <p>
                    int    pos    = Pasteresult.IndexOf("<I", StringComparison.CurrentCultureIgnoreCase);
                    string afterI = Pasteresult.Substring(pos);
                    int    end    = afterI.IndexOf(">") + 1;


                    //If there isn't any left then break
                    if (pos < 0)
                    {
                        break;
                    }
                    else
                    {
                        //Else replace the <p> with the new block
                        Pasteresult = Pasteresult.Substring(0, pos) + replace + Pasteresult.Substring(pos + end);
                    }

                    containsIs -= 1;
                }
                //Do we have any paragraphs? If we do then we need to replace them with new XML CDATA sections
                int containsPs = Regex.Matches(Pasteresult, "<[p,P]").Count;


                //For each <p>
                while (containsPs > 0)
                {
                    //This is the text we will replace the <p>s with, it adds a new block
                    string replace = " ]]></" + ns + "T></" + ns + "OE><" + ns + "OE><" + ns + "T><![CDATA[<span";  //Start current block (this starts a new line)

                    //find the position of the <p>
                    int pos = Pasteresult.IndexOf("<P", StringComparison.CurrentCultureIgnoreCase);

                    //If there isn't any left then break
                    if (pos < 0)
                    {
                        break;
                    }
                    else
                    {
                        //Else replace the <p> with the new block
                        Pasteresult = Pasteresult.Substring(0, pos) + replace + Pasteresult.Substring(pos + "<P".Length);
                    }

                    containsPs -= 1;
                }

                //Remove the orphaned </p> tags
                Pasteresult = Pasteresult.Replace("</P>", "").Replace("</p>", "");
            }


            //Plain text will now re-join here


            //Get the position of the end of the last code block
            int    PageContent = xmlPage.LastIndexOf("]]></" + ns + "T>");
            string startofPage = xmlPage.Substring(0, PageContent);
            string endofPage   = xmlPage.Substring(PageContent, xmlPage.Length - PageContent);

            //Insert out pasted text into the current page
            string NewPage = startofPage + Pasteresult + endofPage;


            try
            {
                //Update the onenote page
                oneNote.UpdatePageContent(NewPage);

                //Just check that the encoding hasn't created any unwanted Â's
                oneNote.GetPageContent(thisPage, out xmlPage);

                int areThereAnyÂs = Regex.Matches(xmlPage, @"Â").Count;;

                if (areThereAnyÂs > 0)
                {
                    while (areThereAnyÂs > 0)
                    {
                        int pos = xmlPage.IndexOf(@"Â", StringComparison.CurrentCultureIgnoreCase);

                        string replace = "";
                        //If there isn't any left then break
                        if (pos < 0)
                        {
                            break;
                        }
                        else
                        {
                            //Else replace the <p> with the new block
                            xmlPage = xmlPage.Substring(0, pos) + replace + xmlPage.Substring(pos + 1);
                        }

                        //Increment numbers
                        areThereAnyÂs -= 1;
                    }

                    oneNote.UpdatePageContent(xmlPage);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + Environment.NewLine + Environment.NewLine + "Try using Ctrl + P", "Error Message");
            }


            oneNote = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        public static List <TaskItem> ReadTaskList(string notebook, string section, string page)
        {
            List <TaskItem> taskList = new List <TaskItem>();

            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;

            var notebookNodeList = doc.Descendants(ns + "Notebook").Where(n =>
                                                                          n.Attribute("name").Value.Contains(notebook));

            if (notebookNodeList == null)
            {
                return(taskList);
            }

            foreach (var notebookNode in notebookNodeList)
            {
                var sectionNode = notebookNode.Descendants(ns + "Section").Where(n =>
                                                                                 n.Attribute("name").Value.Contains(section)).FirstOrDefault();
                if (sectionNode != null)
                {
                    var pageNode = sectionNode.Descendants(ns + "Page")
                                   .Where(n => n.Attribute("name").Value.Contains(page))
                                   .FirstOrDefault();
                    if (pageNode != null)
                    {
                        string pageXml;
                        onenoteApp.GetPageContent(pageNode.Attribute("ID").Value, out pageXml);
                        var pageDoc = System.Xml.Linq.XDocument.Parse(pageXml);

                        Dictionary <int, TaskItemClass> TagDefsDic = new Dictionary <int, TaskItemClass>();
                        var tagDefs = pageDoc.Descendants(ns + "TagDef");
                        foreach (var tagDef in tagDefs)
                        {
                            TaskItemClass ti    = new TaskItemClass();
                            int           value = 0;
                            int.TryParse(tagDef.Attribute("index").Value, out value);
                            ti.Index = value;
                            ti.Name  = tagDef.Attribute("name").Value;
                            ti.Color = tagDef.Attribute("fontColor").Value;
                            TagDefsDic.Add(ti.Index, ti);
                        }

                        var taskTable = pageDoc.Descendants(ns + "Table").FirstOrDefault();
                        if (taskTable != null)
                        {
                            bool bfirst = true;
                            foreach (var taskRow in from row in taskTable.Descendants(ns + "Row") select row)
                            {
                                if (bfirst)
                                {
                                    bfirst = false;
                                    continue;
                                }

                                string[] cellValues    = new string[5];
                                int      index         = 0;
                                string   strTaskId     = "";
                                bool     bTaskComplete = false;
                                int      tagDefIndex   = -1;

                                foreach (var taskCell in from cells in taskRow.Descendants(ns + "Cell") select cells)
                                {
                                    if (index == 0)
                                    {
                                        var taskId = taskCell.Descendants(ns + "OutlookTask").FirstOrDefault();
                                        if (taskId == null)
                                        {
                                            break;
                                        }
                                        strTaskId     = taskId.Attribute("guidTask").Value;
                                        bTaskComplete = (taskId.Attribute("completed").Value == "true");
                                        if (string.IsNullOrEmpty(strTaskId))
                                        {
                                            break;
                                        }

                                        // Get TagDef
                                        var taskTag = taskCell.Descendants(ns + "Tag").FirstOrDefault();
                                        if (taskTag != null)
                                        {
                                            int.TryParse(taskTag.Attribute("index").Value, out tagDefIndex);
                                        }
                                    }

                                    cellValues[index++] = NoHtml(taskCell.Value);//taskCell.Descendants(ns + "T").First().Value;
                                }

                                if (string.IsNullOrEmpty(strTaskId))
                                {
                                    continue;
                                }

                                // 新建任务
                                TaskItem newTask = new TaskItem();

                                newTask.NoteBookId   = notebookNode.Attribute("ID").Value;
                                newTask.NoteBookName = notebookNode.Attribute("name").Value;
                                newTask.SectionId    = sectionNode.Attribute("ID").Value;
                                newTask.SectionName  = sectionNode.Attribute("name").Value;
                                newTask.PageId       = pageNode.Attribute("ID").Value;
                                newTask.PageName     = pageNode.Attribute("name").Value;

                                newTask.TaskOneNoteId = strTaskId;
                                newTask.TaskComplete  = bTaskComplete;
                                newTask.TaskName      = cellValues[0];
                                int value = 0;
                                int.TryParse(cellValues[1], out value);
                                newTask.TaskTimeEdit = value;
                                value = 0;
                                int.TryParse(cellValues[2], out value);
                                newTask.TaskTimeUsage = value;
                                value = 0;
                                int.TryParse(cellValues[3], out value);
                                newTask.TaskTimeInterrupt = value;
                                newTask.TaskComment       = cellValues[4];

                                if (tagDefIndex != -1)
                                {
                                    newTask.TaskClass = TagDefsDic[tagDefIndex];
                                }

                                taskList.Add(newTask);
                            }
                        }
                    }
                }
            }

            return(taskList);
        }
Example #18
0
        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);
        }
Example #19
0
        public async void ExportTasks(IRibbonControl control)
        {
            Window context            = control.Context as Window;
            CWin32WindowWrapper owner = new CWin32WindowWrapper((IntPtr)context.WindowHandle);

            Microsoft.Office.Interop.OneNote.Application onenote = new Microsoft.Office.Interop.OneNote.Application();
            string thisNoteBook = onenote.Windows.CurrentWindow.CurrentNotebookId;
            string thisSection  = onenote.Windows.CurrentWindow.CurrentSectionId;
            string thisPage     = onenote.Windows.CurrentWindow.CurrentPageId;

            String link;

            onenote.GetHyperlinkToObject(thisPage, System.String.Empty, out link);

            String xmlNotebooks;

            onenote.GetHierarchy(null,
                                 Microsoft.Office.Interop.OneNote.HierarchyScope.hsPages, out xmlNotebooks);

            var notebooks = XDocument.Parse(xmlNotebooks);

            var currentbook = from item in notebooks.Descendants(notebooks.Root.Name.Namespace + "Notebook")
                              where item.Attribute("ID").Value == thisNoteBook
                              select item;

            var notebook = currentbook.First().Attribute("name").Value;

            String xmlPage;

            onenote.GetPageContent(thisPage, out xmlPage);
            doc = XDocument.Parse(xmlPage);
            ns  = doc.Root.Name.Namespace;

            var pageTitle = RemoveHtmlTags(doc.Descendants(ns + "Title").First().Value);
            var title     = notebook + ": " + pageTitle;

            var tags = from tagDef in doc.Descendants(ns + "TagDef")
                       where tagDef.Attribute("symbol").Value == "3"
                       select tagDef;

            if (tags.Count() == 0)

            {
                MessageBox.Show(owner, "No tasks found on this page!", pageTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            else

            {
                var      index   = tags.First().Attribute("index").Value;
                string[] allTags = new string[2];
                int      i       = 0;
                foreach (var tag in tags)
                {
                    allTags[i] = tag.Attribute("index").Value;
                    i++;
                }
                var tasks = from oe in doc.Descendants(ns + "OE")
                            from item in oe.Elements(ns + "Tag")
                            //where item.Attribute("index").Value == index
                            where allTags.Contains(item.Attribute("index").Value)
                            where item.Attribute("completed").Value == "false"
                            select oe;
                if (tasks.Count() == 0)
                {
                    MessageBox.Show(owner, "No tasks found on this page!", pageTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }


                string allTasks  = "";
                string prefix    = title;
                string formTitle = "Tasks found: " + tasks.Count().ToString();
                if (prefix.Length > 60)
                {
                    prefix = prefix.Substring(0, 60);
                }
                int counter = 0;
                foreach (var task in tasks)
                {
                    counter++;
                    allTasks += "o    " + prefix + "\n       " + RemoveHtmlTags(task.Element(ns + "T").Value) + "\n\n";
                    if (counter > 4)
                    {
                        break;
                    }
                }
                string taskas = RemoveHtmlTags(tasks.ElementAt(0).Value);

                LoginForm login = new LoginForm();
                login.ShowDialog(owner);

                if (login.DialogResult == DialogResult.OK)
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                    ITodoistTokenlessClient tokenlessClient = new TodoistTokenlessClient();

                    try
                    {
                        if (login.email.Contains("@") == false)
                        {
                            login.email += "@ardi.lt";
                        }
                        ITodoistClient client = await tokenlessClient.LoginAsync(login.email, login.password);

                        var projects = await client.Projects.GetAsync();

                        TasksForm confirm = new TasksForm(formTitle, title, prefix, taskas, projects);
                        confirm.ShowDialog(owner);

                        if (confirm.DialogResult == DialogResult.OK)
                        {
                            var transaction = client.CreateTransaction();

                            if (confirm.id > 0)
                            {
                                foreach (var item in projects)
                                {
                                    if (item.Name == confirm.project)
                                    {
                                        foreach (var task in tasks)
                                        {
                                            var content = "[" + confirm.prefix + RemoveHtmlTags(task.Value) + "](" + link + ")";
                                            var todo    = new Todoist.Net.Models.Item(content);
                                            todo.ProjectId = item.Id;
                                            var taskId = await transaction.Items.AddAsync(todo);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                var projectId = await transaction.Project.AddAsync(new Todoist.Net.Models.Project(confirm.project));

                                foreach (var task in tasks)
                                {
                                    var content = "[" + confirm.prefix + RemoveHtmlTags(task.Value) + "](" + link + ")";
                                    var taskId  = await transaction.Items.AddAsync(new Todoist.Net.Models.Item(content, projectId));

                                    //await transaction.Notes.AddToItemAsync(new Todoist.Net.Models.Note("Task description"), taskId);
                                }
                            }

                            await transaction.CommitAsync();

                            System.Diagnostics.Process.Start("https://todoist.com");
                        }

                        confirm.Dispose();
                        confirm = null;
                    }
                    catch
                    {
                        MessageBox.Show(owner, "Bad user mail or password...", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                login.Dispose();
                login = null;
            }
        }
        public static bool UpdateTaskItem(TaskItem newTask)
        {
            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;

            var notebookNode = doc.Descendants(ns + "Notebook").Where(n =>
                                                                      n.Attribute("ID").Value.Equals(newTask.NoteBookId)).FirstOrDefault();

            if (notebookNode == null)
            {
                return(false);
            }

            var sectionNode = notebookNode.Descendants(ns + "Section").Where(n =>
                                                                             n.Attribute("ID").Value.Equals(newTask.SectionId)).FirstOrDefault();

            if (sectionNode == null)
            {
                return(false);
            }

            var pageNode = sectionNode.Descendants(ns + "Page")
                           .Where(n => n.Attribute("ID").Value.Equals(newTask.PageId))
                           .FirstOrDefault();

            if (pageNode != null)
            {
                string pageXml;
                onenoteApp.GetPageContent(pageNode.Attribute("ID").Value, out pageXml);
                var pageDoc   = System.Xml.Linq.XDocument.Parse(pageXml);
                var taskTable = pageDoc.Descendants(ns + "Table").FirstOrDefault();
                if (taskTable != null)
                {
                    bool bfirst = true;
                    foreach (var taskRow in from row in taskTable.Descendants(ns + "Row") select row)
                    {
                        if (bfirst)
                        {
                            bfirst = false;
                            continue;
                        }

                        string strTaskId = "";
                        var    taskCells = taskRow.Descendants(ns + "Cell");
                        if (taskCells.Count() != 5)
                        {
                            continue;
                        }

                        // 判断任务ID是否相同
                        var taskId = taskCells.ElementAt(0).Descendants(ns + "OutlookTask").FirstOrDefault();
                        if (taskId == null)
                        {
                            continue;
                        }

                        strTaskId = taskId.Attribute("guidTask").Value;
                        if (strTaskId != newTask.TaskOneNoteId)
                        {
                            continue;
                        }

                        // 更新任务信息到OneNote文件中
                        //taskCells.ElementAt(0).SetValue(newTask.TaskName);
                        taskId.SetAttributeValue("completed", newTask.TaskComplete);
                        if (newTask.TaskTimeEdit > 0)
                        {
                            taskCells.ElementAt(1).Descendants(ns + "T").FirstOrDefault().SetValue(
                                new XCData(newTask.TaskTimeEdit.ToString()).Value);
                        }

                        if (newTask.TaskTimeUsage > 0)
                        {
                            taskCells.ElementAt(2).Descendants(ns + "T").FirstOrDefault().SetValue(
                                new XCData(newTask.TaskTimeUsage.ToString()).Value);
                        }

                        if (newTask.TaskTimeInterrupt > 0)
                        {
                            taskCells.ElementAt(3).Descendants(ns + "T").FirstOrDefault().SetValue(
                                new XCData(newTask.TaskTimeInterrupt.ToString()).Value);
                        }

                        taskCells.ElementAt(4).Descendants(ns + "T").FirstOrDefault().SetValue(
                            new XCData(newTask.TaskComment).Value);
                        onenoteApp.UpdatePageContent(pageDoc.ToString(), DateTime.MinValue);
                        return(true);
                    }
                }
            }

            return(false);
        }
Example #21
0
        public void SimpleGantt(IRibbonControl control)
        {
            String xml;

            Microsoft.Office.Interop.OneNote.Application onenote = new Microsoft.Office.Interop.OneNote.Application();
            string thisNoteBook = onenote.Windows.CurrentWindow.CurrentNotebookId;
            string thisSection  = onenote.Windows.CurrentWindow.CurrentSectionId;
            string thisPage     = onenote.Windows.CurrentWindow.CurrentPageId;

            onenote.GetPageContent(thisPage, out xml);

            doc   = XDocument.Parse(xml);
            ns    = doc.Root.Name.Namespace;
            style = "font-family:Calibri;font-size:9.0pt;";

            //doc.Save("D:/one.xml");

            var gantts = from oe in doc.Descendants(ns + "OE")
                         from item in oe.Elements(ns + "Meta")
                         where item.Attribute("name").Value == "SimpleGanttTable"
                         select oe;

            if (gantts.Count() == 0)
            {
                var outline = new XElement(ns + "Outline",
                                           new XElement(ns + "Position",
                                                        new XAttribute("x", "36.0"),
                                                        new XAttribute("y", "80.0")
                                                        ),
                                           new XElement(ns + "Size",
                                                        new XAttribute("width", "600.0"),
                                                        new XAttribute("height", "100.0"),
                                                        new XAttribute("isSetByUser", "true")
                                                        ),
                                           new XElement(ns + "OEChildren",
                                                        new XElement(ns + "OE",
                                                                     new XElement(ns + "Meta",
                                                                                  new XAttribute("name", "SimpleGanttStart"),
                                                                                  new XAttribute("content", "")
                                                                                  ),
                                                                     new XElement(ns + "T", new XCData("Startas: ")) //DateTime.Now.ToString("yyyy.MM.dd")
                                                                     ),
                                                        new XElement(ns + "OE",
                                                                     new XElement(ns + "Meta",
                                                                                  new XAttribute("name", "SimpleGanttFinish"),
                                                                                  new XAttribute("content", "")
                                                                                  ),
                                                                     new XElement(ns + "T", new XCData("Terminas: "))
                                                                     ),
                                                        new XElement(ns + "OE",
                                                                     new XElement(ns + "T", new XCData(""))
                                                                     ),
                                                        new XElement(ns + "OE",
                                                                     new XElement(ns + "Meta",
                                                                                  new XAttribute("name", "SimpleGanttTable"),
                                                                                  new XAttribute("content", "")
                                                                                  ),
                                                                     new XElement(ns + "Table",
                                                                                  new XAttribute("bordersVisible", "true"),
                                                                                  new XAttribute("hasHeaderRow", "true"),

                                                                                  new XElement(ns + "Columns",
                                                                                               new XElement(ns + "Column",
                                                                                                            new XAttribute("index", "0"),
                                                                                                            new XAttribute("width", "140.0"),
                                                                                                            new XAttribute("isLocked", "true")
                                                                                                            ),
                                                                                               new XElement(ns + "Column",
                                                                                                            new XAttribute("index", "1"),
                                                                                                            new XAttribute("width", "40.0"),
                                                                                                            new XAttribute("isLocked", "true")
                                                                                                            ),
                                                                                               new XElement(ns + "Column",
                                                                                                            new XAttribute("index", "2"),
                                                                                                            new XAttribute("width", "40.0"),
                                                                                                            new XAttribute("isLocked", "true")
                                                                                                            ),
                                                                                               new XElement(ns + "Column",
                                                                                                            new XAttribute("index", "3"),
                                                                                                            new XAttribute("width", "80.0"),
                                                                                                            new XAttribute("isLocked", "true")
                                                                                                            )
                                                                                               ),

                                                                                  new XElement(ns + "Row",
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XAttribute("style", style),
                                                                                                                                      new XAttribute("alignment", "center"),
                                                                                                                                      new XElement(ns + "T", new XCData("UŽDUOTIS"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XAttribute("style", style),
                                                                                                                                      new XAttribute("alignment", "center"),
                                                                                                                                      new XElement(ns + "T", new XCData("STARTAS"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XAttribute("style", style),
                                                                                                                                      new XAttribute("alignment", "center"),
                                                                                                                                      new XElement(ns + "T", new XCData("TRUKMĖ"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XAttribute("style", style),
                                                                                                                                      new XAttribute("alignment", "center"),
                                                                                                                                      new XElement(ns + "T", new XCData("KAS?"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            )
                                                                                               ),

                                                                                  new XElement(ns + "Row",
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData("Užduotis 1"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData("1"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData("1"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData(""))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            )
                                                                                               ),


                                                                                  new XElement(ns + "Row",
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData(""))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData(""))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData(""))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData(""))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            )
                                                                                               )


                                                                                  )
                                                                     )
                                                        )
                                           );

                var page = doc.Descendants(ns + "Page").First();
                page.Add(outline);

                gantts = from oe in doc.Descendants(ns + "OE")
                         from item in oe.Elements(ns + "Meta")
                         where item.Attribute("name").Value == "SimpleGanttTable"
                         select oe;
            }

            gantt = gantts.ElementAt(0);

            var dates = from oe in doc.Descendants(ns + "OEChildren")
                        from item in oe.Descendants(ns + "Meta")
                        where item.Attribute("name").Value == "SimpleGanttTable"
                        select oe; //.Descendants(ns + "T");

            if (dates.Count() > 0)
            {
                //var startas = RemoveHtmlTags(dates.ElementAt(0).Value).Substring(8).Trim();
                var startas = RemoveHtmlTags(dates.Descendants(ns + "T").First().Value).Substring(8).Trim();
                DateTime.TryParse(startas, out ganttStart);
                //MessageBox.Show("Start: " + ganttStart);
            }


            // CALC COLUMNS //

            int    taskColumn     = 1;
            int    startColumn    = 2;
            int    durationColumn = 3;
            string taskName       = "";
            int    start          = 0;
            int    duration       = 0;
            int    maxPeriod      = 0;

            var items = gantt.Elements(ns + "Table").First().Descendants(ns + "Cell");
            int cols  = gantt.Elements(ns + "Table").First().Descendants(ns + "Column").Count();
            int _cols = cols;
            int col   = 0;

            foreach (var item in items)
            {
                col++;
                if (col == startColumn)
                {
                    Int32.TryParse(item.Value, out start);
                }
                if (col == durationColumn & start > 0 & Int32.TryParse(item.Value, out duration))
                {
                    if (start + duration - 1 > maxPeriod)
                    {
                        maxPeriod = start + duration - 1;
                    }
                }
                if (col == _cols)
                {
                    col = 0;
                }
            }

            // ADD COLUMNS //

            addGanttColumns(maxPeriod + 4 - cols);
            cols = gantt.Elements(ns + "Table").First().Descendants(ns + "Column").Count();

            // SET HEADER ROW //

            var headers = gantt.Descendants(ns + "Row").First().Descendants(ns + "Cell");

            foreach (var header in headers)
            {
                col++;
                if (col > 4)
                {
                    var    index = col - 4;
                    String txt   = index.ToString();
                    if (ganttStart != new DateTime())
                    {
                        var date = ganttStart.AddDays(col - 5);
                        txt = Right("0" + date.Month.ToString(), 2) + "." + Right("0" + date.Day.ToString(), 2);
                    }
                    header.Descendants(ns + "T").First().Value = txt;
                }
            }
            col = 0;

            // ADD COLORS //

            var cells = gantt.Elements(ns + "Table").First().Descendants(ns + "Cell");

            foreach (var cell in cells)
            {
                col++;
                if (col == taskColumn)
                {
                    taskName = cell.Value;
                }
                if (col == startColumn)
                {
                    Int32.TryParse(cell.Value, out start);
                }
                if (col == durationColumn)
                {
                    Int32.TryParse(cell.Value, out duration);
                }
                var color = cell.Attribute("shadingColor");
                if (color != null)
                {
                    cell.Attribute("shadingColor").Remove();
                }
                var finish  = start + duration - 1;
                var current = col - 4;
                if (col > 4 & current >= start & current <= finish)
                {
                    if (taskName == taskName.ToUpper())
                    {
                        cell.Add(new XAttribute("shadingColor", "#5F497A"));
                    }
                    else
                    {
                        cell.Add(new XAttribute("shadingColor", "#CCC1D9"));
                    }
                }
                else if (col > 4)
                {
                    if (col % 2 > 0)
                    {
                        cell.Add(new XAttribute("shadingColor", "#FAFAFA"));
                    }
                }
                if (col == cols)
                {
                    col = 0;
                }
            }

            //doc.Save("D:/doc.xml");
            onenote.UpdatePageContent(doc.ToString());
        }
Example #22
0
        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));
        }