/////////////////////////////////////////////////////////////////////////////



        //////////////////////////////////////////////////////////////////////
        /// <summary>runs an authentication test</summary> 
        //////////////////////////////////////////////////////////////////////
        [Test] public void ContactsAuthenticationTest()
        {
            Tracing.TraceMsg("Entering ContactsAuthenticationTest");

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName + "@googlemail.com"));
            ContactsService service = new ContactsService("unittests");

            if (this.userName != null)
            {
                service.Credentials = new GDataCredentials(this.userName, this.passWord);
            }

            ContactsFeed feed = service.Query(query);

            ObjectModelHelper.DumpAtomObject(feed,CreateDumpFileName("ContactsAuthTest")); 

            if (feed != null && feed.Entries.Count > 0)
            {
                Tracing.TraceMsg("Found a Feed " + feed.ToString());

                foreach (ContactEntry entry in feed.Entries)
                {
                    Assert.IsTrue(entry.Etag != null, "contact entries should have etags");
                }
            }
        }
Example #2
0
        public void CreateNewContact()
        {
            try
            {
                ContactsService service = new ContactsService("WebGear.GoogleContactsSync");
                service.setUserCredentials(ConfigurationManager.AppSettings["Gmail.Username"],
                    ConfigurationManager.AppSettings["Gmail.Password"]);

                #region Delete previously created test contact.
                ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                query.NumberToRetrieve = 500;

                ContactsFeed feed = service.Query(query);

                foreach (ContactEntry entry in feed.Entries)
                {
                    if (entry.PrimaryEmail != null && entry.PrimaryEmail.Address == "*****@*****.**")
                    {
                        entry.Delete();
                        break;
                    }
                }
                #endregion

                ContactEntry newEntry = new ContactEntry();
                newEntry.Title.Text = "John Doe";

                EMail primaryEmail = new EMail("*****@*****.**");
                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);

                PostalAddress postalAddress = new PostalAddress();
                postalAddress.Value = "123 somewhere lane";
                postalAddress.Primary = true;
                postalAddress.Rel = ContactsRelationships.IsHome;
                newEntry.PostalAddresses.Add(postalAddress);

                newEntry.Content.Content = "Who is this guy?";

                Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));

                ContactEntry createdEntry = (ContactEntry)service.Insert(feedUri, newEntry);

                Assert.IsNotNull(createdEntry.Id.Uri);

                //delete this temp contact
                createdEntry.Delete();
            }
            catch (Exception ex)
            {

            }
        }
Example #3
0
        static void Main(string[] args)
        {
            try
            {
                // create an OAuth factory to use
                GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "MyApp");
                requestFactory.ConsumerKey = "CONSUMER_KEY";
                requestFactory.ConsumerSecret = "CONSUMER_SECRET";

                // example of performing a query (use OAuthUri or query.OAuthRequestorId)
                Uri calendarUri = new OAuthUri("http://www.google.com/calendar/feeds/default/owncalendars/full", "USER", "DOMAIN");
                // can use plain Uri if setting OAuthRequestorId in the query
                // Uri calendarUri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");

                CalendarQuery query = new CalendarQuery();
                query.Uri = calendarUri;
                query.OAuthRequestorId = "USER@DOMAIN"; // can do this instead of using OAuthUri for queries

                CalendarService service = new CalendarService("MyApp");
                service.RequestFactory = requestFactory;
                service.Query(query);
                Console.WriteLine("Query Success!");

                // example with insert (must use OAuthUri)
                Uri contactsUri = new OAuthUri("http://www.google.com/m8/feeds/contacts/default/full", "USER", "DOMAIN");

                ContactEntry entry = new ContactEntry();
                EMail primaryEmail = new EMail("*****@*****.**");
                primaryEmail.Primary = true;
                primaryEmail.Rel = ContactsRelationships.IsHome;
                entry.Emails.Add(primaryEmail);

                ContactsService contactsService = new ContactsService("MyApp");
                contactsService.RequestFactory = requestFactory;
                contactsService.Insert(contactsUri, entry); // this could throw if contact exists

                Console.WriteLine("Insert Success!");

                // to perform a batch use
                // service.Batch(batchFeed, new OAuthUri(atomFeed.Batch, userName, domain));

                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fail!");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.ReadKey();
            }
        }
        //////////////////////////////////////////////////////////////////////
        /// <summary>runs an authentication test, inserts a new contact</summary> 
        //////////////////////////////////////////////////////////////////////
        [Test] public void InsertContactsTest()
        {
            const int numberOfInserts = 37;
            Tracing.TraceMsg("Entering InsertContactsTest");

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName + "@googlemail.com")); 
            ContactsService service = new ContactsService("unittests");

            if (this.userName != null)
            {
                service.Credentials = new GDataCredentials(this.userName, this.passWord);
            }

            ContactsFeed feed = service.Query(query);

            int originalCount = feed.Entries.Count;

            PhoneNumber p = null;

            List<ContactEntry> inserted = new List<ContactEntry>();
            if (feed != null)
            {
                Assert.IsTrue(feed.Entries != null, "the contacts needs entries");

                for (int i = 0; i < numberOfInserts; i++)
                {
                    ContactEntry entry = ObjectModelHelper.CreateContactEntry(i);
                    entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com";

                    p = entry.PrimaryPhonenumber;
                    inserted.Add(feed.Insert(entry));
                }
            }


            List<ContactEntry> list = new List<ContactEntry>();

            feed = service.Query(query);
            foreach (ContactEntry e in feed.Entries)
            {
                list.Add(e);
            }

            while (feed.NextChunk != null)
            {
                ContactsQuery nq = new ContactsQuery(feed.NextChunk); 
                feed = service.Query(nq);
                foreach (ContactEntry e in feed.Entries)
                {
                    list.Add(e);
                }
            }
            


            if (inserted.Count > 0)
            {
                int iVer = numberOfInserts;
                // let's find those guys
                for (int i = 0; i < inserted.Count; i++)
                {
                    ContactEntry test = inserted[i] as ContactEntry;
                    foreach (ContactEntry e in list)
                    {
                        if (e.Id == test.Id)
                        {
                            iVer--;
                            // verify we got the phonenumber back....
                            Assert.IsTrue(e.PrimaryPhonenumber != null, "They should have a primary phonenumber");
                            Assert.AreEqual(e.PrimaryPhonenumber.Value,p.Value, "They should be identical");
                        }
                    }
                }

                Assert.IsTrue(iVer == 0, "The new entries should all be part of the feed now, we have " + iVer + " now");
            }

            // now delete them again

            foreach (ContactEntry e in inserted)
            {
                e.Delete();
            }

            // now make sure they are gone
            if (inserted.Count > 0)
            {
                feed = service.Query(query);

                // let's find those guys, we should not find ANY
                for (int i = 0; i < inserted.Count; i++)
                {
                    ContactEntry test = inserted[i] as ContactEntry;
                    foreach (ContactEntry e in feed.Entries)
                    {
                        Assert.IsTrue(e.Id != test.Id, "The new entries should all be deleted now");
                    }
                }
                Assert.IsTrue(feed.Entries.Count == originalCount, "The count should be correct as well");
            }
        }
 /////////////////////////////////////////////////////////////////////////////
 
 
 private void AddContactPhoto(ContactEntry entry, ContactsService contactService)
 {
     try
     {
         using (FileStream fs = new FileStream(this.resourcePath + "contactphoto.jpg", System.IO.FileMode.Open))
         {
             Stream res = contactService.StreamSend(entry.PhotoUri, fs, GDataRequestType.Update, "image/jpg", null);
             res.Close();
         }
     } finally   
     {
     }
 } 
        public void ConflictContactsTest()
        {
            const int numberOfInserts = 50;
            const int numberWithAdds = 60; 
            Tracing.TraceMsg("Entering InsertContactsTest");

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName + "@googlemail.com"));
            ContactsService service = new ContactsService("unittests");


            if (this.userName != null)
            {
                service.Credentials = new GDataCredentials(this.userName, this.passWord);
            }

            // clean the contacts feed
            DeleteAllContacts();

            ContactsFeed feed = service.Query(query);

            int originalCount = feed.Entries.Count;

            string email = Guid.NewGuid().ToString();

            List<ContactEntry> inserted = new List<ContactEntry>();

            // insert a number of guys
            for (int i = 0; i < numberOfInserts; i++)
            {
                ContactEntry entry = ObjectModelHelper.CreateContactEntry(i);
                entry.PrimaryEmail.Address = email + i.ToString() + "@doe.com";
                entry = feed.Insert(entry);
                AddContactPhoto(entry, service);
                inserted.Add(entry);

            }


            if (feed != null)
            {
                for (int x = numberOfInserts; x <= numberWithAdds; x++)
                {
                    for (int i = 0; i < x; i++)
                    {
                        ContactEntry entry = ObjectModelHelper.CreateContactEntry(i);
                        entry.PrimaryEmail.Address = email + i.ToString() + "@doe.com";

                        try
                        {
                            entry = feed.Insert(entry);
                            AddContactPhoto(entry, service);
                            inserted.Add(entry);
                        }
                        catch (GDataRequestException)
                        {
                        }
                    }
                }
            }

            List<ContactEntry> list = new List<ContactEntry>();
            feed = service.Query(query);
            foreach (ContactEntry e in feed.Entries)
            {
                list.Add(e);
            }

            while (feed.NextChunk != null)
            {
                ContactsQuery nq = new ContactsQuery(feed.NextChunk);
                feed = service.Query(nq);
                foreach (ContactEntry e in feed.Entries)
                {
                    list.Add(e);
                }
            }

            Assert.AreEqual(list.Count, numberWithAdds - originalCount, "We should have added new entries");

            // clean the contacts feed
            DeleteAllContacts();

        }
        /////////////////////////////////////////////////////////////////////////////


        /////////////////////////////////////////////////////////////////////
        /// <summary>runs an basic auth test against the groups feed test</summary> 
        //////////////////////////////////////////////////////////////////////
        [Test] public void GroupsSystemTest()
        {
            Tracing.TraceMsg("Entering GroupsSystemTest");

            GroupsQuery query = new GroupsQuery(ContactsQuery.CreateGroupsUri(this.userName + "@googlemail.com"));
            ContactsService service = new ContactsService("unittests");

            if (this.userName != null)
            {
                service.Credentials = new GDataCredentials(this.userName, this.passWord);
            }

            GroupsFeed feed = service.Query(query);

            int i = 0; 
            foreach (GroupEntry g in feed.Entries )
            {
               if (g.SystemGroup != null)
               {
                   i++;
               }
            }

            Assert.IsTrue(i==4, "There should be 4 system groups in the groups feed");


            ObjectModelHelper.DumpAtomObject(feed,CreateDumpFileName("GroupsAuthTest"));

            GroupEntry newGroup = new GroupEntry();
            newGroup.Title.Text = "Private Data";

            GroupEntry insertedGroup = feed.Insert(newGroup);

            GroupEntry g2 = new GroupEntry();
            g2.Title.Text = "Another Private Group";
            GroupEntry insertedGroup2 = feed.Insert(g2);

            // now insert a new contact that belongs to that group
            ContactsQuery q = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName + "@googlemail.com"));
            ContactsFeed cf = service.Query(q);
            ContactEntry entry = ObjectModelHelper.CreateContactEntry(1);
            GroupMembership member = new GroupMembership();
            member.HRef = insertedGroup.Id.Uri.ToString();
            GroupMembership member2 = new GroupMembership();
            member2.HRef = insertedGroup2.Id.Uri.ToString();

            ContactEntry insertedEntry = cf.Insert(entry);
            // now change the group membership
            insertedEntry.GroupMembership.Add(member);
            insertedEntry.GroupMembership.Add(member2);
            ContactEntry currentEntry = insertedEntry.Update();

            Assert.IsTrue(currentEntry.GroupMembership.Count == 2, "The entry should be in 2 groups");

            currentEntry.GroupMembership.Clear();
            currentEntry = currentEntry.Update();
            // now we should have 2 new groups and one new entry with no groups anymore


            int oldCountGroups = feed.Entries.Count;
            int oldCountContacts = cf.Entries.Count;

            currentEntry.Delete();

            insertedGroup.Delete();
            insertedGroup2.Delete();

            feed = service.Query(query);
            cf = service.Query(q);

            Assert.AreEqual(oldCountContacts, cf.Entries.Count, "Contacts count should be the same");
            Assert.AreEqual(oldCountGroups, feed.Entries.Count, "Groups count should be the same");
        }
        private void GetContactList(string username, string password)
        {
            contactTable.Columns.Add("Photo", typeof(System.Drawing.Bitmap));
            contactTable.Columns.Add("Name", typeof(string));
            contactTable.Columns.Add("Email", typeof(string));
            toDataGrid.DataSource = contactTable;
            toDataGrid.ShowCellToolTips = false;
            ccDataGrid.DataSource = contactTable;
            bccDataGrid.DataSource = contactTable;
            DataGridViewColumn column = toDataGrid.Columns[0];
            column.Width = 42;
            column.HeaderText = "";
            column = ccDataGrid.Columns[0];
            column.Width = 42;
            column.HeaderText = "";
            column = bccDataGrid.Columns[0];
            column.Width = 42;
            column.HeaderText = "";

            ContactsService client = new ContactsService("William Randol-Gmail Icon Notifier-0.8 (RC1)");
            client.setUserCredentials(user, pass);
            string authToken = client.QueryAuthenticationToken(); // Authenticate the user immediately

            RequestSettings rs = new RequestSettings("Gmail Icon Notifier", user, pass);
            rs.AutoPaging = true;
            ContactsRequest cr = new ContactsRequest(rs);

            Feed<Contact> f = cr.GetContacts();

            foreach (Contact c in f.Entries)
            {
                foreach (EMail email in c.Emails)
                {
                    contactTable.Rows.Add(contactPhoto(c, authToken), c.Title, email.Address);
                }
            }
        }
Example #9
0
            public string GetDomain(ContactsService ContactService)
            {
                char[] delimiterChars = { '@' };
                string[] temp = ContactService.Credentials.Username.ToString().Split(delimiterChars);
                var Domain = temp[1];

                return Domain;
            }
Example #10
0
        /// <summary>
        /// Authenticates the user to the Contacts API
        /// </summary>
        /// <param name="username">The user's username (e-mail)</param>
        /// <param name="password">The user's password</param>
        /// <exception cref="AuthenticationException">Thrown on invalid credentials.</exception>
        public void Login(string username, string password)
        {
            if (loggedIn)
            {
                throw new ApplicationException("Already logged in.");
            }

            try
            {
                this.service = new ContactsService("google-ContactsClientExample-v1.0");
                ((GDataRequestFactory)this.service.RequestFactory).KeepAlive = false;

                this.service.setUserCredentials(username, password);
                this.service.QueryAuthenticationToken();

                loggedIn = true;
            }
            catch (AuthenticationException e)
            {
                loggedIn = false;
                this.service = null;
                throw e;
            }
        }
 private static ContactsFeed GetContactsFeed(ContactsQuery query, ContactsService service)
 {
     ContactsFeed feed = service.Query(query);
     return feed;
 }
 private static ContactsService CreateService(string username, string password, string appName)
 {
     ContactsService service = new ContactsService(appName);
     service.setUserCredentials(username, password);
     return service;
 }
Example #13
0
        private ActionResult OAuthCallback()
        {
            IAuthorizationState auth = client.ProcessUserAuthorization(Request);
            Session["auth"] = auth;
            var authFactory = new GAuthSubRequestFactory("cp", "Geeks Dilemma") {Token = auth.AccessToken};
            var service = new ContactsService(authFactory.ApplicationName) {RequestFactory = authFactory};

            var query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
            query.NumberToRetrieve = 1000;
            ContactsFeed contacts = service.Query(query);
            ViewBag.ImportFrom = "Google";
            var userId = GetCurrentUserId();

            DeletePreviousImportIfNecessary(userId);

            var googleContact = new GoogleContact
                {
                    UserId = userId,
                    Contacts = (from ContactEntry entry in contacts.Entries
                                from email in entry.Emails
                                where entry.Name != null
                                where email != null
                                select new ImportModel
                                    {
                                        Import = false,
                                        EmailAddress = email.Address.ToLower(),
                                        Name = entry.Name.FullName
                                    }).ToList()
                };

            RavenSession.Store(googleContact);

            return View("Import");
        }
		public void FetchTask()
		{
			if (syncEngine.SyncCanceled)
			{
				this.FetchSem.Release();
				return;
			}

			mans.Clear();
			contactsByFullName.Clear();

			googleService = new ContactsService("Contact Infomation");

			if (Credentials == null)
			{
				this.FetchSem.Release();
				return;
			}
			else
			{
				if (Credentials.UserName != null && !Credentials.UserName.ToLower().EndsWith("@gmail.com"))
				{
					Credentials.UserName += "@gmail.com";
				}
				googleService.setUserCredentials(Credentials.UserName, Credentials.Password);
			}

			((GDataRequestFactory)googleService.RequestFactory).Timeout = 3000;

			queruUriFull = ContactsQuery.CreateContactsUri(Credentials.UserName, ContactsQuery.fullProjection);
			contactsQuery = new ContactsQuery(queruUriFull);
			contactsQuery.NumberToRetrieve = 1000;

			try
			{

				feed = googleService.Query(contactsQuery);
			}
			catch (Google.GData.Client.GDataRequestException e)
			{
				Credentials = null;

				Dispatcher.Invoke(new SyncCancelEventHandler(owner.CancelSync),
						this, e.InnerException.Message, null);

				this.FetchSem.Release();
				return;
			}
			catch (Google.GData.Client.InvalidCredentialsException e)
			{
				Credentials = null;

				Dispatcher.Invoke(new SyncCancelEventHandler(owner.CancelSync),
						this, e.Message, null);

				this.FetchSem.Release();
				return;
			}
			catch (CaptchaRequiredException e)
			{
				Credentials = null;

				Dispatcher.Invoke(new SyncCancelEventHandler(owner.CancelSync),
						this, e.Message, "https://www.google.com/accounts/UnlockCaptcha");

				this.FetchSem.Release();
				return;
			}
			catch (Exception e)
			{
				Credentials = null;

				Dispatcher.Invoke(new SyncCancelEventHandler(owner.CancelSync),
						this, e.Message, null);

				this.FetchSem.Release();
				return;
			}

			syncEngine.CurrentTotal += feed.Entries.Count;
			
			GroupsQuery groupsQuery = new GroupsQuery(GroupsQuery.
				CreateGroupsUri(Credentials.UserName, ContactsQuery.thinProjection));

			try
			{
				groupsFeed = googleService.Query(groupsQuery);
			} 
			catch (Google.GData.Client.GDataRequestException e)
			{
				Credentials = null;

				Dispatcher.Invoke(new SyncCancelEventHandler(owner.CancelSync),
						this, e.InnerException.Message, null);
								
				this.FetchSem.Release();
				return;
			}

			foreach (ContactEntry entry in feed.Entries)
			{

				if (owner != null)
				{
					Dispatcher.Invoke(new SyncProgressEventHandler(owner.Progress), this,
						"Loading " + "(" + syncEngine.CurrentItemNum + "/" + syncEngine.CurrentTotal + ")",
						syncEngine.CurrentItemNum, syncEngine.CurrentTotal);
					syncEngine.CurrentItemNum++;
				}

				Contact contact = GetCanonicalContact(entry);
				
				string fullname = contact.FullName;

				if (fullname == null || fullname.Trim() == "")
				{
				}
				else
				{
					contactsByFullName[fullname] = contact;
					mans.Add(new Man { FullName = fullname, EMail = contact.EMail, Phone = contact.Phone });
				}
				
			}

			this.FetchSem.Release();
		}
Example #15
0
        public void LoginToGoogle(string username, string password)
        {
            if (_googleService == null)
                _googleService = new ContactsService("WebGear.GoogleContactsSync");

            _googleService.setUserCredentials(username, password);
            _authToken = _googleService.QueryAuthenticationToken();

            int maxUserIdLength = Syncronizer.OutlookUserPropertyMaxLength - (Syncronizer.OutlookUserPropertyTemplate.Length - 3 + 2);//-3 = to remove {0}, +2 = to add length for "id" or "up"
            string userId = _googleService.Credentials.Username;
            if (userId.Length > maxUserIdLength)
                userId = userId.GetHashCode().ToString("X"); //if a user id would overflow UserProperty name, then use that user id hash code as id.

            _propertyPrefix = string.Format(Syncronizer.OutlookUserPropertyTemplate, userId);
        }
Example #16
0
        protected void ExecuteImport()
        {
            //start sync
            ContactsService GContactService = new ContactsService("Contact Infomation");
            GContactService.setUserCredentials(email, password);

            ContactsQuery query = new ContactsQuery(ContactsQuery.
            CreateContactsUri("default"));
            ContactsFeed feed = null;

            try
            {
                feed = GContactService.Query(query);
            }
            catch (Exception)
            {
                this.setLabelText("Invalid email or password", Color.Red);
                return;
            }

            //start
            this.showProgressBar(feed.TotalResults);
            this.setLabelText("Importing...", Color.Black);

            int progress = 0;
            int startIndex = 0;
            while (feed.Entries.Count > 0)
            {
                startIndex += feed.ItemsPerPage;
                query.StartIndex = startIndex;
                PhoneNumbers.PhoneNumberUtil util = PhoneNumbers.PhoneNumberUtil.GetInstance();
                foreach (ContactEntry entry in feed.Entries)
                {
                    this.setProgress(progress);
                    progress++;

                    if (entry.Phonenumbers.Count > 0)
                    {
                        foreach (PhoneNumber number in entry.Phonenumbers)
                        {
                            string numb = string.Empty;
                            try
                            {
                                PhoneNumbers.PhoneNumber num = util.Parse(number.Value, "NL");
                                numb = num.CountryCode.ToString() + num.NationalNumber.ToString();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Exception was thrown: " + ex.Message);
                                continue;
                            }
                            if (!ContactStore.numberExists(numb + "@s.whatsapp.net"))
                            {
                                Contact contact = new Contact(0, numb + "@s.whatsapp.net", "", "", entry.Name.GivenName, entry.Name.FamilyName);
                                ContactStore.AddContact(contact);
                            }
                        }
                    }
                }
                feed = GContactService.Query(query);
            }

            //done!
            this.doExit();
        }
Example #17
0
            protected override void ProcessRecord()
            {
                adminUser = credentials.UserName;
                adminPassword = new Dgc.ConvertToUnsecureString(credentials.Password).PlainString;
                var _domain = dgcGoogleAppsService.GetDomain(adminUser);

                try
                {
                    //AppsService
                    service.AppsService = new AppsService(_domain, adminUser, adminPassword);

                    //CalendarService
                    var _calendarService = new CalendarService("Calendar");
                    _calendarService.setUserCredentials(adminUser, adminPassword);
                    service.CalendarService = _calendarService;

                    //OauthCalendarService
                    if (consumerKey != null)
                    {
                        if (consumerSecret == null)
                        {
                            throw new Exception("-ConsumerSecret can't be null");
                        }
                        var _oauthCalendarService = new CalendarService("Calendar");
                        var _oauth = new GDataTypes.Oauth();
                        _oauth.ConsumerKey = consumerKey;
                        _oauth.ConsumerSecret = consumerSecret;
                        service.Oauth = _oauth;
                        GOAuthRequestFactory _requestFactory = new GOAuthRequestFactory("cl", "GDataCmdLet");
                        _requestFactory.ConsumerKey = _oauth.ConsumerKey;
                        _requestFactory.ConsumerSecret = _oauth.ConsumerSecret;
                        _oauthCalendarService.RequestFactory = _requestFactory;
                        service.OauthCalendarService = _oauthCalendarService;
                    }

                    //MailSettingsService
                    var _googleMailSettingsService = new GoogleMailSettingsService(_domain, "GMailSettingsService");
                    _googleMailSettingsService.setUserCredentials(adminUser, adminPassword);
                    service.GoogleMailSettingsService = _googleMailSettingsService;

                    //ProfileService
                    var _dgcGoogleProfileService = new Dgc.GoogleProfileService();
                    service.ProfileService = _dgcGoogleProfileService.GetAuthToken(adminUser, adminPassword);

                    //ResourceService
                    var _dgcGoogleResourceService = new Dgc.GoogleResourceService();
                    service.ResourceService = _dgcGoogleResourceService.GetAuthToken(adminUser, adminPassword);

                    //ContactsService
                    var _contactService = new ContactsService("GData");
                    _contactService.setUserCredentials(adminUser, adminPassword);
                    service.ContactsService = _contactService;

                    WriteObject(service);
                }
                catch (AppsException _exception)
                {
                    WriteObject(_exception, true);
                }
            }
        public string GoogleContactLookup(string username, string password, string lookup)
        {
            try
            {
                Log("Starting Google Contact Lookup for " + lookup + ".");

                ContactsService service = new ContactsService("sipsorcery-lookup");
                ((GDataRequestFactory)service.RequestFactory).KeepAlive = false;

                service.setUserCredentials(username, password);
                var result = service.QueryClientLoginToken();

                var query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                query.ExtraParameters = "q=" + lookup + "&max-results=1";

                ContactsFeed feed = service.Query(query);

                if (feed != null && feed.Entries != null && feed.Entries.Count > 0)
                {
                    var entry = feed.Entries.First() as ContactEntry;

                    if (entry.Name != null && entry.Name.FullName.NotNullOrBlank())
                    {
                        Log("Result found Google Contact Lookup for " + lookup + " of " + entry.Name.FullName + ".");
                        return entry.Name.FullName;
                    }
                    else
                    {
                        Log("A result was found Google Contact Lookup for " + lookup + " but the FullName field was empty.");
                        return null;
                    }
                }
                else
                {
                    Log("No result was found with a Google Contact Lookup for " + lookup + ".");
                    return null;
                }
            }
            catch (Exception excp)
            {
                Log("Exception in GoogleContactLookup. " + excp.Message);
                return null;
            }
        }