private string ExtractNotes(string notebook) { if (cancelled) { return(null); } syncStep = SyncStep.ExtractNotes; ENScriptWrapper enscript = new ENScriptWrapper(); enscript.ENScriptPath = enscriptpath; string exportFile = Path.GetTempFileName(); #if DEBUG exportFile = @"D:\Development\evimsync\" + notebook + ".xml"; #endif if (enscript.ExportNotebook(notebook, exportFile)) { return(exportFile); } // in case the selected notebook is empty, we don't get // an exportFile. But just to make sure the notebook // exists anyway, we check that here before giving up if (enscript.GetNotebooks().Contains(notebook)) { return(string.Empty); } return(null); }
private void SyncEvernoteWithIMAP() { Configuration config = Configuration.Create(); enscriptpath = config.ENScriptPath; foreach (SyncPairSettings syncPair in config.SyncPairs) { if (cancelled) { break; } synchronizationContext.Send(new SendOrPostCallback(delegate(object state) { this.infoText0.Text = string.Format("Syncing notebook {0}", syncPair.EvernoteNotebook); }), null); syncStep = SyncStep.Start; SetInfo("Extracting notes from Evernote", "", 0, 0); string exportFile = ExtractNotes(syncPair.EvernoteNotebook); if (exportFile != null) { List <Note> notesEvernote = new List <Note>(); if (exportFile != string.Empty) { SetInfo("Parsing notes from Evernote", "", 0, 0); notesEvernote = ParseNotes(exportFile); } SetInfo("Fetching list of emails", "", 0, 0); List <Note> notesIMAP = GetMailList(syncPair.IMAPServer, syncPair.IMAPUsername, syncPair.IMAPPassword, syncPair.IMAPNotesFolder); SetInfo("Figuring out what needs to be synced", "", 0, 0); DiffNotesAndMails(ref notesEvernote, ref notesIMAP, syncPair.LastSyncTime); SetInfo("Adjusting tags in the GMail account", "", 0, 0); AdjustIMAPTags(syncPair.IMAPNotesFolder, notesIMAP); SetInfo("Downloading emails", "", 0, 0); List <Note> imapnotes = new List <Note>(notesIMAP); DownloadAndImportMailsToEvernote(imapnotes, notesEvernote, syncPair.EvernoteNotebook); if (exportFile != string.Empty) { SetInfo("Figuring out what needs to be synced", "", 0, 0); DiffNotesAndMails(ref notesEvernote, ref notesIMAP, syncPair.LastSyncTime); SetInfo("Uploading emails", "", 0, 0); UploadNotesAsMails(syncPair.IMAPNotesFolder, notesEvernote, exportFile); } syncPair.LastSyncTime = DateTime.Now; if (client != null) { client.Stop(); } } else { MessageBox.Show(string.Format("The notebook \"{0}\" either does not exist or isn't accessible!", syncPair.EvernoteNotebook)); } } if (!cancelled) { config.Save(); } else { SetInfo(null, "Operation cancelled", 0, 0); } synchronizationContext.Send(new SendOrPostCallback(delegate(object state) { startsync.Text = "Start Sync"; this.infoText1.Text = "Finished"; this.progressIndicator.Minimum = 0; this.progressIndicator.Maximum = 100000; this.progressIndicator.Value = 0; }), null); }
private List<Note> ParseNotes(string exportFile) { syncStep = SyncStep.ParseNotes; List<Note> noteList = new List<Note>(); if (cancelled) { return noteList; } XmlTextReader xtrInput; XmlDocument xmlDocItem; xtrInput = new XmlTextReader(exportFile); try { 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()))); string outerXml = xtrInput.ReadOuterXml(); string htmlDecode = HttpUtility.HtmlDecode(outerXml); string newHtmlDecode = RemoveProblematicTags(htmlDecode); xmlDocItem.LoadXml(newHtmlDecode); XmlNode node = xmlDocItem.FirstChild; // node is <note> element // node.FirstChild.InnerText is <title> node = node.FirstChild; Note note = new Note(); note.Title = node.InnerText; noteList.Add(note); } } xtrInput.Close(); } catch (System.Xml.XmlException) { // happens if the notebook was empty or does not exist. MessageBox.Show(string.Format("The notebook \"{0}\" either does not exist or empty!", ENNotebookName)); } return noteList; }
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("'", "'"); 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("'", "'"), note.SourceUrl.Length > 0 ? xmlSource : ""); string xml = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("'", "'"), 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("'", "'"), note.SourceUrl.Length > 0 ? xmlSource : ""); string xml = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("'", "'"), 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())); } } }
private void ImportNotesToOnenote() { syncStep = SyncStep.Start; if (m_enexfile != null && m_enexfile.Length > 0) { List<Note> notesEvernote = new List<Note>(); if (m_enexfile != string.Empty) { SetInfo("Parsing notes from Evernote", "", 0, 0); notesEvernote = ParseNotes(m_enexfile); } if (m_enexfile != string.Empty) { SetInfo("importing notes to Onenote", "", 0, 0); ImportNotesToOnenote(ENNotebookName, notesEvernote, m_enexfile); } } else { SetInfo("Extracting notes from Evernote", "", 0, 0); string exportFile = ExtractNotes(ENNotebookName); if (exportFile != null) { List<Note> notesEvernote = new List<Note>(); if (exportFile != string.Empty) { SetInfo("Parsing notes from Evernote", "", 0, 0); notesEvernote = ParseNotes(exportFile); } if (exportFile != string.Empty) { SetInfo("importing notes to Onenote", "", 0, 0); ImportNotesToOnenote(ENNotebookName, notesEvernote, exportFile); } } else { MessageBox.Show(string.Format("The notebook \"{0}\" either does not exist or isn't accessible!", ENNotebookName)); } } m_enexfile = ""; if (cancelled) { SetInfo(null, "Operation cancelled", 0, 0); } synchronizationContext.Send(new SendOrPostCallback(delegate(object state) { startsync.Text = "Start Import"; this.infoText1.Text = "Finished"; this.infoText2.Text = ""; this.progressIndicator.Minimum = 0; this.progressIndicator.Maximum = 100000; this.progressIndicator.Value = 0; }), null); }
private string ExtractNotes(string notebook) { if (cancelled) { return null; } syncStep = SyncStep.ExtractNotes; ENScriptWrapper enscript = new ENScriptWrapper(); enscript.ENScriptPath = enscriptpath; string exportFile = Path.GetTempFileName(); #if DEBUG exportFile = @"D:\Development\evimsync\" + notebook + ".xml"; #endif if (enscript.ExportNotebook(notebook, exportFile)) { return exportFile; } // in case the selected notebook is empty, we don't get // an exportFile. But just to make sure the notebook // exists anyway, we check that here before giving up if (enscript.GetNotebooks().Contains(notebook)) return string.Empty; return null; }
public MatchMakingSyncEvent(Guid syncId, SyncStep currentSyncStep) { SyncId = syncId; CurrentSyncStep = currentSyncStep; Broadcast = true; }
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("'", "'"); emailBody = emailBody.Replace("’", "'"); emailBody = rxCDATAInner.Replace(emailBody, "<![CDATA[${text}]]>"); 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("'", "'"), note.SourceUrl.Length > 0 ? xmlSource : ""); string xml = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("'", "'"), 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("'", "'"), note.SourceUrl.Length > 0 ? xmlSource : ""); string xml = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("'", "'"), 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())); } } }
private List <Note> ParseNotes(string exportFile) { syncStep = SyncStep.ParseNotes; List <Note> noteList = new List <Note>(); if (cancelled) { return(noteList); } XmlTextReader xtrInput; XmlDocument xmlDocItem; xtrInput = new XmlTextReader(exportFile); string xmltext = ""; try { 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); noteList.Add(note); } } 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) { Regex rxnote = new Regex("<title>(.+)</title>", RegexOptions.IgnoreCase); 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())); } } return(noteList); }
private void ImportNotesToOnenote() { syncStep = SyncStep.Start; if (m_enexfile != null && m_enexfile.Length > 0) { List <Note> notesEvernote = new List <Note>(); if (m_enexfile != string.Empty) { SetInfo("Parsing notes from Evernote", "", 0, 0); notesEvernote = ParseNotes(m_enexfile); } if (m_enexfile != string.Empty) { SetInfo("importing notes to Onenote", "", 0, 0); ImportNotesToOnenote(ENNotebookName, notesEvernote, m_enexfile); } } else { SetInfo("Extracting notes from Evernote", "", 0, 0); string exportFile = ExtractNotes(ENNotebookName); if (exportFile != null) { List <Note> notesEvernote = new List <Note>(); if (exportFile != string.Empty) { SetInfo("Parsing notes from Evernote", "", 0, 0); notesEvernote = ParseNotes(exportFile); } if (exportFile != string.Empty) { SetInfo("importing notes to Onenote", "", 0, 0); ImportNotesToOnenote(ENNotebookName, notesEvernote, exportFile); } } else { MessageBox.Show(string.Format("The notebook \"{0}\" either does not exist or isn't accessible!", ENNotebookName)); } } m_enexfile = ""; if (cancelled) { SetInfo(null, "Operation cancelled", 0, 0); } else { SetInfo("", "", 0, 0); } synchronizationContext.Send(new SendOrPostCallback(delegate(object state) { startsync.Text = "Start Import"; this.infoText1.Text = "Finished"; this.progressIndicator.Minimum = 0; this.progressIndicator.Maximum = 100000; this.progressIndicator.Value = 0; }), null); if (cmdNoteBook.Length > 0) { synchronizationContext.Send(new SendOrPostCallback(delegate(object state) { this.Close(); }), null); } }
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("'", "'"); emailBody = emailBody.Replace("’", "'"); emailBody = rxCDATAInner.Replace(emailBody, "<![CDATA[${text}]]>"); 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("'", "'"), note.SourceUrl.Length > 0 ? xmlSource : ""); string xml = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("'", "'"), 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("'", "'"), note.SourceUrl.Length > 0 ? xmlSource : ""); string xml = string.Format(m_xmlNewOutline, outlineContent, m_PageID, m_xmlns, System.Security.SecurityElement.Escape(note.Title).Replace("'", "'"), 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())); } } }
private List<Note> ParseNotes(string exportFile) { syncStep = SyncStep.ParseNotes; List<Note> noteList = new List<Note>(); if (cancelled) { return noteList; } XmlTextReader xtrInput; XmlDocument xmlDocItem; xtrInput = new XmlTextReader(exportFile); string xmltext = ""; try { 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); noteList.Add(note); } } 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) { Regex rxnote = new Regex("<title>(.+)</title>", RegexOptions.IgnoreCase); 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())); } return noteList; }
private void SyncEvernoteWithIMAP() { Configuration config = Configuration.Create(); enscriptpath = config.ENScriptPath; foreach (SyncPairSettings syncPair in config.SyncPairs) { if (cancelled) { break; } synchronizationContext.Send(new SendOrPostCallback(delegate(object state) { this.infoText0.Text = string.Format("Syncing notebook {0}", syncPair.EvernoteNotebook); }), null); syncStep = SyncStep.Start; SetInfo("Extracting notes from Evernote", "", 0, 0); string exportFile = ExtractNotes(syncPair.EvernoteNotebook); if (exportFile != null) { List<Note> notesEvernote = new List<Note>(); if (exportFile != string.Empty) { SetInfo("Parsing notes from Evernote", "", 0, 0); notesEvernote = ParseNotes(exportFile); } SetInfo("Fetching list of emails", "", 0, 0); List<Note> notesIMAP = GetMailList(syncPair.IMAPServer, syncPair.IMAPUsername, syncPair.IMAPPassword, syncPair.IMAPNotesFolder); SetInfo("Figuring out what needs to be synced", "", 0, 0); DiffNotesAndMails(ref notesEvernote, ref notesIMAP, syncPair.LastSyncTime); SetInfo("Adjusting tags in the GMail account", "", 0, 0); AdjustIMAPTags(syncPair.IMAPNotesFolder, notesIMAP); SetInfo("Downloading emails", "", 0, 0); List<Note> imapnotes = new List<Note>(notesIMAP); DownloadAndImportMailsToEvernote(imapnotes, notesEvernote, syncPair.EvernoteNotebook); if (exportFile != string.Empty) { SetInfo("Figuring out what needs to be synced", "", 0, 0); DiffNotesAndMails(ref notesEvernote, ref notesIMAP, syncPair.LastSyncTime); SetInfo("Uploading emails", "", 0, 0); UploadNotesAsMails(syncPair.IMAPNotesFolder, notesEvernote, exportFile); } syncPair.LastSyncTime = DateTime.Now; if (client != null) client.Stop(); } else { MessageBox.Show(string.Format("The notebook \"{0}\" either does not exist or isn't accessible!", syncPair.EvernoteNotebook)); } } if (!cancelled) { config.Save(); } else { SetInfo(null, "Operation cancelled", 0, 0); } synchronizationContext.Send(new SendOrPostCallback(delegate(object state) { startsync.Text = "Start Sync"; this.infoText1.Text = "Finished"; this.progressIndicator.Minimum = 0; this.progressIndicator.Maximum = 100000; this.progressIndicator.Value = 0; }), null); }