Inheritance: TBase
        static void Main(string[] args)
        {
            // Supply your key using ENSessionAdvanced instead of ENEsssion, to indicate your use of the Advanced interface.
            // Be sure to put your own consumer key and consumer secret here.
            ENSessionAdvanced.SetSharedSessionConsumerKey("your key", "your secret");

            if (ENSession.SharedSession.IsAuthenticated == false)
            {
                ENSession.SharedSession.AuthenticateToEvernote();
            }

            // Create a note (in the user's default notebook) with an attribute set (in this case, the ReminderOrder attribute to create a Reminder).
            ENNoteAdvanced myNoteAdv = new ENNoteAdvanced();
            myNoteAdv.Title = "Sample note with Reminder set";
            myNoteAdv.Content = ENNoteContent.NoteContentWithString("Hello, world - this note has a Reminder on it.");
            myNoteAdv.EdamAttributes["ReminderOrder"] = DateTime.Now.ToEdamTimestamp();
            ENNoteRef myRef = ENSession.SharedSession.UploadNote(myNoteAdv, null);

            // Now we'll create an EDAM Note.
            // First create the ENML content for the note.
            ENMLWriter writer = new ENMLWriter();
            writer.WriteStartDocument();
            writer.WriteString("Hello again, world.");
            writer.WriteEndDocument();
            // Create a note locally.
            Note myNote = new Note();
            myNote.Title = "Sample note from the Advanced world";
            myNote.Content = writer.Contents.ToString();
            // Create the note in the service, in the user's personal, default notebook.
            ENNoteStoreClient store = ENSessionAdvanced.SharedSession.PrimaryNoteStore;
            Note resultNote = store.CreateNote(myNote);
        }
 /// <summary>
 /// ノート本文の内容を出力する。
 /// </summary>
 /// <param name="note"></param>
 private void WriteNote(Note note)
 {
     Console.WriteLine("Title: " + note.Title);
     Console.WriteLine("GUID: " + note.Guid);
     Console.WriteLine("Content: " + note.Content);
     Console.WriteLine("ToString: " + note.ToString());
 }
        public void SaveNote(Note note, string baseName, int noteCount)
        {
            string noteBaseName = GetNoteBaseName(note, baseName, noteCount);

            // 本文を保存する
            string contentFilePath = GetContentPath(noteBaseName);
            OutputNoteContent outputNoteContent = new OutputNoteContent(note, contentFilePath);
            outputNoteContent.Save();

            // 添付なしの場合、Resourcesがnullになる模様。
            if (note.Resources == null)
            {
                return;
            }

            // 添付をファイル保存する
            int count = 1;
            foreach (Resource res in note.Resources)
            {
                string resPath = GetResPath(res, noteBaseName, count);

                OutputNoteResource outputNoteResource = new OutputNoteResource(res, resPath);
                outputNoteResource.Save();

                count++;
            }
        }
Exemple #4
0
 /// <summary>
 /// Makes a new Note in an existing Notebook.
 /// </summary>
 public Note CreateNote(Note n)
 {
     lock (this)
         using (var httpClient = GetHttpClient())
         {
             return GetNoteStoreClient(httpClient).createNote(this.authToken, n);
         }
 }
        // Evernote has a bunch of junk in it's xml tomboy doesn't care about, and tomboy
        // also requires some specific tags. So strip out evernote's and add tomboys
        // TODO - Really, Really need to convert the html-like tags, not just strip them
        // TODO -  so that we can keep things like bulleted lists, font sizes, etc
        public string CreateTomboyNoteContent(Evernote.EDAM.Type.Note note)
        {
            string evernoteContent;

            try
            {
                evernoteContent = _noteStore.getNoteContent(_authToken, note.Guid);
            }
            catch (Exception e)
            {
                evernoteContent = "Could not retrieve Evernote Content";
            }
            ExportManager exportManager = new ExportManager(EvernoteToTomboyXSLTResourceName);
            string        tomboyContent;

            try
            {
                tomboyContent = exportManager.ApplyXSL(evernoteContent, note.Title, null, ValidationType.DTD);
            }
            catch (Exception e)
            {
                tomboyContent = "Evernote Export failed." +
                                " Please report a bug at http://bugzilla.gnome.org with the following: (strip out confidential information)" +
                                e + "\n" + note;
            }

            string content = TomboyHeader + "\n" + "<title>" + note.Title + "</title>" +
                             "<text xml:space=\"preserve\"><note-content version=\"0.1\">" + "\n";

            content += tomboyContent;
            content += "</note-content></text>\n";
            DateTime date;

            if (note.Updated > DateTime.MinValue.Ticks && note.Updated < DateTime.MaxValue.Ticks)
            {
                date = Epoch.Add(TimeSpan.FromTicks(note.Updated * 10000));
            }
            else
            {
                date = DateTime.Now;
            }
            content += "<last-change-date>" + date + "</last-change-date>\n";
            content += "<last-metadata-change-date>" + date + "</last-metadata-change-date>\n";
            if (note.Created > DateTime.MinValue.Ticks && note.Created < DateTime.MaxValue.Ticks)
            {
                date = Epoch.Add(TimeSpan.FromTicks(note.Created * 10000));
            }
            content += "<create-date>" + date + "</create-date>\n";

            content += "</note>";
            return(content);
        }
 private static string GetCorrectGuid(Evernote.EDAM.Type.Note note)
 {
     if (note.Attributes.SourceApplication != null && note.Attributes.SourceApplication.ToLowerInvariant() == "tomboy" &&
         !string.IsNullOrEmpty(note.Attributes.Source))
     {
         //it looks like a GUID, and talks like a GUID, so assume it's a GUID
         return(note.Attributes.Source);
     }
     else
     {
         return(note.Guid);
     }
 }
        public void TestSaveNote_Normal_0001()
        {
            // 準備
            Note note = new Note();
            note.Content = "content";
            string baseName = "TestSaveNote_Normal_0001";

            // テスト実行
            mTarget.SaveNote(note, baseName, 1);

            // 検証
            Assert.True(File.Exists(baseName + "_00001.txt"));
        }
 private string GetNoteBaseName(Note note, string baseName, int noteCount)
 {
     string path;
     if (string.IsNullOrEmpty(baseName))
     {
         path = note.Title;
     }
     else
     {
         path = baseName + "_" + GetSeq(noteCount);
     }
     return path;
 }
Exemple #9
0
        /// <summary>
        /// Tweets the given note.
        /// </summary>
        private static void TweetNote( Note note )
        {
            string tweet = note.Title.Replace( '@', '-' ); // Temporary; don't want to callout people during testingv.         

            log.Info( "Tweeting \"" + tweet + "\"..." );
            if ( note.Resources != null && note.Resources.Count > 0 )
            {
                // Mark this note as tweeted. We do this first because double tweeting is worse than missing a note here and there.
                GuidCache.Add( note.Guid );

                // Tweet. If it failed, then mark it as untweeted.
                if ( !TwitterPoster.Tweet( tweet, note.Resources[0].Data.Body ) )
                    GuidCache.Remove( note.Guid );
            }
        }
 private bool CreateNewEvernote(Note note)
 {
     Evernote.EDAM.Type.Note newNote = new Evernote.EDAM.Type.Note();
     newNote = FillEvernote(note, newNote);
     try
     {
         _noteStore.createNote(_authToken, newNote);
     }
     catch (Exception e)
     {
         Logger.Error("[Evernote] Error Creating new Evernote :" + e + "\n EverNote: " + newNote + "\nTomboyNote: " + note);
         return(false);
     }
     return(true);
 }
        private void CreateNote()
        {
            Note note = new Note();
            note.Title = "EvernoteAPI 新規ノート作成テスト";
            note.Content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">" +
                "<en-note>サンプルテキスト。<br/>" +
                "サンプルテキスト。<br/>" +
                "サンプルテキスト。<br/>" +
                "</en-note>";

            Note createdNote = mNoteStore.createNote(mAuthToken, note);

            Console.WriteLine("Successfully created new note with GUID: " + createdNote.Guid);
        }
        private bool UpdateEvernote(Evernote.EDAM.Type.Note evernote, Note tomboynote)
        {
            Logger.Debug("[Evernote] Updating evernote: " + evernote.Guid);
            try
            {
                evernote = FillEvernote(tomboynote, evernote);
                _noteStore.updateNote(_authToken, evernote);
            }
            catch (Exception e)
            {
                Logger.Warn("[Evernote] Could not Update note: " + e + "EverNote: " + evernote + "\nTomboyNote: " + tomboynote);
                return(false);
            }

            return(true);
        }
        public void UploadNotes(IList <Note> notes)
        {
            //TODO - this could take a long time, think of a better way to do this
            //TODO - an alternative is to just try to Update and evernote (without checking whether it exists),
            //TODO -  but the _noteStore.updateNote function throws an Exception on error, instead of returning false
            //TODO -  and using exceptions for process control is costly.

            NoteFilter noteFilter = new NoteFilter();

            noteFilter.NotebookGuid = _tomboyNotebook.Guid;
            NoteList evernoteList = _noteStore.findNotes(_authToken, noteFilter, 0, Evernote.EDAM.Limits.Constants.EDAM_USER_NOTES_MAX);

            Logger.Debug("[Evernote] Uploading " + notes.Count + " notes");

            foreach (Note note in notes)
            {
                bool foundNote = false;
                Evernote.EDAM.Type.Note enote = null;
                foreach (Evernote.EDAM.Type.Note evernote in evernoteList.Notes)
                {
                    if (GetCorrectGuid(evernote) == note.Id)
                    {
                        foundNote = true;
                        enote     = evernote;
                        break;
                    }
                }
                if (foundNote)
                {
                    if (!UpdateEvernote(enote, note))
                    {
                        Logger.Error("[Evernote] Could not update Evernote: " + note);
                        throw new TomboySyncException("Could not Update Evernote");
                    }
                }
                else
                {
                    //does not exist, so create a new note.
                    if (!CreateNewEvernote(note))
                    {
                        Logger.Debug("[Evernote] Problem creating note with id" + note.Id);
                        throw new TomboySyncException("Couldn't create Evernote");
                    }
                }
            }
        }
        public void TestSaveNote_Normal_0002()
        {
            // 準備
            Resource resource = new Resource();
            resource.Data = new Data();
            resource.Data.Body = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 };
            Note note = new Note();
            note.Content = "content";
            note.Resources = new List<Resource>();
            note.Resources.Add(resource);
            string baseName = "TestSaveNote_Normal_0002";

            // テスト実行
            mTarget.SaveNote(note, baseName, 1);

            // 検証
            Assert.True(File.Exists(baseName + "_00001.txt"));
        }
        private Evernote.EDAM.Type.Note FillEvernote(Note tomboynote, Evernote.EDAM.Type.Note evernote)
        {
            Logger.Debug("[Evernote] Creating new Evernote from tomboy:" + tomboynote.Id.ToString());
            if (evernote.Attributes == null)
            {
                evernote.Attributes = new NoteAttributes();
            }
            evernote.Attributes.SourceApplication = "tomboy"; //this note came from tomboy. This is read later to match guids
            evernote.Attributes.Source            = tomboynote.Id;

            ExportManager exportManager = new ExportManager(TomboyToEvernoteXSLTResourceName);
            string        mycontent     = exportManager.ApplyXSL(tomboynote);

            string content = mycontent;

            evernote.Content += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml.dtd\">";
            evernote.Content += content;
            try
            {
                ValidateXML(evernote.Content);
            }
            catch (Exception e)
            {
                Logger.Error("[Evernote] Could not validate XML: " + evernote.Content);
            }

            evernote.Title = tomboynote.Title;
            if (tomboynote.Tags.Count > 0)
            {
                evernote.TagNames = new List <string>();
                foreach (Tag tag in tomboynote.Tags)
                {
                    evernote.TagNames.Add(tag.Name);
                }
            }
            evernote.NotebookGuid = _tomboyNotebook.Guid;
            evernote.Created      = (long)tomboynote.CreateDate.Subtract(Epoch).TotalMilliseconds;
            evernote.Updated      = (long)tomboynote.ChangeDate.Subtract(Epoch).TotalMilliseconds;
            return(evernote);
        }
 public void PerformOperation(IEvernoteService evernoteService, Note note)
 {
 }
Exemple #17
0
 public Note UpdateNote(Note n)
 {
     return Note.UpdateNote(n);
 }
        private Evernote.EDAM.Type.Note FillEvernote(Note tomboynote, Evernote.EDAM.Type.Note evernote)
        {
            Logger.Debug("[Evernote] Creating new Evernote from tomboy:" + tomboynote.Id.ToString());
            if (evernote.Attributes == null) {
                evernote.Attributes = new NoteAttributes();
            }
            evernote.Attributes.SourceApplication = "tomboy"; //this note came from tomboy. This is read later to match guids
            evernote.Attributes.Source = tomboynote.Id;

            ExportManager exportManager = new ExportManager(TomboyToEvernoteXSLTResourceName);
            string mycontent = exportManager.ApplyXSL(tomboynote);

            string content = mycontent;
            evernote.Content += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml.dtd\">";
            evernote.Content +=  content;
            try
            {
                ValidateXML(evernote.Content);
            }
            catch (Exception e)
            {
                Logger.Error("[Evernote] Could not validate XML: " + evernote.Content);
            }

            evernote.Title = tomboynote.Title;
            if (tomboynote.Tags.Count > 0) {
                evernote.TagNames = new List<string>();
                foreach (Tag tag in tomboynote.Tags)
                {
                    evernote.TagNames.Add(tag.Name);
                }
            }
            evernote.NotebookGuid = _tomboyNotebook.Guid;
            evernote.Created = (long)tomboynote.CreateDate.Subtract(Epoch).TotalMilliseconds;
            evernote.Updated = (long)tomboynote.ChangeDate.Subtract(Epoch).TotalMilliseconds;
            return evernote;
        }
 private bool CreateNewEvernote(Note note)
 {
     Evernote.EDAM.Type.Note newNote = new Evernote.EDAM.Type.Note();
     newNote = FillEvernote(note, newNote);
     try
     {
         _noteStore.createNote(_authToken, newNote);
     }
     catch (Exception e)
     {
         Logger.Error("[Evernote] Error Creating new Evernote :" + e + "\n EverNote: " + newNote + "\nTomboyNote: " + note);
         return false;
     }
     return true;
 }
        /// <summary>
        /// Create a new note in the account of the user with the specified developer token.
        /// </summary>
        /// <returns>true if the note was created successfully, false otherwise.</returns>
        public bool createNote(String developerToken)
        {
            try
            {
                try
                {
                    if (!auth(developerToken))
                    {
                        // This is an unrecoverable error - our protocol version is out of date
                        return false;
                    }
                }
                catch (EDAMUserException eux)
                {
                    // TODO - do proper error handling
                    return false;
                }

                THttpClient noteStoreTransport = new THttpClient(new Uri(noteStoreUrl));
                noteStoreTransport.CustomHeaders[HttpRequestHeader.UserAgent.ToString()] = USER_AGENT;
                TProtocol noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
                NoteStore.Client noteStore = new NoteStore.Client(noteStoreProtocol);

                // The bytes of the image we want to send up to the service
                // In this test, we use an image hardcoded as a base64-encoded string
                IBuffer imageBuffer = CryptographicBuffer.DecodeFromBase64String(imgBase64);
                byte[] imageBytes = WindowsRuntimeBufferExtensions.ToArray(imageBuffer);
                
                HashAlgorithmProvider provider = HashAlgorithmProvider.OpenAlgorithm("MD5");
                IBuffer hashBuffer = provider.HashData(imageBuffer);
                byte[] hash = WindowsRuntimeBufferExtensions.ToArray(hashBuffer);
                String hashHex = CryptographicBuffer.EncodeToHexString(hashBuffer);

                Data data = new Data();
                data.Size = imageBytes.Length;
                data.BodyHash = hash;
                data.Body = imageBytes;

                Resource resource = new Resource();
                resource.Mime = "image/png";
                resource.Data = data;

                Note note = new Note();
                note.Title = "Hello, World!";
                note.Content = EDAM_NOTE_PREAMBLE + 
                    "<h2>This note is created by the Evernote sample code for Windows Store applications!</h2>" + 
                    "<br />" +
                    "<en-media type=\"image/png\" hash=\"" + hashHex + "\"/>" +
                    EDAM_NOTE_POSTAMBLE;
                note.Resources = new List<Resource>();
                note.Resources.Add(resource);

                try
                {
                    noteStore.createNote(authToken, note);
                    return true;
                }
                catch (EDAMUserException ex)
                {
                    // Handle note creation failure
                }
            }
            catch (TApplicationException tax)
            {
                // Handle generic Thrift error
            }
            catch (TTransportException ttx)
            {
                // Handle networking error
            }
            catch (EDAMSystemException esx)
            {
                // Handle unrecoverable Evernote error (i.e., error not caused by bad user input)
            }

            return false;
        }
Exemple #21
0
 public void DeleteNote(Note n)
 {
     n.Active = false;
     note.UpdateNote(n);
 }
        private void DeleteNote()
        {
            Note note = new Note();
            note.Title = "EvernoteAPI ノート削除テスト";
            note.Content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">" +
                "<en-note>サンプルテキスト。<br/>" +
                "サンプルテキスト。<br/>" +
                "サンプルテキスト。<br/>" +
                "</en-note>";
            Note createdNote = mNoteStore.createNote(mAuthToken, note);
            Console.WriteLine("Successfully created new note with GUID: " + createdNote.Guid);

            int ret = mNoteStore.deleteNote(mAuthToken, createdNote.Guid);
            Console.WriteLine("Returned value of NoteStore#deleteNote method : " + ret);
        }
 public OutputNoteContent(Note note, string path)
 {
     this.mNote = note;
     this.mPath = path;
 }
		// Initialize a new ENNote from an EDAMNote.
		internal ENNote(Note edamNote)
		{
			// Copy the fields that can be edited at this level.
			_Title = edamNote.Title;
			_Content = ENNoteContent.NoteContentWithENML(edamNote.Content);
			this.IsReminder = edamNote.Attributes.ReminderOrder != 0;
			this.SourceUrl = edamNote.Attributes.SourceURL;
			_TagNames = edamNote.TagNames; //This is usually null, unfortunately, on notes that come from the service.

			// Resources to ENResources
			_Resources = new List<ENResource>();
			if (edamNote.Resources != null)
			{
				foreach (Resource serviceResource in edamNote.Resources)
				{
					ENResource resource = ENResource.ResourceWithServiceResource(serviceResource);
					if (resource != null)
					{
						_Resources.Add(resource);
					}
				}
			}

			// Keep a copy of the service note around with all of its extra properties
			// in case we have to convert back to an EDAMNote later.
			ServiceNote = edamNote;

			// Get rid of these references here; they take up memory and we can let them be potentially cleaned up.
			ServiceNote.Content = null;
			ServiceNote.Resources = null;
		}
        private bool UpdateEvernote(Evernote.EDAM.Type.Note evernote,  Note tomboynote)
        {
            Logger.Debug("[Evernote] Updating evernote: " + evernote.Guid);
            try
            {
                evernote = FillEvernote(tomboynote, evernote);
                _noteStore.updateNote(_authToken, evernote);
            }
            catch (Exception e)
            {
                Logger.Warn("[Evernote] Could not Update note: " + e + "EverNote: " + evernote + "\nTomboyNote: " + tomboynote);
                return false;
            }

            return true;
        }
Exemple #26
0
        public static void RunImpl(object state)
        {
            // Username and password of the Evernote user account to access
            const string username = ""; // Enter your username here
            const string password = ""; // Enter your password here

            if ((ConsumerKey == String.Empty) || (ConsumerSecret == String.Empty))
            {
                ShowMessage("Please provide your API key in Sample.cs");
                return;
            }
            if ((username == String.Empty) || (password == String.Empty))
            {
                ShowMessage("Please provide your username and password in Sample.cs");
                return;
            }

            // Instantiate the libraries to connect the service
            TTransport userStoreTransport = new THttpClient(new Uri(UserStoreUrl));
            TProtocol userStoreProtocol = new TBinaryProtocol(userStoreTransport);
            UserStore.Client userStore = new UserStore.Client(userStoreProtocol);

            // Check that the version is correct
            bool versionOK =
                userStore.checkVersion("C# EDAMTest",
                   Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MAJOR,
                   Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MINOR);
            InvokeOnUIThread(() => ViewModel.TheViewModel.VersionOK = versionOK);
            Debug.WriteLine("Is my EDAM protocol version up to date? " + versionOK);
            if (!versionOK)
            {
                return;
            }

            // Now we are going to authenticate
            AuthenticationResult authResult;
            try
            {
                authResult = userStore.authenticate(username, password, ConsumerKey, ConsumerSecret);
            }
            catch (EDAMUserException ex)
            {
                HandleAuthenticateException(EvernoteHost, ConsumerKey, ex);
                return;
            }
            Debug.WriteLine("We are connected to the service");

            // User object received after authentication
            User user = authResult.User;
            String authToken = authResult.AuthenticationToken;
            InvokeOnUIThread(() => ViewModel.TheViewModel.AuthToken = authToken);

            Debug.WriteLine("Authentication successful for: " + user.Username);
            Debug.WriteLine("Authentication token = " + authToken);

            // Creating the URL of the NoteStore based on the user object received
            String noteStoreUrl = EDAMBaseUrl + "/edam/note/" + user.ShardId;

            TTransport noteStoreTransport = new THttpClient(new Uri(noteStoreUrl));
            TProtocol noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
            NoteStore.Client noteStore = new NoteStore.Client(noteStoreProtocol);

            // Listing all the user's notebook
            List<Notebook> notebooks = noteStore.listNotebooks(authToken);
            Debug.WriteLine("Found " + notebooks.Count + " notebooks:");
            InvokeOnUIThread(() => notebooks.ForEach(notebook => ViewModel.TheViewModel.Notebooks.Add(notebook)));

            // Find the default notebook
            Notebook defaultNotebook = notebooks.Single(notebook => notebook.DefaultNotebook);

            // Printing the names of the notebooks
            foreach (Notebook notebook in notebooks)
            {
                Debug.WriteLine("  * " + notebook.Name);
            }

            // Listing the first 10 notes in the default notebook
            NoteFilter filter = new NoteFilter { NotebookGuid = defaultNotebook.Guid };
            NoteList notes = noteStore.findNotes(authToken, filter, 0, 10);
            InvokeOnUIThread(() => notes.Notes.ForEach(note => ViewModel.TheViewModel.Notes.Add(note)));
            foreach (Note note in notes.Notes)
            {
                Debug.WriteLine("  * " + note.Title);
            }

            // Creating a new note in the default notebook
            Debug.WriteLine("Creating a note in the default notebook: " + defaultNotebook.Name);

            Note newNote = new Note
                            {
                                NotebookGuid = defaultNotebook.Guid,
                                Title = "Test note from EDAMTest.cs",
                                Content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                          "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">" +
                                          "<en-note>Here's an Evernote test note<br/>" +
                                          "</en-note>"
                            };

            Note createdNote = noteStore.createNote(authToken, newNote);

            ShowMessage("Successfully created new note with GUID: " + createdNote.Guid);
        }
 public ENNoteAdvanced(Note edamNote) : base(edamNote)
 {
 }
Exemple #28
0
 public Note CreateNote(Note n)
 {
     return Note.CreateNote(n);
 }
		internal Note EDAMNoteToReplaceServiceNoteGUID(string guid)
		{
			// Turn the ENNote into an EDAMNote. Use the cached EDAMNote as a starting point if we have one
			// and if it matches the note GUID we're given. This way we can preserve the characteristics
			// of the "original" note we might be replacing, but not propagate those properties to a
			// a completely fresh note.
			Note edNote = null;
			if (ServiceNote != null && ServiceNote.Guid == guid)
			{
				// TODO: Make sure we don't need a copy here like the iOS SDK
				edNote = ServiceNote;
				// Don't preserve these. Our caller will either rewrite them or leave them blank.
				edNote.Guid = null;
				edNote.NotebookGuid = null;
				edNote.UpdateSequenceNum = 0;
			}
			else
			{
				edNote = new Note();
			}

			edNote.Content = EnmlContent();
			if (string.IsNullOrEmpty(edNote.Content))
			{
				ENNoteContent emptyContent = ENNoteContent.NoteContentWithString("");
				edNote.Content = emptyContent.EnmlWithResources(Resources);
			}
			// Invalidate the derivative content fields.
			edNote.ContentHash = null;
			edNote.ContentLength = 0;

			edNote.Title = Title;
			if (string.IsNullOrEmpty(edNote.Title))
			{
				// Only use a dummy title if we couldn't get a real one inside limits.
				edNote.Title = "Untitled Note";
			}

			// Set up note attributes.
			if (edNote.Attributes == null)
			{
				edNote.Attributes = new NoteAttributes();
			}
			var sourceApplication = ENSession.SharedSession.SourceApplication;

			// Write sourceApplication and source on all notes.
			edNote.Attributes.SourceApplication = sourceApplication;
			edNote.Attributes.Source = "";

			// If reminder is flagged on, set reminderOrder to the current UNIX timestamp by convention.
			// (Preserve existing reminderOrder if present)
			if (IsReminder)
			{
				if (edNote.Attributes.ReminderOrder == 0)
				{
					edNote.Attributes.ReminderOrder = DateTime.Now.ToEdamTimestamp();
				}
			}

			if (SourceUrl != null)
			{
				edNote.Attributes.SourceURL = SourceUrl;
			}

			// Move tags over if present.
			if (TagNames != null)
			{
				edNote.TagNames = TagNames;
			}

			// Turn any ENResources on the note into EDAMResources.
			List<Resource> edResources = new List<Resource>();
			foreach (var localResource in Resources)
			{
				Resource rs = localResource.EDAMResource();
				if (rs != null)
				{
					edResources.Add(rs);
				}
			}

			// Always set the resources array, even if empty. If we end up using this EDAMNote to
			// update an existing note, we always desire the intention of removing any existing resources.
			edNote.Resources = edResources;

			// Set EDAM attributes if EdamAttributes dictionary is not null.
			if (EdamAttributes != null)
			{
				foreach (string key in EdamAttributes.Keys)
				{
					var value = EdamAttributes[key];
					try
					{
						var piInstance = typeof(NoteAttributes).GetProperty(key);
						piInstance.SetValue(edNote.Attributes, value, null);
					}
					catch (KeyNotFoundException)
					{
						ENSDKLogger.ENSDKLogError(string.Format("Key {0} not found on EDAMNote.Attributes", key));
					}
					catch (Exception)
					{
						ENSDKLogger.ENSDKLogError(string.Format("Unable to set value {0} for key {1} on EDAMNote.Attributes", value, key));
					}
				}
			}

			return edNote;
		}
			///** Submit a set of changes to a note to the service.
			// The provided data must include the note's guid field for identification. The note's title must also be set.
			// @param  note A Note object containing the desired fields to be populated on the service. With the exception of the note's title and guid, fields that are not being changed do not need to be set. If the content is not being modified, note.content should be left unset. If the list of resources is not being modified, note.resources should be left unset.
			// */
			public Note UpdateNote(Note note)
			{
				return Client.updateNote(AuthenticationToken(), note);
			}
Exemple #31
0
        public static void RunImpl(object state)
        {
            if (authToken == "your developer token") {
            {
                ShowMessage("Please fill in your devleoper token in Sample.cs");
                return;
            }

            // Instantiate the libraries to connect the service
            TTransport userStoreTransport = new THttpClient(new Uri(UserStoreUrl));
            TProtocol userStoreProtocol = new TBinaryProtocol(userStoreTransport);
            UserStore.Client userStore = new UserStore.Client(userStoreProtocol);

            // Check that the version is correct
            bool versionOK =
                userStore.checkVersion("Evernote EDAMTest (WP7)",
                   Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MAJOR,
                   Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MINOR);
            InvokeOnUIThread(() => ViewModel.TheViewModel.VersionOK = versionOK);
            Debug.WriteLine("Is my Evernote API version up to date? " + versionOK);
            if (!versionOK)
            {
                return;
            }

            // Get the URL used to interact with the contents of the user's account
            // When your application authenticates using OAuth, the NoteStore URL will
            // be returned along with the auth token in the final OAuth request.
            // In that case, you don't need to make this call.
            String noteStoreUrl = userStore.getNoteStoreUrl(authToken);

            TTransport noteStoreTransport = new THttpClient(new Uri(authResult.NoteStoreUrl));
            TProtocol noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
            NoteStore.Client noteStore = new NoteStore.Client(noteStoreProtocol);

            // Listing all the user's notebook
            List<Notebook> notebooks = noteStore.listNotebooks(authToken);
            Debug.WriteLine("Found " + notebooks.Count + " notebooks:");
            InvokeOnUIThread(() => notebooks.ForEach(notebook => ViewModel.TheViewModel.Notebooks.Add(notebook)));

            // Find the default notebook
            Notebook defaultNotebook = notebooks.Single(notebook => notebook.DefaultNotebook);

            // Printing the names of the notebooks
            foreach (Notebook notebook in notebooks)
            {
                Debug.WriteLine("  * " + notebook.Name);
            }

            // Listing the first 10 notes in the default notebook
            NoteFilter filter = new NoteFilter { NotebookGuid = defaultNotebook.Guid };
            NoteList notes = noteStore.findNotes(authToken, filter, 0, 10);
            InvokeOnUIThread(() => notes.Notes.ForEach(note => ViewModel.TheViewModel.Notes.Add(note)));
            foreach (Note note in notes.Notes)
            {
                Debug.WriteLine("  * " + note.Title);
            }

            // Creating a new note in the default notebook
            Debug.WriteLine("Creating a note in the default notebook: " + defaultNotebook.Name);

            Note newNote = new Note
                            {
                                NotebookGuid = defaultNotebook.Guid,
                                Title = "Test note from EDAMTest.cs",
                                Content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                          "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">" +
                                          "<en-note>Here's an Evernote test note<br/>" +
                                          "</en-note>"
                            };

            Note createdNote = noteStore.createNote(authToken, newNote);

            ShowMessage("Successfully created new note with GUID: " + createdNote.Guid);
        }
        /// <summary>
        /// Create a new note in the account of the user with the specified Evernote username and password.
        /// </summary>
        /// <returns>true if the note was created successfully, false otherwise.</returns>
        public bool createNote(String username, String password)
        {
            try
            {
                try
                {
                    if (!auth(username, password))
                    {
                        // This is an unrecoverable error - our protocol version is out of date
                        return false;
                    }
                }
                catch (EDAMUserException eux)
                {
                    // I'm showing some of the most common error codes here that we might want to handle separately.
                    // For the full list, see 
                    // http://dev.evernote.com/documentation/reference/UserStore.html#Fn_UserStore_authenticate
                    if (eux.ErrorCode == EDAMErrorCode.INVALID_AUTH)
                    {
                        if (eux.Parameter == "username" || eux.Parameter == "password")
                        {
                            // We failed to authenticate because the username or password was invalid
                            // This is a recoverable error that the user can fix
                        }
                        else
                        {
                            // Our API key was invalid, or something else wonky happened
                            // The user can't help us recover from this
                        }
                    }
                    else if (eux.ErrorCode == EDAMErrorCode.PERMISSION_DENIED)
                    {
                        if (eux.Parameter == "User.active")
                        {
                            // The credentials were correct, but this user account is not active
                        }
                    }
                    else
                    {
                        // We failed to authenticate for some other reason
                    }
                    return false;
                }

                THttpClient noteStoreTransport = new THttpClient(new Uri(noteStoreUrl));
                noteStoreTransport.CustomHeaders[HttpRequestHeader.UserAgent.ToString()] = USER_AGENT;
                TProtocol noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
                NoteStore.Client noteStore = new NoteStore.Client(noteStoreProtocol);

                // The bytes of the image we want to send up to the service
                // In this test, we use an image hardcoded as a base64-encoded string
                IBuffer imageBuffer = CryptographicBuffer.DecodeFromBase64String(imgBase64);
                byte[] imageBytes = WindowsRuntimeBufferExtensions.ToArray(imageBuffer);
                
                HashAlgorithmProvider provider = HashAlgorithmProvider.OpenAlgorithm("MD5");
                IBuffer hashBuffer = provider.HashData(imageBuffer);
                byte[] hash = WindowsRuntimeBufferExtensions.ToArray(hashBuffer);
                String hashHex = CryptographicBuffer.EncodeToHexString(hashBuffer);

                Data data = new Data();
                data.Size = imageBytes.Length;
                data.BodyHash = hash;
                data.Body = imageBytes;

                Resource resource = new Resource();
                resource.Mime = "image/png";
                resource.Data = data;

                Note note = new Note();
                note.Title = "Hello, World!";
                note.Content = EDAM_NOTE_PREAMBLE + 
                    "<h2>This note is created by Skitch for Metro!</h2>" + 
                    "<br />" +
                    "<en-media type=\"image/png\" hash=\"" + hashHex + "\"/>" +
                    EDAM_NOTE_POSTAMBLE;
                note.Resources = new List<Resource>();
                note.Resources.Add(resource);

                try
                {
                    noteStore.createNote(authToken, note);
                    return true;
                }
                catch (EDAMUserException ex)
                {
                    // Handle note creation failure
                }
            }
            catch (TApplicationException tax)
            {
                // Handle generic Thrift error
            }
            catch (TTransportException ttx)
            {
                // Handle networking error
            }
            catch (EDAMSystemException esx)
            {
                // Handle unrecoverable Evernote error (i.e., error not caused by bad user input)
            }

            return false;
        }
 public ENNoteINoteMetadataAdapter(Note enNote)
 {
     _enNote = enNote;
 }
 private void WriteNote(Note note)
 {
     Console.WriteLine(" * " + note.Title + ", " + note.Guid);
 }
        private static string ProcessContent(PublicUserInfo userInfo, Note note)
        {
            var content = note.Content;

            var beginMatch = EnNoteBeginTagRegex.Match(content);
            if (!beginMatch.Success) {
                throw new EverpageException("Cannot find the begin tag <en-note> in the content.");
            }

            var startIndex = beginMatch.Index + beginMatch.Length;
            var endIndex = content.LastIndexOf("</en-note>", StringComparison.Ordinal);
            if (endIndex < 0) {
                throw new EverpageException("Cannot find the end tag </en-note> in the content.");
            }

            var body = content.Substring(startIndex, endIndex - startIndex);
            var resources = note.Resources.ToDictionary(r => ToHex(r.Data.BodyHash));
            return EnMediaTagRegex.Replace(body, m => EnMediaToImg(m, resources, userInfo.WebApiUrlPrefix));
        }
			///** Asks the service to make a note with the provided set of information.
			// @param  note A Note object containing the desired fields to be populated on the service.
			// @exception EDAMUserException Thrown if the note is not valid.
			// @exception EDAMNotFoundException If the note is not found by GUID
			// */
			public Note CreateNote(Note note)
			{
				return Client.createNote(AuthenticationToken(), note);
			}