コード例 #1
0
ファイル: MainFrm.cs プロジェクト: nscaife/Evernote2OneNote
        private void ImportNotesToOnenote(string folder, List<Note> notesEvernote, string exportFile)
        {
            syncStep = SyncStep.CalculateWhatToDo;
            int uploadcount = notesEvernote.Count;

            string temppath = Path.GetTempPath() + "\\ev2on";
            Directory.CreateDirectory(temppath);

            syncStep = SyncStep.ImportNotes;
            int counter = 0;

            {
                XmlTextReader xtrInput;
                XmlDocument xmlDocItem;

                try
                {
                    xtrInput = new XmlTextReader(exportFile);
                    while (xtrInput.Read())
                    {
                        while ((xtrInput.NodeType == XmlNodeType.Element) && (xtrInput.Name.ToLower() == "note"))
                        {
                            if (cancelled)
                            {
                                break;
                            }

                            xmlDocItem = new XmlDocument();
                            xmlDocItem.LoadXml(RemoveProblematicTags(HttpUtility.HtmlDecode(xtrInput.ReadOuterXml())));
                            XmlNode node = xmlDocItem.FirstChild;

                            // node is <note> element
                            // node.FirstChild.InnerText is <title>
                            node = node.FirstChild;

                            Note note = new Note();
                            note.Title = node.InnerText;
                            node = node.NextSibling;
                            note.Content = node.InnerXml;

                            XmlNodeList atts = xmlDocItem.GetElementsByTagName("resource");
                            foreach (XmlNode xmln in atts)
                            {
                                Attachment attachment = new Attachment();
                                attachment.Base64Data = xmln.FirstChild.InnerText;
                                byte[] data = Convert.FromBase64String(xmln.FirstChild.InnerText);
                                byte[] hash = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(data);
                                string hashHex = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();

                                attachment.Hash = hashHex;

                                XmlNodeList fns = xmlDocItem.GetElementsByTagName("file-name");
                                if (fns.Count > note.Attachments.Count)
                                {
                                    attachment.FileName = System.Security.SecurityElement.Escape(fns.Item(note.Attachments.Count).InnerText);
                                }

                                XmlNodeList mimes = xmlDocItem.GetElementsByTagName("mime");
                                if (mimes.Count > note.Attachments.Count)
                                {
                                    attachment.ContentType = mimes.Item(note.Attachments.Count).InnerText;
                                }

                                // generate a filename if not present
                                if (String.IsNullOrEmpty(attachment.FileName))
                                {
                                    switch (attachment.ContentType)
                                    {
                                        case "application/pdf":
                                            attachment.FileName = attachment.Hash + ".pdf";
                                            break;
                                        case "image/png":
                                            attachment.FileName = attachment.Hash + ".png";
                                            break;
                                        case "image/gif":
                                            attachment.FileName = attachment.Hash + ".gif";
                                            break;
                                        case "image/jpeg":
                                            attachment.FileName = attachment.Hash + ".jpg";
                                            break;
                                        default:
                                            //throw new Exception("Unknown Mime Type: " + attachment.ContentType);
                                            break;
                                    }
                                }

                                note.Attachments.Add(attachment);
                            }

                            XmlNodeList tagslist = xmlDocItem.GetElementsByTagName("tag");
                            foreach (XmlNode n in tagslist)
                            {
                                note.Tags.Add(n.InnerText);
                            }

                            XmlNodeList datelist = xmlDocItem.GetElementsByTagName("created");
                            foreach (XmlNode n in datelist)
                            {
                                try
                                {
                                    note.Date = DateTime.ParseExact(n.InnerText, "yyyyMMddTHHmmssZ", null);
                                }
                                catch (System.FormatException)
                                {
                                }
                            }

                            XmlNodeList datelist2 = xmlDocItem.GetElementsByTagName("updated");
                            foreach (XmlNode n in datelist2)
                            {
                                try
                                {
                                    note.Date = DateTime.ParseExact(n.InnerText, "yyyyMMddTHHmmssZ", null);
                                }
                                catch (System.FormatException)
                                {
                                }
                            }
                            XmlNodeList sourceurl = xmlDocItem.GetElementsByTagName("source-url");
                            note.SourceUrl = "";
                            foreach (XmlNode n in sourceurl)
                            {
                                try
                                {
                                    note.SourceUrl = n.InnerText;
                                    if (n.InnerText.StartsWith("file://"))
                                        note.SourceUrl = "";
                                }
                                catch (System.FormatException)
                                {
                                }
                            }

                            SetInfo(null, string.Format("importing note ({0} of {1}) : \"{2}\"", counter + 1, uploadcount, note.Title), counter++, uploadcount);

                            string htmlBody = note.Content;

                            List<string> tempfiles = new List<string>();
                            string xmlAttachments = "";
                            foreach (Attachment attachment in note.Attachments)
                            {
                                // save the attached file
                                string tempfilepath = temppath + "\\";
                                byte[] data = Convert.FromBase64String(attachment.Base64Data);
                                if ((attachment.FileName != null) && (attachment.FileName.Length > 0))
                                {
                                    string name = attachment.FileName;
                                    string invalid = new string(Path.GetInvalidFileNameChars());
                                    foreach (char c in invalid)
                                    {
                                        name = name.Replace(c.ToString(), "");
                                    }
                                    if (name.Length >= (240 - tempfilepath.Length))
                                        name = name.Substring(name.Length - (240 - tempfilepath.Length));
                                    tempfilepath += name;
                                }
                                else
                                    tempfilepath += attachment.Hash;
                                Stream fs = new FileStream(tempfilepath, FileMode.Create);
                                fs.Write(data, 0, data.Length);
                                fs.Close();
                                tempfiles.Add(tempfilepath);

                                Regex rx = new Regex(@"<en-media\b[^>]*?hash=""" + attachment.Hash + @"""[^>]*/>", RegexOptions.IgnoreCase);
                                if ((attachment.ContentType != null) && (attachment.ContentType.Contains("image") && rx.Match(htmlBody).Success))
                                {
                                    // replace the <en-media /> tag with an <img /> tag
                                    htmlBody = rx.Replace(htmlBody, @"<img src=""file:///" + tempfilepath + @"""/>");
                                }
                                else
                                {
                                    rx = new Regex(@"<en-media\b[^>]*?hash=""" + attachment.Hash + @"""[^>]*></en-media>", RegexOptions.IgnoreCase);
                                    if ((attachment.ContentType != null) && (attachment.ContentType.Contains("image") && rx.Match(htmlBody).Success))
                                    {
                                        // replace the <en-media /> tag with an <img /> tag
                                        htmlBody = rx.Replace(htmlBody, @"<img src=""file:///" + tempfilepath + @"""/>");
                                    }
                                    else
                                    {
                                        if ((attachment.FileName != null) && (attachment.FileName.Length > 0))
                                            xmlAttachments += string.Format("<one:InsertedFile pathSource=\"{0}\" preferredName=\"{1}\" />", tempfilepath, attachment.FileName);
                                        else
                                            xmlAttachments += string.Format("<one:InsertedFile pathSource=\"{0}\" preferredName=\"{1}\" />", tempfilepath, attachment.Hash);
                                    }
                                }
                            }
                            note.Attachments.Clear();

                            Regex rx2 = new Regex("style=\\\"[^\\\"]*\\\"", RegexOptions.IgnoreCase);
                            htmlBody = rx2.Replace(htmlBody, string.Empty);
                            rx2 = new Regex(@"<!\[CDATA\[<\?xml version=""1.0""[^?]*\?>", RegexOptions.IgnoreCase);
                            htmlBody = rx2.Replace(htmlBody, string.Empty);
                            htmlBody = htmlBody.Replace(@"<!DOCTYPE en-note SYSTEM ""http://xml.evernote.com/pub/enml2.dtd"">", string.Empty);
                            htmlBody = htmlBody.Replace("<en-note>", "<body>");
                            htmlBody = htmlBody.Replace("</en-note>]]>", "</body>");
                            htmlBody = htmlBody.Replace("</en-note>\n]]>", "</body>");
                            htmlBody = htmlBody.Replace("<en-note />]]", "<body></body>");
                            htmlBody = htmlBody.Trim();
                            htmlBody = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN""><head></head>" + htmlBody;

                            string emailBody = htmlBody;
                            Regex rex = new Regex(@"^date:(.*)$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                            emailBody = rex.Replace(emailBody, "Date: " + note.Date.ToString("ddd, dd MMM yyyy HH:mm:ss K"));
                            emailBody = emailBody.Replace("&apos;", "'");

                            try
                            {
                                // Get the hierarchy for all the notebooks
                                if ((note.Tags.Count > 0) && (!m_bUseUnfiledSection) && (!ignoreTagsRadioButton.Checked))
                                {
                                    foreach (string tag in note.Tags)
                                    {
                                        string sectionId = GetSection(tag);
                                        onApp.CreateNewPage(sectionId, out m_PageID, Microsoft.Office.Interop.OneNote.NewPageStyle.npsBlankPageWithTitle);
                                        string textToSave;
                                        onApp.GetPageContent(m_PageID, out textToSave, Microsoft.Office.Interop.OneNote.PageInfo.piBasic);
                                        //OneNote uses HTML for the xml string to pass to the UpdatePageContent, so use the
                                        //Outlook HTMLBody property.  It coerces rtf and plain text to HTML.
                                        int outlineID = new System.Random().Next();
                                        //string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, m_outlineIDMetaName);
                                        string xmlSource = string.Format(m_xmlSourceUrl, note.SourceUrl);
                                        string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), note.SourceUrl.Length > 0 ? xmlSource : "");
                                        string xml = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), xmlAttachments, note.Date.ToString("yyyy'-'MM'-'ddTHH':'mm':'ss'Z'"));
                                        onApp.UpdatePageContent(xml, DateTime.MinValue, OneNote.XMLSchema.xs2010, true);
                                        if (newNoteForFirstTagRadioButton.Checked) { break; }
                                    }
                                }
                                else
                                {
                                    string sectionId = m_bUseUnfiledSection ? newnbID : GetSection("unspecified");
                                    onApp.CreateNewPage(sectionId, out m_PageID, Microsoft.Office.Interop.OneNote.NewPageStyle.npsBlankPageWithTitle);
                                    string textToSave;
                                    onApp.GetPageContent(m_PageID, out textToSave, Microsoft.Office.Interop.OneNote.PageInfo.piBasic);
                                    //OneNote uses HTML for the xml string to pass to the UpdatePageContent, so use the
                                    //Outlook HTMLBody property.  It coerces rtf and plain text to HTML.
                                    int outlineID = new System.Random().Next();
                                    //string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, m_outlineIDMetaName);
                                    string xmlSource = string.Format(m_xmlSourceUrl, note.SourceUrl);
                                    string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), note.SourceUrl.Length > 0 ? xmlSource : "");
                                    string xml = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), xmlAttachments, note.Date.ToString("yyyy'-'MM'-'ddTHH':'mm':'ss'Z'"));
                                    onApp.UpdatePageContent(xml, DateTime.MinValue, OneNote.XMLSchema.xs2010, true);
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(string.Format("Note:{0}\n{1}", note.Title, ex.ToString()));
                            }

                            foreach (string p in tempfiles)
                            {
                                File.Delete(p);
                            }
                        }
                    }

                    xtrInput.Close();
                }
                catch (System.Xml.XmlException ex)
                {
                    // happens if the notebook was empty or does not exist.
                    MessageBox.Show(string.Format("The notebook \"{0}\" either does not exist or empty!\n{1}", ENNotebookName, ex.ToString()));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Exception importing notes:\n{0}", ex.ToString()));
                }
            }
        }
コード例 #2
0
ファイル: MainFrm.cs プロジェクト: gavioto/evimsync
        private void ImportNotesToOnenote(string folder, List<Note> notesEvernote, string exportFile)
        {
            syncStep = SyncStep.CalculateWhatToDo;
            int uploadcount = notesEvernote.Count;

            string temppath = Path.GetTempPath() + "\\ev2on";
            Directory.CreateDirectory(temppath);

            syncStep = SyncStep.ImportNotes;
            int counter = 0;


            {
                XmlTextReader xtrInput;
                XmlDocument xmlDocItem;
                string xmltext = "";
                try
                {
                    xtrInput = new XmlTextReader(exportFile);
                    while (xtrInput.Read())
                    {
                        while ((xtrInput.NodeType == XmlNodeType.Element) && (xtrInput.Name.ToLower() == "note"))
                        {
                            if (cancelled)
                            {
                                break;
                            }

                            xmlDocItem = new XmlDocument();
                            xmltext = SanitizeXml(xtrInput.ReadOuterXml());
                            xmlDocItem.LoadXml(xmltext);
                            XmlNode node = xmlDocItem.FirstChild;

                            // node is <note> element
                            // node.FirstChild.InnerText is <title>
                            node = node.FirstChild;

                            Note note = new Note();
                            note.Title = HttpUtility.HtmlDecode(node.InnerText);
                            node = node.NextSibling;
                            note.Content = HttpUtility.HtmlDecode(node.InnerXml);

                            XmlNodeList atts = xmlDocItem.GetElementsByTagName("resource");
                            foreach (XmlNode xmln in atts)
                            {
                                Attachment attachment = new Attachment();
                                attachment.Base64Data = xmln.FirstChild.InnerText;
                                byte[] data = Convert.FromBase64String(xmln.FirstChild.InnerText);
                                byte[] hash = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(data);
                                string hashHex = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();

                                attachment.Hash = hashHex;

                                XmlNodeList fns = xmlDocItem.GetElementsByTagName("file-name");
                                if (fns.Count > note.Attachments.Count)
                                {
                                    attachment.FileName = HttpUtility.HtmlDecode(fns.Item(note.Attachments.Count).InnerText);
                                    string invalid = new string(Path.GetInvalidFileNameChars());
                                    foreach (char c in invalid)
                                    {
                                        attachment.FileName = attachment.FileName.Replace(c.ToString(), "");
                                    }
                                    attachment.FileName = System.Security.SecurityElement.Escape(attachment.FileName);
                                }

                                XmlNodeList mimes = xmlDocItem.GetElementsByTagName("mime");
                                if (mimes.Count > note.Attachments.Count)
                                {
                                    attachment.ContentType = HttpUtility.HtmlDecode(mimes.Item(note.Attachments.Count).InnerText);
                                }

                                note.Attachments.Add(attachment);
                            }

                            XmlNodeList tagslist = xmlDocItem.GetElementsByTagName("tag");
                            foreach (XmlNode n in tagslist)
                            {
                                note.Tags.Add(HttpUtility.HtmlDecode(n.InnerText));
                            }

                            XmlNodeList datelist = xmlDocItem.GetElementsByTagName("created");
                            foreach (XmlNode n in datelist)
                            {
                                DateTime dateCreated;

                                if (DateTime.TryParseExact(n.InnerText, "yyyyMMddTHHmmssZ", CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal, out dateCreated))
                                {
                                    note.Date = dateCreated;
                                }
                            }
                            if (modifiedDateCheckbox.Checked)
                            {
                                XmlNodeList datelist2 = xmlDocItem.GetElementsByTagName("updated");
                                foreach (XmlNode n in datelist2)
                                {
                                    DateTime dateUpdated;

                                    if (DateTime.TryParseExact(n.InnerText, "yyyyMMddTHHmmssZ", CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal, out dateUpdated))
                                    {
                                        note.Date = dateUpdated;
                                    }
                                }
                            }

                            XmlNodeList sourceurl = xmlDocItem.GetElementsByTagName("source-url");
                            note.SourceUrl = "";
                            foreach (XmlNode n in sourceurl)
                            {
                                try
                                {
                                    note.SourceUrl = n.InnerText;
                                    if (n.InnerText.StartsWith("file://"))
                                        note.SourceUrl = "";
                                }
                                catch (System.FormatException)
                                {
                                }
                            }

                            if (cmdDate > note.Date)
                                continue;

                            SetInfo(null, string.Format("importing note ({0} of {1}) : \"{2}\"", counter + 1, uploadcount, note.Title), counter++, uploadcount);

                            string htmlBody = note.Content;

                            List<string> tempfiles = new List<string>();
                            string xmlAttachments = "";
                            foreach (Attachment attachment in note.Attachments)
                            {
                                // save the attached file
                                string tempfilepath = temppath + "\\";
                                byte[] data = Convert.FromBase64String(attachment.Base64Data);
                                tempfilepath += attachment.Hash;
                                Stream fs = new FileStream(tempfilepath, FileMode.Create);
                                fs.Write(data, 0, data.Length);
                                fs.Close();
                                tempfiles.Add(tempfilepath);

                                Regex rx = new Regex(@"<en-media\b[^>]*?hash=""" + attachment.Hash + @"""[^>]*/>", RegexOptions.IgnoreCase);
                                if ((attachment.ContentType != null) && (attachment.ContentType.Contains("image") && rx.Match(htmlBody).Success))
                                {
                                    // replace the <en-media /> tag with an <img /> tag
                                    htmlBody = rx.Replace(htmlBody, @"<img src=""file:///" + tempfilepath + @"""/>");
                                }
                                else
                                {
                                    rx = new Regex(@"<en-media\b[^>]*?hash=""" + attachment.Hash + @"""[^>]*></en-media>", RegexOptions.IgnoreCase);
                                    if ((attachment.ContentType != null) && (attachment.ContentType.Contains("image") && rx.Match(htmlBody).Success))
                                    {
                                        // replace the <en-media /> tag with an <img /> tag
                                        htmlBody = rx.Replace(htmlBody, @"<img src=""file:///" + tempfilepath + @"""/>");
                                    }
                                    else
                                    {
                                        if ((attachment.FileName != null) && (attachment.FileName.Length > 0))
                                            xmlAttachments += string.Format("<one:InsertedFile pathSource=\"{0}\" preferredName=\"{1}\" />", tempfilepath, attachment.FileName);
                                        else
                                            xmlAttachments += string.Format("<one:InsertedFile pathSource=\"{0}\" preferredName=\"{1}\" />", tempfilepath, attachment.Hash);
                                    }
                                }
                            }
                            note.Attachments.Clear();

                            htmlBody = rxStyle.Replace(htmlBody, "${text}");
                            htmlBody = rxComment.Replace(htmlBody, string.Empty);
                            htmlBody = rxCDATA.Replace(htmlBody, string.Empty);
                            htmlBody = rxDtd.Replace(htmlBody, string.Empty);
                            htmlBody = rxBodyStart.Replace(htmlBody, "<body>");
                            htmlBody = rxBodyEnd.Replace(htmlBody, "</body>");
                            htmlBody = rxBodyEmpty.Replace(htmlBody, "<body></body>");
                            htmlBody = htmlBody.Trim();
                            htmlBody = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN""><head></head>" + htmlBody;

                            string emailBody = htmlBody;
                            emailBody = rxDate.Replace(emailBody, "Date: " + note.Date.ToString("ddd, dd MMM yyyy HH:mm:ss K"));
                            emailBody = emailBody.Replace("&apos;", "'");
                            emailBody = emailBody.Replace("’", "'");
                            emailBody = rxCDATAInner.Replace(emailBody, "&lt;![CDATA[${text}]]&gt;");
                            emailBody = emailBody.Replace("‘", "'");

                            try
                            {
                                // Get the hierarchy for all the notebooks
                                if ((note.Tags.Count > 0) && (!m_bUseUnfiledSection))
                                {
                                    foreach (string tag in note.Tags)
                                    {
                                        string sectionId = GetSection(tag);
                                        onApp.CreateNewPage(sectionId, out m_PageID, Microsoft.Office.Interop.OneNote.NewPageStyle.npsBlankPageWithTitle);
                                        string textToSave;
                                        onApp.GetPageContent(m_PageID, out textToSave, Microsoft.Office.Interop.OneNote.PageInfo.piBasic);
                                        //OneNote uses HTML for the xml string to pass to the UpdatePageContent, so use the
                                        //Outlook HTMLBody property.  It coerces rtf and plain text to HTML.
                                        int outlineID = new System.Random().Next();
                                        //string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, m_outlineIDMetaName);
                                        string xmlSource = string.Format(m_xmlSourceUrl, note.SourceUrl);
                                        string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), note.SourceUrl.Length > 0 ? xmlSource : "");
                                        string xml = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), xmlAttachments, note.Date.ToString("yyyy'-'MM'-'ddTHH':'mm':'ss'Z'"));
                                        onApp.UpdatePageContent(xml, DateTime.MinValue, OneNote.XMLSchema.xs2013, true);
                                    }
                                }
                                else
                                {
                                    string sectionId = m_bUseUnfiledSection ? newnbID : GetSection("not specified");
                                    onApp.CreateNewPage(sectionId, out m_PageID, Microsoft.Office.Interop.OneNote.NewPageStyle.npsBlankPageWithTitle);
                                    string textToSave;
                                    onApp.GetPageContent(m_PageID, out textToSave, Microsoft.Office.Interop.OneNote.PageInfo.piBasic);
                                    //OneNote uses HTML for the xml string to pass to the UpdatePageContent, so use the
                                    //Outlook HTMLBody property.  It coerces rtf and plain text to HTML.
                                    int outlineID = new System.Random().Next();
                                    //string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, m_outlineIDMetaName);
                                    string xmlSource = string.Format(m_xmlSourceUrl, note.SourceUrl);
                                    string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), note.SourceUrl.Length > 0 ? xmlSource : "");
                                    string xml = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), xmlAttachments, note.Date.ToString("yyyy'-'MM'-'ddTHH':'mm':'ss'Z'"));
                                    onApp.UpdatePageContent(xml, DateTime.MinValue, OneNote.XMLSchema.xs2013, true);
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(string.Format("Note:{0}\n{1}", note.Title, ex.ToString()));
                            }

                            foreach (string p in tempfiles)
                            {
                                File.Delete(p);
                            }
                        }
                    }

                    xtrInput.Close();
                }
                catch (System.Xml.XmlException ex)
                {
                    // happens if the notebook was empty or does not exist.
                    // Or due to a parsing error if a note isn't properly xml encoded
                    // try to find the name of the note that's causing the problems
                    string notename = "";
                    if (xmltext.Length > 0)
                    {
                        var notematch = rxNote.Match(xmltext);
                        if (notematch.Groups.Count == 2)
                        {
                            notename = notematch.Groups[1].ToString();
                        }
                    }
                    if (notename.Length > 0)
                        MessageBox.Show(string.Format("Error parsing the note \"{2}\" in notebook \"{0}\",\n{1}", ENNotebookName, ex.ToString(), notename));
                    else
                        MessageBox.Show(string.Format("Error parsing the notebook \"{0}\"\n{1}", ENNotebookName, ex.ToString()));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Exception importing notes:\n{0}", ex.ToString()));
                }
            }
        }
コード例 #3
0
        private void ImportNotesToOnenote(string folder, List <Note> notesEvernote, string exportFile)
        {
            syncStep = SyncStep.CalculateWhatToDo;
            int uploadcount = notesEvernote.Count;

            string temppath = Path.GetTempPath() + "\\ev2on";

            Directory.CreateDirectory(temppath);

            syncStep = SyncStep.ImportNotes;
            int counter = 0;


            {
                XmlTextReader xtrInput;
                XmlDocument   xmlDocItem;
                string        xmltext = "";
                try
                {
                    xtrInput = new XmlTextReader(exportFile);
                    while (xtrInput.Read())
                    {
                        while ((xtrInput.NodeType == XmlNodeType.Element) && (xtrInput.Name.ToLower() == "note"))
                        {
                            if (cancelled)
                            {
                                break;
                            }

                            xmlDocItem = new XmlDocument();
                            xmltext    = SanitizeXml(xtrInput.ReadOuterXml());
                            xmlDocItem.LoadXml(xmltext);
                            XmlNode node = xmlDocItem.FirstChild;

                            // node is <note> element
                            // node.FirstChild.InnerText is <title>
                            node = node.FirstChild;

                            Note note = new Note();
                            note.Title   = HttpUtility.HtmlDecode(node.InnerText);
                            node         = node.NextSibling;
                            note.Content = HttpUtility.HtmlDecode(node.InnerXml);

                            XmlNodeList atts = xmlDocItem.GetElementsByTagName("resource");
                            foreach (XmlNode xmln in atts)
                            {
                                Attachment attachment = new Attachment();
                                attachment.Base64Data = xmln.FirstChild.InnerText;
                                byte[] data    = Convert.FromBase64String(xmln.FirstChild.InnerText);
                                byte[] hash    = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(data);
                                string hashHex = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();

                                attachment.Hash = hashHex;

                                XmlNodeList fns = xmlDocItem.GetElementsByTagName("file-name");
                                if (fns.Count > note.Attachments.Count)
                                {
                                    attachment.FileName = HttpUtility.HtmlDecode(fns.Item(note.Attachments.Count).InnerText);
                                    string invalid = new string(Path.GetInvalidFileNameChars());
                                    foreach (char c in invalid)
                                    {
                                        attachment.FileName = attachment.FileName.Replace(c.ToString(), "");
                                    }
                                    attachment.FileName = System.Security.SecurityElement.Escape(attachment.FileName);
                                }

                                XmlNodeList mimes = xmlDocItem.GetElementsByTagName("mime");
                                if (mimes.Count > note.Attachments.Count)
                                {
                                    attachment.ContentType = HttpUtility.HtmlDecode(mimes.Item(note.Attachments.Count).InnerText);
                                }

                                note.Attachments.Add(attachment);
                            }

                            XmlNodeList tagslist = xmlDocItem.GetElementsByTagName("tag");
                            foreach (XmlNode n in tagslist)
                            {
                                note.Tags.Add(HttpUtility.HtmlDecode(n.InnerText));
                            }

                            XmlNodeList datelist = xmlDocItem.GetElementsByTagName("created");
                            foreach (XmlNode n in datelist)
                            {
                                DateTime dateCreated;

                                if (DateTime.TryParseExact(n.InnerText, "yyyyMMddTHHmmssZ", CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal, out dateCreated))
                                {
                                    note.Date = dateCreated;
                                }
                            }
                            if (modifiedDateCheckbox.Checked)
                            {
                                XmlNodeList datelist2 = xmlDocItem.GetElementsByTagName("updated");
                                foreach (XmlNode n in datelist2)
                                {
                                    DateTime dateUpdated;

                                    if (DateTime.TryParseExact(n.InnerText, "yyyyMMddTHHmmssZ", CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal, out dateUpdated))
                                    {
                                        note.Date = dateUpdated;
                                    }
                                }
                            }

                            XmlNodeList sourceurl = xmlDocItem.GetElementsByTagName("source-url");
                            note.SourceUrl = "";
                            foreach (XmlNode n in sourceurl)
                            {
                                try
                                {
                                    note.SourceUrl = n.InnerText;
                                    if (n.InnerText.StartsWith("file://"))
                                    {
                                        note.SourceUrl = "";
                                    }
                                }
                                catch (System.FormatException)
                                {
                                }
                            }

                            if (cmdDate > note.Date)
                            {
                                continue;
                            }

                            SetInfo(null, string.Format("importing note ({0} of {1}) : \"{2}\"", counter + 1, uploadcount, note.Title), counter++, uploadcount);

                            string htmlBody = note.Content;

                            List <string> tempfiles      = new List <string>();
                            string        xmlAttachments = "";
                            foreach (Attachment attachment in note.Attachments)
                            {
                                // save the attached file
                                string tempfilepath = temppath + "\\";
                                byte[] data         = Convert.FromBase64String(attachment.Base64Data);
                                tempfilepath += attachment.Hash;
                                Stream fs = new FileStream(tempfilepath, FileMode.Create);
                                fs.Write(data, 0, data.Length);
                                fs.Close();
                                tempfiles.Add(tempfilepath);

                                Regex rx = new Regex(@"<en-media\b[^>]*?hash=""" + attachment.Hash + @"""[^>]*/>", RegexOptions.IgnoreCase);
                                if ((attachment.ContentType != null) && (attachment.ContentType.Contains("image") && rx.Match(htmlBody).Success))
                                {
                                    // replace the <en-media /> tag with an <img /> tag
                                    htmlBody = rx.Replace(htmlBody, @"<img src=""file:///" + tempfilepath + @"""/>");
                                }
                                else
                                {
                                    rx = new Regex(@"<en-media\b[^>]*?hash=""" + attachment.Hash + @"""[^>]*></en-media>", RegexOptions.IgnoreCase);
                                    if ((attachment.ContentType != null) && (attachment.ContentType.Contains("image") && rx.Match(htmlBody).Success))
                                    {
                                        // replace the <en-media /> tag with an <img /> tag
                                        htmlBody = rx.Replace(htmlBody, @"<img src=""file:///" + tempfilepath + @"""/>");
                                    }
                                    else
                                    {
                                        if ((attachment.FileName != null) && (attachment.FileName.Length > 0))
                                        {
                                            xmlAttachments += string.Format("<one:InsertedFile pathSource=\"{0}\" preferredName=\"{1}\" />", tempfilepath, attachment.FileName);
                                        }
                                        else
                                        {
                                            xmlAttachments += string.Format("<one:InsertedFile pathSource=\"{0}\" preferredName=\"{1}\" />", tempfilepath, attachment.Hash);
                                        }
                                    }
                                }
                            }
                            note.Attachments.Clear();

                            htmlBody = rxStyle.Replace(htmlBody, "${text}");
                            htmlBody = rxComment.Replace(htmlBody, string.Empty);
                            htmlBody = rxCDATA.Replace(htmlBody, string.Empty);
                            htmlBody = rxDtd.Replace(htmlBody, string.Empty);
                            htmlBody = rxBodyStart.Replace(htmlBody, "<body>");
                            htmlBody = rxBodyEnd.Replace(htmlBody, "</body>");
                            htmlBody = rxBodyEmpty.Replace(htmlBody, "<body></body>");
                            htmlBody = htmlBody.Trim();
                            htmlBody = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN""><head></head>" + htmlBody;

                            string emailBody = htmlBody;
                            emailBody = rxDate.Replace(emailBody, "Date: " + note.Date.ToString("ddd, dd MMM yyyy HH:mm:ss K"));
                            emailBody = emailBody.Replace("&apos;", "'");
                            emailBody = emailBody.Replace("’", "'");
                            emailBody = rxCDATAInner.Replace(emailBody, "&lt;![CDATA[${text}]]&gt;");
                            emailBody = emailBody.Replace("‘", "'");

                            try
                            {
                                // Get the hierarchy for all the notebooks
                                if ((note.Tags.Count > 0) && (!m_bUseUnfiledSection))
                                {
                                    foreach (string tag in note.Tags)
                                    {
                                        string sectionId = GetSection(tag);
                                        onApp.CreateNewPage(sectionId, out m_PageID, Microsoft.Office.Interop.OneNote.NewPageStyle.npsBlankPageWithTitle);
                                        string textToSave;
                                        onApp.GetPageContent(m_PageID, out textToSave, Microsoft.Office.Interop.OneNote.PageInfo.piBasic);
                                        //OneNote uses HTML for the xml string to pass to the UpdatePageContent, so use the
                                        //Outlook HTMLBody property.  It coerces rtf and plain text to HTML.
                                        int outlineID = new System.Random().Next();
                                        //string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, m_outlineIDMetaName);
                                        string xmlSource      = string.Format(m_xmlSourceUrl, note.SourceUrl);
                                        string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), note.SourceUrl.Length > 0 ? xmlSource : "");
                                        string xml            = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), xmlAttachments, note.Date.ToString("yyyy'-'MM'-'ddTHH':'mm':'ss'Z'"));
                                        onApp.UpdatePageContent(xml, DateTime.MinValue, OneNote.XMLSchema.xs2013, true);
                                    }
                                }
                                else
                                {
                                    string sectionId = m_bUseUnfiledSection ? newnbID : GetSection("not specified");
                                    onApp.CreateNewPage(sectionId, out m_PageID, Microsoft.Office.Interop.OneNote.NewPageStyle.npsBlankPageWithTitle);
                                    string textToSave;
                                    onApp.GetPageContent(m_PageID, out textToSave, Microsoft.Office.Interop.OneNote.PageInfo.piBasic);
                                    //OneNote uses HTML for the xml string to pass to the UpdatePageContent, so use the
                                    //Outlook HTMLBody property.  It coerces rtf and plain text to HTML.
                                    int outlineID = new System.Random().Next();
                                    //string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, m_outlineIDMetaName);
                                    string xmlSource      = string.Format(m_xmlSourceUrl, note.SourceUrl);
                                    string outlineContent = string.Format(m_xmlNewOutlineContent, emailBody, outlineID, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), note.SourceUrl.Length > 0 ? xmlSource : "");
                                    string xml            = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("&apos;", "'"), xmlAttachments, note.Date.ToString("yyyy'-'MM'-'ddTHH':'mm':'ss'Z'"));
                                    onApp.UpdatePageContent(xml, DateTime.MinValue, OneNote.XMLSchema.xs2013, true);
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(string.Format("Note:{0}\n{1}", note.Title, ex.ToString()));
                            }

                            foreach (string p in tempfiles)
                            {
                                File.Delete(p);
                            }
                        }
                    }

                    xtrInput.Close();
                }
                catch (System.Xml.XmlException ex)
                {
                    // happens if the notebook was empty or does not exist.
                    // Or due to a parsing error if a note isn't properly xml encoded
                    // try to find the name of the note that's causing the problems
                    string notename = "";
                    if (xmltext.Length > 0)
                    {
                        var notematch = rxNote.Match(xmltext);
                        if (notematch.Groups.Count == 2)
                        {
                            notename = notematch.Groups[1].ToString();
                        }
                    }
                    if (notename.Length > 0)
                    {
                        MessageBox.Show(string.Format("Error parsing the note \"{2}\" in notebook \"{0}\",\n{1}", ENNotebookName, ex.ToString(), notename));
                    }
                    else
                    {
                        MessageBox.Show(string.Format("Error parsing the notebook \"{0}\"\n{1}", ENNotebookName, ex.ToString()));
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Exception importing notes:\n{0}", ex.ToString()));
                }
            }
        }
コード例 #4
0
ファイル: Note.cs プロジェクト: gavioto/evimsync
        public void AddAttachment(byte[] binaryData, string contentId, string contentType, string contentFileName)
        {
            byte[] hash = new MD5CryptoServiceProvider().ComputeHash(binaryData);
            string hashHex = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
            string cid = string.Empty;
            if (contentId != null)
                cid = contentId.TrimStart('<', '"');
            cid = cid.TrimEnd('>', '"');
            if ((cid.Length > 0) && content.Contains(cid))
            {
                // convert the reference tag to a media tag
                int idIndex = content.IndexOf(cid);

                // go left until the '<' is found
                int bracketIndex = content.LastIndexOf('<', idIndex);
                int endBracket = content.IndexOf('>', bracketIndex);
                string refTag = content.Substring(bracketIndex, endBracket - bracketIndex + 1);
                int srcStart = refTag.ToLower().IndexOf("src=\"") + 4;
                int srcEnd = refTag.IndexOf('"', srcStart + 1);
                string srcString = refTag.Substring(srcStart, srcEnd - srcStart + 1);
                string mediaTag = refTag.Replace("src=", "hash=");
                mediaTag = mediaTag.Replace(srcString, '"' + hashHex + '"');
                int imgStart = mediaTag.IndexOf('<') + 1;
                int imgEnd = mediaTag.IndexOfAny(" \t".ToCharArray(), imgStart);
                mediaTag = mediaTag.Remove(imgStart, imgEnd - imgStart);
                mediaTag = mediaTag.Insert(imgStart, "en-media type=\"" + contentType.ToLower() + "\"");
                Content = content.Replace(refTag, mediaTag);
            }
            else
            {
                // just link the attachment to the content
                Content = content + "<en-media hash=\"" + hashHex + "\" type=\"" + contentType.ToLower() + "\"/>";
            }

            string attachmentString = Convert.ToBase64String(binaryData);
            attachmentString = "<data encoding=\"base64\">" + attachmentString + "</data><mime>" + contentType.ToLower() + "</mime>" +
                "<resource-attributes><file-name>" + XmlSanitizer.SanitizeXmlString(contentFileName).Replace("&", string.Empty) + "</file-name></resource-attributes>";
            Attachment at = new Attachment();
            at.Base64Data = attachmentString;
            at.ContentID = contentId;
            at.ContentType = contentType.ToLower();
            at.FileName = contentFileName;
            at.Hash = hashHex;
            Attachments.Add(at);
        }