Menu

[r313]: / trunk / UnitTests / GoogleAPITests.cs  Maximize  Restore  History

Download this file

298 lines (232 with data), 13.0 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;
using System.Configuration;
using Google.Contacts;
using Google.Documents;
using Google.GData.Client.ResumableUpload;
using Google.GData.Documents;
using System.Collections;
namespace GoContactSyncMod.UnitTests
{
[TestFixture]
public class GoogleAPITests
{
ClientLoginAuthenticator _authenticator;
static Logger.LogUpdatedHandler _logUpdateHandler = null;
void Logger_LogUpdated(string message)
{
Console.WriteLine(message);
}
[TestFixtureSetUp]
public void Init()
{
//string timestamp = DateTime.Now.Ticks.ToString();
if (_logUpdateHandler == null)
{
_logUpdateHandler = new Logger.LogUpdatedHandler(Logger_LogUpdated);
Logger.LogUpdated += _logUpdateHandler;
}
}
[Test]
public void CreateNewContact()
{
string gmailUsername;
string gmailPassword;
string syncProfile;
GoogleAPITests.LoadSettings(out gmailUsername, out gmailPassword, out syncProfile);
RequestSettings rs = new RequestSettings("GoogleContactSyncMod", gmailUsername, gmailPassword);
ContactsRequest service = new ContactsRequest(rs);
#region Delete previously created test contact.
ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
query.NumberToRetrieve = 500;
Feed<Contact> feed = service.Get<Contact>(query);
Logger.Log("Loaded Google contacts", EventType.Information);
foreach (Contact entry in feed.Entries)
{
if (entry.PrimaryEmail != null && entry.PrimaryEmail.Address == "johndoe@example.com")
{
service.Delete(entry);
Logger.Log("Deleted Google contact", EventType.Information);
//break;
}
}
#endregion
Contact newEntry = new Contact();
newEntry.Title = "John Doe";
EMail primaryEmail = new EMail("johndoe@example.com");
primaryEmail.Primary = true;
primaryEmail.Rel = ContactsRelationships.IsWork;
newEntry.Emails.Add(primaryEmail);
PhoneNumber phoneNumber = new PhoneNumber("555-555-5551");
phoneNumber.Primary = true;
phoneNumber.Rel = ContactsRelationships.IsMobile;
newEntry.Phonenumbers.Add(phoneNumber);
StructuredPostalAddress postalAddress = new StructuredPostalAddress();
postalAddress.Street = "123 somewhere lane";
postalAddress.Primary = true;
postalAddress.Rel = ContactsRelationships.IsHome;
newEntry.PostalAddresses.Add(postalAddress);
newEntry.Content = "Who is this guy?";
Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
Contact createdEntry = service.Insert(feedUri, newEntry);
Logger.Log("Created Google contact", EventType.Information);
Assert.IsNotNull(createdEntry.ContactEntry.Id.Uri);
Contact updatedEntry = service.Update(createdEntry);
Logger.Log("Updated Google contact", EventType.Information);
//delete test contacts
service.Delete(createdEntry);
Logger.Log("Deleted Google contact", EventType.Information);
}
[Test]
public void CreateNewNote()
{
string gmailUsername;
string gmailPassword;
string syncProfile;
GoogleAPITests.LoadSettings(out gmailUsername, out gmailPassword, out syncProfile);
RequestSettings rs = new RequestSettings("GoogleContactSyncMod", gmailUsername, gmailPassword);
DocumentsRequest service = new DocumentsRequest(rs);
//Instantiate an Authenticator object according to your authentication, to use ResumableUploader
_authenticator = new ClientLoginAuthenticator("GCSM Unit Tests", service.Service.ServiceIdentifier, gmailUsername, gmailPassword);
//Delete previously created test note.
DeleteTestNote(service);
Document newEntry = new Document();
newEntry.Type = Document.DocumentType.Document;
newEntry.Title = "AN_OUTLOOK_TEST_NOTE";
string file = NotePropertiesUtils.CreateNoteFile("AN_OUTLOOK_TEST_NOTE", "This is just a test note to test GoContactSyncMod", null);
newEntry.MediaSource = new MediaFileSource(file, MediaFileSource.GetContentTypeForFileName(file));
#region normal flow, only working to create documents without content (metadata only), e.g. for Notes folder
Document createdEntry = Syncronizer.SaveGoogleNote(null, newEntry, service);
Assert.IsNotNull(createdEntry.DocumentEntry.Id.Uri);
Logger.Log("Created Google note", EventType.Information);
//delete test note
DeleteTestNote(service);
#endregion
#region workaround flow to use UploadDocument, not needed anymore because of new approach to use ResumableUploader
//Google.GData.Documents.DocumentEntry createdEntry2 = service.Service.UploadDocument(file, newEntry.Title);
//Assert.IsNotNull(createdEntry2.Id.Uri);
////delete test note
//DeleteTestNote(service);
#endregion
#region New approach how to update an existing document: https://developers.google.com/google-apps/documents-list/#updatingchanging_documents_and_files
//Instantiate the ResumableUploader component.
ResumableUploader uploader = new ResumableUploader();
uploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(OnGoogleNoteCreated);
Syncronizer.CreateGoogleNote(newEntry, file, service, uploader, _authenticator);
#endregion
//Wait 5 seconds to give the testcase the chance to finish the Async events
System.Threading.Thread.Sleep(5000);
DeleteTestNote(service);
}
private void OnGoogleNoteCreated(object sender, AsyncOperationCompletedEventArgs e)
{
DocumentEntry entry = e.Entry as DocumentEntry;
Assert.IsNotNull(entry);
Logger.Log("Created Google note", EventType.Information);
//Now update the same entry
//Instantiate the ResumableUploader component.
ResumableUploader uploader = new ResumableUploader();
uploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(OnGoogleNoteUpdated);
uploader.UpdateAsync(_authenticator, entry, e.UserState);
}
private void OnGoogleNoteUpdated(object sender, AsyncOperationCompletedEventArgs e)
{
DocumentEntry entry = e.Entry as DocumentEntry;
Assert.IsNotNull(entry);
Logger.Log("Updated Google note", EventType.Information);
System.IO.File.Delete(e.UserState as string);
}
private static void DeleteTestNote(DocumentsRequest service)
{
//ToDo: Doesn'T work always, frequently throwing 401, Precondition failed, maybe Google API bug
//service.Delete(createdEntry);
//Todo: Workaround to load document again
DocumentQuery query = new DocumentQuery(service.BaseUri);
query.NumberToRetrieve = 500;
Feed<Document> feed = service.Get<Document>(query);
Logger.Log("Loaded Google notes", EventType.Information);
foreach (Document entry in feed.Entries)
{
if (entry.Title == "AN_OUTLOOK_TEST_NOTE")
{
//service.Delete(entry);
service.Delete(new Uri(Google.GData.Documents.DocumentsListQuery.documentsBaseUri + "/" + entry.ResourceId), entry.ETag);
Logger.Log("Deleted Google note", EventType.Information);
//break;
}
}
}
internal static void LoadSettings(out string gmailUsername, out string gmailPassword, out string syncProfile, out string syncContactsFolder, out string syncNotesFolder)
{
Microsoft.Win32.RegistryKey regKeyAppRoot = LoadSettings(out gmailUsername, out gmailPassword, out syncProfile);
syncContactsFolder = "";
syncNotesFolder = "";
//First, check if there is a folder called GCSMTestContacts and GCSMTestNotes available, if yes, use them
ArrayList outlookContactFolders = new ArrayList();
ArrayList outlookNoteFolders = new ArrayList();
Microsoft.Office.Interop.Outlook.Folders folders = Syncronizer.OutlookNameSpace.Folders;
foreach (Microsoft.Office.Interop.Outlook.Folder folder in folders)
{
try
{
SettingsForm.GetOutlookMAPIFolders(outlookContactFolders, outlookNoteFolders, folder);
}
catch (Exception e)
{
Logger.Log("Error getting available Outlook folders: " + e.Message, EventType.Warning);
}
}
foreach (OutlookFolder folder in outlookContactFolders)
{
if (folder.FolderName.ToUpper().Contains("GCSMTestContacts".ToUpper()))
{
Logger.Log("Uses Test folder: " + folder.DisplayName, EventType.Information);
syncContactsFolder = folder.FolderID;
break;
}
}
foreach (OutlookFolder folder in outlookNoteFolders)
{
if (folder.FolderName.ToUpper().Contains("GCSMTestNotes".ToUpper()))
{
Logger.Log("Uses Test folder: " + folder.DisplayName, EventType.Information);
syncNotesFolder = folder.FolderID;
break;
}
}
if (string.IsNullOrEmpty(syncContactsFolder))
if (regKeyAppRoot.GetValue("SyncContactsFolder") != null)
syncContactsFolder = regKeyAppRoot.GetValue("SyncContactsFolder") as string;
if (string.IsNullOrEmpty(syncNotesFolder))
if (regKeyAppRoot.GetValue("SyncNotesFolder") != null)
syncNotesFolder = regKeyAppRoot.GetValue("SyncNotesFolder") as string;
}
private static Microsoft.Win32.RegistryKey LoadSettings(out string gmailUsername, out string gmailPassword, out string syncProfile)
{
//sync.LoginToGoogle(ConfigurationManager.AppSettings["Gmail.Username"], ConfigurationManager.AppSettings["Gmail.Password"]);
//ToDo: Reading the username and config from the App.Config file doesn't work. If it works, consider special characters like & = &amp; in the XML file
//ToDo: Maybe add a common Test account to the App.config and read it from there, encrypt the password
//For now, read the userName and Password from the Registry (same settings as for GoogleContactsSync Application
gmailUsername = "";
gmailPassword = "";
const string appRootKey = @"Software\Webgear\GOContactSync";
Microsoft.Win32.RegistryKey regKeyAppRoot = regKeyAppRoot = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(appRootKey);
syncProfile = "Default Profile";
if (regKeyAppRoot.GetValue("SyncProfile") != null)
syncProfile = regKeyAppRoot.GetValue("SyncProfile") as string;
regKeyAppRoot = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(appRootKey + (syncProfile != null ? ('\\' + syncProfile) : ""));
if (regKeyAppRoot.GetValue("Username") != null)
{
gmailUsername = regKeyAppRoot.GetValue("Username") as string;
if (regKeyAppRoot.GetValue("Password") != null)
gmailPassword = Encryption.DecryptPassword(gmailUsername, regKeyAppRoot.GetValue("Password") as string);
}
return regKeyAppRoot;
}
}
}
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.