Exemplo n.º 1
0
        /// <summary>
        /// Import all Google contacts
        /// </summary>
        public void ImportGmail()
        {
            string MyContactID = GetGroups();

            Contact = new List <contacts>();

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));

            query.StartIndex  = 1;
            query.ShowDeleted = false;
            if (MyContactID != "")
            {
                query.Group = MyContactID;
            }

            Feed <Google.Contacts.Contact> f = cr.Get <Google.Contacts.Contact>(query);
            int contactsCount = f.Entries.Count();

            while (contactsCount > 0)
            {
                foreach (Google.Contacts.Contact entry in f.Entries)
                {
                    contacts contact;
                    if (ConvertContact(entry, out contact))
                    {
                        Contact.Add(contact);
                    }
                }

                query.StartIndex += contactsCount;
                f             = cr.Get <Google.Contacts.Contact>(query);
                contactsCount = f.Entries.Count();
            }


            /*for (int i = 0; i < Contact.Count; i++)
             * {
             *
             *  var item = Contact[i];
             *  if (item.AvatarUri != null)
             *  {
             *      try
             *      {
             *          item.Avatar = cr.Service.Query(item.AvatarUri);
             *      }
             *      catch (Exception err)
             *      {
             *
             *      }
             *      Contact.RemoveAt(i);
             *      Contact.Insert(i, item);
             *  }
             * }*/
        }
Exemplo n.º 2
0
        public async Task <IList <Contact> > ReadContactsAsync(string query)
        {
            var secrets = Paths.BinDir.CatDir("client_secret_292564741141-6fa0tqv21ro1v8s28gj4upei0muvuidm.apps.googleusercontent.com.json").Read(GoogleClientSecrets.Load).Secrets;

            var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                secrets,
                new string[] { "https://www.google.com/m8/feeds" },
                credentialProvider.GetCredential().UserName,
                CancellationToken.None,
                null);

            var parameters = new Google.GData.Client.OAuth2Parameters()
            {
                ClientId     = secrets.ClientId,
                ClientSecret = secrets.ClientSecret,
                RedirectUri  = redirectUri,
                Scope        = scope,
                AccessToken  = credential.Token.AccessToken,
                RefreshToken = credential.Token.RefreshToken,
            };

            var contacts = new ContactsRequest(new RequestSettings("hagen", parameters));
            var q        = new FeedQuery("https://www.google.com/m8/feeds/contacts/default/full")
            {
                Query = query
            };
            var feed    = contacts.Get <Contact>(q);
            var entries = feed.Entries.ToList();

            return(entries);
        }
        public void InsertExtendedPropertyContactsTest()
        {
            Tracing.TraceMsg("Entering InsertExtendedPropertyContactsTest");

            DeleteAllContacts();

            RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);

            rs.AutoPaging = true;

            FeedQuery query = new FeedQuery();

            query.Uri = new Uri(CreateUri(this.resourcePath + "contactsextendedprop.xml"));



            ContactsRequest cr = new ContactsRequest(rs);

            Feed <Contact> f = cr.Get <Contact>(query);

            Contact newEntry = null;

            foreach (Contact c in f.Entries)
            {
                ExtendedProperty e = c.ExtendedProperties[0];
                Assert.IsTrue(e != null);
                newEntry = c;
            }

            f = cr.GetContacts();

            Contact createdEntry = cr.Insert <Contact>(f, newEntry);

            cr.Delete(createdEntry);
        }
Exemplo n.º 4
0
        public async Task ReadContactsAsync()
        {
            var secrets = Paths.BinDir.CatDir("client_secret_292564741141-6fa0tqv21ro1v8s28gj4upei0muvuidm.apps.googleusercontent.com.json").Read(GoogleClientSecrets.Load).Secrets;

            var credentialProvider = Sidi.CredentialManagement.Factory.GetCredentialProvider("https://www.google.com/m8/feeds");

            var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                secrets,
                new string[] { "https://www.google.com/m8/feeds" },
                credentialProvider.GetCredential().UserName,
                CancellationToken.None,
                new FileDataStore("Contacts2"));

            var parameters = new Google.GData.Client.OAuth2Parameters()
            {
                ClientId     = secrets.ClientId,
                ClientSecret = secrets.ClientSecret,
                RedirectUri  = redirectUri,
                Scope        = "https://www.google.com/m8/feeds",
                AccessToken  = credential.Token.AccessToken,
                RefreshToken = credential.Token.RefreshToken,
            };

            var contacts = new ContactsRequest(new RequestSettings("hagen", parameters));
            var q        = new FeedQuery("https://www.google.com/m8/feeds/contacts/default/full")
            {
                Query = "Grimme"
            };
            var feed = contacts.Get <Contact>(q);

            log.Info(feed.Entries.ListFormat());
        }
        public void PrintDateMinQueryResults(ContactsRequest cr)
        {
            Service service = new ContactsService("EventManagement");

            service.setUserCredentials("*****@*****.**", "Vandematram@123");
            var token = service.QueryClientLoginToken();

            service.SetAuthenticationToken(token);

            GAuthSubRequestFactory authFactory =
                new GAuthSubRequestFactory("cl", "EventManagement");

            authFactory.Token = (String)token;
            //  CalendarService service2 = new CalendarService(authFactory.ApplicationName);
            service.RequestFactory = authFactory;

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
            // query.StartDate = new DateTime(2008, 1, 1);
            Feed <Contact> feed = cr.Get <Contact>(query);

            foreach (Contact contact in feed.Entries)
            {
                Console.WriteLine(contact.Name.FullName);
                Console.WriteLine("Updated on: " + contact.Updated.ToString());
            }
        }
        public void ModelTestETagQuery()
        {
            Tracing.TraceMsg("Entering ModelTestETagQuery");

            RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);

            rs.AutoPaging = true;

            ContactsRequest cr = new ContactsRequest(rs);

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

            ContactsQuery q = new ContactsQuery(ContactsQuery.CreateContactsUri(null));

            q.Etag = ((ISupportsEtag)f.AtomFeed).Etag;

            try
            {
                f = cr.Get <Contact>(q);
                foreach (Contact c in f.Entries)
                {
                }
            }
            catch (GDataNotModifiedException g)
            {
                Assert.IsTrue(g != null);
            }
        }
Exemplo n.º 7
0
        public bool AreContactsModifiedToday()
        {
            bool areContactsModifiedToday = false;

            try
            {
                RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);
                // AutoPaging results in automatic paging in order to retrieve all contacts
                rs.AutoPaging = true;
                ContactsRequest cr = new ContactsRequest(rs);

                ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                //query.StartDate = new DateTime(2000, 1, 1);
                query.NumberToRetrieve = int.MaxValue;
                //query.OrderBy =

                query.StartDate = DateTime.Now.AddDays(-1);

                List <ConciseContact> ccList = new List <ConciseContact>();
                DateTime today = DateTime.Now.Date;

                Feed <Contact> feed = cr.Get <Contact>(query);

                if (feed.TotalResults > 0)
                {
                    areContactsModifiedToday = true;
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }

            return(areContactsModifiedToday);
        }
Exemplo n.º 8
0
        /// <summary>
        /// retrieve all profiles for the domain
        /// </summary>
        public void GetAllProfiles()
        {
            ContactsQuery query =
                new ContactsQuery("https://www.google.com/m8/feeds/profiles/domain/" + this.domain + "/full");

            Feed <Contact> f = cr.Get <Contact>(query);

            this.profiles = new List <Contact>(f.Entries);
        }
Exemplo n.º 9
0
        private Contact LoadGoogleContacts(AtomId id)
        {
            string message = "Error Loading Google Contacts. Cannot connect to Google.\r\nPlease ensure you are connected to the internet. If you are behind a proxy, change your proxy configuration!";

            Contact ret = null;

            try
            {
                GoogleContacts = new Collection <Contact>();

                ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                query.NumberToRetrieve = 256;
                query.StartIndex       = 0;

                //Group group = GetGoogleGroupByName(myContactsGroup);
                //if (group != null)
                //    query.Group = group.Id;

                //query.ShowDeleted = false;
                //query.OrderBy = "lastmodified";

                Feed <Contact> feed = ContactsRequest.Get <Contact>(query);

                while (feed != null)
                {
                    foreach (Contact a in feed.Entries)
                    {
                        GoogleContacts.Add(a);
                        if (id != null && id.Equals(a.ContactEntry.Id))
                        {
                            ret = a;
                        }
                    }
                    query.StartIndex += query.NumberToRetrieve;
                    feed              = ContactsRequest.Get <Contact>(feed, FeedRequestType.Next);
                }

                Logger.Log(UserName + " : " + GoogleContacts.Count + " contact(s)", EventType.Debug);
            }
            catch (System.Net.WebException ex)
            {
                Logger.Log(ex.Message, EventType.Error);

                //throw new GDataRequestException(message, ex);
            }
            catch (System.NullReferenceException ex)
            {
                Logger.Log(ex.Message, EventType.Error);

                //Logger.Log(message, EventType.Error);
                //throw new GDataRequestException(message, new System.Net.WebException("Error accessing feed", ex));
            }

            return(ret);
        }
Exemplo n.º 10
0
        private static void findGroup(string groupname)
        {
            GroupsQuery query = new GroupsQuery(GroupsQuery.CreateGroupsUri("default"));

            query.StartDate = new DateTime(2008, 1, 1);
            Feed <Group> feed = cr.Get <Group>(query);

            foreach (Group group in feed.Entries)
            {
                if (group.Title == groupname)
                {
                    HRefMedlem = group.Id;
                }
            }
        }
Exemplo n.º 11
0
        public List <Contact> ContactsChangedSince(DateTime d)
        {
            List <Contact>  result = new List <Contact>();
            ContactsRequest cr     = new ContactsRequest(rs);
            ContactsQuery   q      = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));

            q.StartDate = d;
            Feed <Contact> feed = cr.Get <Contact>(q);

            foreach (Contact c in feed.Entries)
            {
                result.Add(c);
            }
            return(result);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Send authorized queries to a Request-based library
        /// </summary>
        /// <param name="service"></param>
        static void RunContactsSample(OAuth2Parameters parameters)
        {
            try
            {
                RequestSettings settings = new RequestSettings("Google contacts tutorial", parameters);
                ContactsRequest cr       = new ContactsRequest(settings);

                //ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                //query.StartDate = new DateTime(2001, 1, 1);
                //Feed<Contact> feed = cr.Get<Contact>(query);
                //foreach (Contact contact in feed.Entries)
                //{
                //    Console.WriteLine(contact.Name.FullName);
                //    //Console.WriteLine("Updated on: " + contact.Updated.ToString());
                //}

                GroupsQuery query = new GroupsQuery(GroupsQuery.CreateGroupsUri("default"));
                query.StartDate = new DateTime(2001, 1, 1);
                Feed <Group> feed = cr.Get <Group>(query);

                foreach (Group group in feed.Entries)
                {
                    Console.WriteLine(group.Title);
                    Console.WriteLine("Updated on: " + group.Updated.ToString());
                }

                ////string applicationName = "Test-OAuth2";
                ////GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory("apps", applicationName, parameters);
                ////GroupsService service = new GroupsService(domain, applicationName);
                ////service.RequestFactory = requestFactory;
                ////GroupFeed feed = service.RetrieveAllGroups();
                ////foreach (GroupEntry group in feed.Entries)
                ////{
                ////    Console.WriteLine(group.GroupName);
                ////}

                //Feed<Contact> f = cr.GetContacts();
                //foreach (Contact c in f.Entries)
                //{
                //    Console.WriteLine(c.Name.FullName);
                //}
            }
            catch (Exception a)
            {
                Console.WriteLine("A Google Apps error occurred.");
                Console.WriteLine();
            }
        }
    public List <ContactDetail> GetContacts(GooglePlusAccessToken serStatus)
    {
        string           refreshToken    = serStatus.refresh_token;
        string           accessToken     = serStatus.access_token;
        string           scopes          = "https://www.google.com/m8/feeds/contacts/default/full/";
        OAuth2Parameters oAuthparameters = new OAuth2Parameters()
        {
            RedirectUri  = ConfigurationManager.AppSettings["google_redirect_url"].ToString(),
            Scope        = scopes,
            AccessToken  = accessToken,
            RefreshToken = refreshToken
        };


        RequestSettings settings = new RequestSettings("<var>" + ConfigurationManager.AppSettings["google_app_name"].ToString() + "</var>", oAuthparameters);
        ContactsRequest cr       = new ContactsRequest(settings);
        ContactsQuery   query    = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));

        query.NumberToRetrieve = 5000;
        Feed <Contact> feed = cr.Get <Contact>(query);

        StringBuilder        sb             = new StringBuilder();
        int                  i              = 1;
        List <ContactDetail> contactDetails = new List <ContactDetail>();

        foreach (Contact entry in feed.Entries)
        {
            ContactDetail contact = new
                                    ContactDetail
            {
                Name          = entry.Title.ToString(),
                EmailAddress1 = entry.Emails.Count >= 1 ? entry.Emails[0].Address : "",
                EmailAddress2 = entry.Emails.Count >= 2 ? entry.Emails[1].Address : "",
                Phone         = entry.Phonenumbers.Count >= 1 ? entry.Phonenumbers[0].Value : "",
                Address       = entry.PostalAddresses.Count >= 1 ? entry.PostalAddresses[0].FormattedAddress : ""
                                //Details = entry.Content.Content
            };

            contactDetails.Add(contact);
        }
        /*End*/
        return(contactDetails);
    }
Exemplo n.º 14
0
    public void GetContacts(GooglePlusAccessToken serStatus)
    {
        string google_client_id     = "yourclientId";
        string google_client_sceret = "yourclientSecret";
        /*Get Google Contacts From Access Token and Refresh Token*/
        string           refreshToken    = serStatus.refresh_token;
        string           accessToken     = serStatus.access_token;
        string           scopes          = "https://www.google.com/m8/feeds/contacts/default/full/";
        OAuth2Parameters oAuthparameters = new OAuth2Parameters()
        {
            ClientId     = google_client_id,
            ClientSecret = google_client_sceret,
            RedirectUri  = "http://www.yogihosting.com/TutorialCode/GoogleContactAPI/google-contact-api.aspx",
            Scope        = scopes,
            AccessToken  = accessToken,
            RefreshToken = refreshToken
        };


        RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters);
        ContactsRequest cr       = new ContactsRequest(settings);
        ContactsQuery   query    = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));

        query.NumberToRetrieve = 5000;
        Feed <Contact> feed = cr.Get <Contact>(query);

        StringBuilder sb = new StringBuilder();
        int           i  = 1;

        foreach (Contact entry in feed.Entries)
        {
            foreach (EMail email in entry.Emails)
            {
                sb.Append(i + "&nbsp;").Append(email.Address).Append("<br/>");
                i++;
            }
        }
        /*End*/
        dataDiv.InnerHtml = sb.ToString();
    }
        public Feed <Contact> GetContacts(GooglePlusAccessToken serStatus)
        {
            string           refreshToken    = serStatus.refresh_token;
            string           accessToken     = serStatus.access_token;
            string           scopes          = "https://www.google.com/m8/feeds/contacts/default/full/";
            OAuth2Parameters oAuthparameters = new OAuth2Parameters()
            {
                RedirectUri  = "http://localhost:2216/index.aspx",
                Scope        = scopes,
                AccessToken  = accessToken,
                RefreshToken = refreshToken
            };


            RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters);
            ContactsRequest cr       = new ContactsRequest(settings);
            ContactsQuery   query    = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));

            query.NumberToRetrieve = 5000;
            Feed <Contact> feed = cr.Get <Contact>(query);

            return(feed);
        }
Exemplo n.º 16
0
    public void GetContacts(GooglePlusAccessToken serStatus)
    {
        string google_client_id = "yourclientId";
        string google_client_sceret = "yourclientSecret";
        /*Get Google Contacts From Access Token and Refresh Token*/
        string refreshToken = serStatus.refresh_token;
        string accessToken = serStatus.access_token;
        string scopes = "https://www.google.com/m8/feeds/contacts/default/full/";
        OAuth2Parameters oAuthparameters = new OAuth2Parameters()
        {
            ClientId = google_client_id,
            ClientSecret = google_client_sceret,
            RedirectUri = "http://www.yogihosting.com/TutorialCode/GoogleContactAPI/google-contact-api.aspx",
            Scope = scopes,
            AccessToken = accessToken,
            RefreshToken = refreshToken
        };

        RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters);
        ContactsRequest cr = new ContactsRequest(settings);
        ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
        query.NumberToRetrieve = 5000;
        Feed<Contact> feed = cr.Get<Contact>(query);

        StringBuilder sb = new StringBuilder();
        int i = 1;
        foreach (Contact entry in feed.Entries)
        {
            foreach (EMail email in entry.Emails)
            {
                sb.Append(i + "&nbsp;").Append(email.Address).Append("<br/>");
                i++;
            }
        }
        /*End*/
        dataDiv.InnerHtml = sb.ToString();
    }
Exemplo n.º 17
0
        public void GetContacts(GooglePlusAccessToken serStatus)
        {
            /*Get Google Contacts From Access Token and Refresh Token*/
            string           refreshToken    = serStatus.refresh_token;
            string           accessToken     = serStatus.access_token;
            string           scopes          = "https://www.google.com/m8/feeds/contacts/default/full/";
            OAuth2Parameters oAuthparameters = new OAuth2Parameters()
            {
                Scope        = scopes,
                AccessToken  = accessToken,
                RefreshToken = refreshToken
            };

            RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters);
            ContactsRequest cr       = new ContactsRequest(settings);
            ContactsQuery   query    = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));

            query.NumberToRetrieve = 5000;
            Feed <Contact> feed = cr.Get <Contact>(query);

            StringBuilder sb = new StringBuilder();
            int           i  = 1;

            foreach (Contact entry in feed.Entries)
            {
                foreach (EMail email in entry.Emails)
                {
                    sb.Append("<span>" + i + ". </span>").Append(email.Address)
                    .Append("<br/>");
                    i++;
                }
            }
            /*End*/

            //dataDiv.InnerHtml = sb.ToString();
        }
        private void LoadAlbumBackground(object sender, DoWorkEventArgs e)
        {
            //albums = new List<PicasaEntry>();
              //albumIndex = -1;

              // Prepare for contact query
              string applicationName = "DigitalFrame";
              string username = settings.Username;
              string password = settings.Password;

              RequestSettings contactRequestSettings = new RequestSettings(applicationName, username, password);
              ContactsRequest contactRequest = new ContactsRequest(contactRequestSettings);

              // Request all groups of the auth user.
              //var allGroups = contactRequest.GetGroups();
              //foreach (var item in allGroups.Entries) {
              //  Debug.Write(item.Id + " - " + item.Title);
              //}

              // Get Family group entry.
              Group familyGroup;
              StringBuilder gs = new StringBuilder(GroupsQuery.CreateGroupsUri("default"));
              gs.Append("/");
              gs.Append("e"); // Family

              try {
            Feed<Group> gf = contactRequest.Get<Group>(new Uri(gs.ToString()));
            familyGroup = gf.Entries.First();
              }
              catch (AuthenticationException) {
            // We fail to get the group which means the login failed.
            return;
              }
              catch (GDataRequestException) {
            return;
              }

              // Get all contacts in Family group.
              ContactsQuery contactQuery = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
              contactQuery.Group = familyGroup.Id;
              Feed<Contact> friends = contactRequest.Get<Contact>(contactQuery);

              // Prepare for picasa query
              service = new PicasaService(applicationName);
              service.setUserCredentials(username, password);
              service.SetAuthenticationToken(service.QueryAuthenticationToken());

              allPhotos = new List<PicasaEntry>();

              foreach (var contact in friends.Entries) {
            try {
              string friendUsername = ParseUserName(contact);
              if (!string.IsNullOrEmpty(friendUsername)) {
            AlbumQuery query = new AlbumQuery();
            query.Uri = new Uri(PicasaQuery.CreatePicasaUri(friendUsername));

            PicasaFeed picasaFeed = service.Query(query);
            if (picasaFeed != null && picasaFeed.Entries.Count > 0) {
              foreach (PicasaEntry albumEntry in picasaFeed.Entries) {
                PhotoQuery photosQuery = new PhotoQuery(albumEntry.FeedUri);
                var photosFeed = (PicasaFeed)service.Query(photosQuery);
                foreach (PicasaEntry photoEntry in photosFeed.Entries) {
                  allPhotos.Add(photoEntry);
                }
              }
            }
              }
            }
            catch (LoggedException) {
              // Ignore the exception and continue.
            }
              }
        }
Exemplo n.º 19
0
        public void ModelTestETagQuery()
        {
            const int numberOfInserts = 5;
            Tracing.TraceMsg("Entering ModelTestETagQuery");

            RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);
            rs.AutoPaging = true;

            ContactsRequest cr = new ContactsRequest(rs);

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

            ContactsQuery q = new ContactsQuery(ContactsQuery.CreateContactsUri(null));

            q.Etag = ((ISupportsEtag)f.AtomFeed).Etag;

            try
            {
                f = cr.Get<Contact>(q);
                foreach (Contact c in f.Entries)
                {
                }
            }
            catch (GDataNotModifiedException g)
            {
                Assert.IsTrue(g != null);
            }
        }
    public static void Main(string [] args)
    {
        if (args.Length < 2) {
            Console.WriteLine ("usage: gcontact-yomigana.exe [username] [password] [--delete]");
            return;
        }
        if (args.Length > 2 && args [2] == "--delete") {
            Console.WriteLine ("Cleanup mode");
            cleanup = true;
        }

        ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;
        string username = args [0];
        string password = args [1];
        var rs = new RequestSettings (app_name, username, password);
        rs.AutoPaging = true;
        var cr = new ContactsRequest (rs);
        #if false
        var cq = new ContactsQuery (ContactsQuery.CreateContactsUri(null));
        cq.Group = "My Contacts";
        var results = cr.Get<Contact> (cq);
        #else
        var results = cr.GetContacts ();
        #endif

        if (cleanup) {
            foreach (var c in results.Entries) {
                // these silly null check is required since
                // setting value to nonexistent field causes AE.
                if (c.Name.FamilyNamePhonetics != null)
                    c.Name.FamilyNamePhonetics = null;
                if (c.Name.GivenNamePhonetics != null)
                    c.Name.GivenNamePhonetics = null;
        #if false // this does not work
                if (c.ContactEntry.Dirty)
                    Console.WriteLine ("{0} {1} being updated", c.Name.FamilyName, c.Name.GivenName);
        #else
                cr.Update<Contact> (c);
        #endif
            }
        #if false // Probably this does not work for extensions
            results.AtomFeed.Publish ();
        #endif
            return;
        }

        var l = new List<string> ();
        var dic = new Dictionary<string,string> ();
        foreach (var c in results.Entries)
            CollectName (c.Name, l);

        // query to mecab server
        string req = String.Join (" ", l.ToArray ());
        byte [] bytes = new WebClient ().DownloadData (server_url_param + req);
        string res = Encoding.UTF8.GetString (bytes);
        string [] rl = res.Split (' ');
        if (rl.Length != l.Count)
            throw new Exception ("Some error occured. I cannot handle address book entry that contains 'm(__)m'.");
        for (int i = 0; i < l.Count; i++) {
            var dst = rl [i].Replace ("m(__)m", " ");
            if (l [i] != dst)
                dic [l [i]] = dst;
        }
        foreach (var p in dic)
            Console.Write ("{0}=> {1}, ", p.Key, p.Value);

        // update
        foreach (var c in results.Entries)
            UpdateName (c, dic, cr);
        #if false // Probably this does not work for extension fields.
        results.AtomFeed.Publish ();
        #endif
    }
Exemplo n.º 21
0
        public void CreateNewContact()
        {
            string gmailUsername;
            string syncProfile;
            GoogleAPITests.LoadSettings(out gmailUsername, out syncProfile);

            ContactsRequest service;

            var scopes = new List<string>();
            //Contacts-Scope
            scopes.Add("https://www.google.com/m8/feeds");
            //Notes-Scope
            scopes.Add("https://docs.google.com/feeds/");
            //scopes.Add("https://docs.googleusercontent.com/");
            //scopes.Add("https://spreadsheets.google.com/feeds/");
            //Calendar-Scope
            //scopes.Add("https://www.googleapis.com/auth/calendar");
            scopes.Add(CalendarService.Scope.Calendar);

            UserCredential credential;
            byte[] jsonSecrets = Properties.Resources.client_secrets;

            using (var stream = new MemoryStream(jsonSecrets))
            {
                FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true);

                GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(stream);

                credential = GCSMOAuth2WebAuthorizationBroker.AuthorizeAsync(
                                clientSecrets.Secrets,
                                scopes.ToArray(),
                                gmailUsername,
                                CancellationToken.None,
                                fDS).
                                Result;

                OAuth2Parameters parameters = new OAuth2Parameters
                {
                    ClientId = clientSecrets.Secrets.ClientId,
                    ClientSecret = clientSecrets.Secrets.ClientSecret,

                    // Note: AccessToken is valid only for 60 minutes
                    AccessToken = credential.Token.AccessToken,
                    RefreshToken = credential.Token.RefreshToken
                };

                RequestSettings settings = new RequestSettings("GoContactSyncMod", parameters);

                service = new ContactsRequest(settings);
            }

            #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 == "*****@*****.**")
                {
                    service.Delete(entry);
                    Logger.Log("Deleted Google contact", EventType.Information);
                    //break;
                }
            }
            #endregion

            Contact newEntry = new Contact();
            newEntry.Title = "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);

            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);
        }
Exemplo n.º 22
0
        public List <ConciseContact> GetContactsWithBirthdaysToday()
        {
            RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);

            // AutoPaging results in automatic paging in order to retrieve all contacts
            rs.AutoPaging = true;
            ContactsRequest cr = new ContactsRequest(rs);

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));

            query.StartDate        = new DateTime(2000, 1, 1);
            query.NumberToRetrieve = int.MaxValue;
            //query.OrderBy =

            query.ModifiedSince = DateTime.Now.AddDays(-10000);

            List <ConciseContact> ccList = new List <ConciseContact>();
            DateTime today = DateTime.Now.Date;

            Feed <Contact> feed = cr.Get <Contact>(query);
            Contact        dbgC = null;

            foreach (Contact c in feed.Entries)
            {
                try
                {
                    dbgC = c;

                    if (string.IsNullOrEmpty(c.ContactEntry.Birthday))
                    {
                        continue;
                    }

                    DateTime birthday = DateTime.Parse(c.ContactEntry.Birthday);

                    if (birthday.Month != today.Month || birthday.Day != today.Day)
                    {
                        continue;
                    }

                    // Birthdays today found
                    ConciseContact cc = new ConciseContact();
                    cc.FirstName = c.Name.GivenName;
                    cc.LastName  = c.Name.FamilyName;

                    if (c.Organizations.Count > 0)
                    {
                        cc.Title = c.Organizations[0].Title;
                    }

                    //c.PrimaryPhonenumber
                    //c.PrimaryPhonenumber
                    //c.Phonenumbers[0]
                    if (c.Phonenumbers.Count > 0)
                    {
                        cc.PhoneNumber = c.Phonenumbers[0].Value;
                    }

                    ccList.Add(cc);

                    Console.WriteLine(c.Title);
                    Console.WriteLine("Name: " + c.Name.FullName);
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex, dbgC.Name.GivenName + " " + dbgC.Name.FamilyName);
                }
            }

            return(ccList);
        }
Exemplo n.º 23
0
 public List<Contact> ContactsChangedSince(DateTime d)
 {
     List<Contact> result = new List<Contact>();
     ContactsRequest cr = new ContactsRequest(rs);
     ContactsQuery q = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
     q.StartDate = d;
     Feed<Contact> feed = cr.Get<Contact>(q);
     foreach (Contact c in feed.Entries)
     {
         result.Add(c);
     }
     return result;
 }
Exemplo n.º 24
0
        public override List <EContact> GetContacts(string pCodeForAccessToken)
        {
            List <EContact> vListOfContacts = new List <EContact>();
            EContact        vEContact       = null;
            string          vParameters     = string.Empty;

            byte[] vByteArray          = null;
            Stream vPostStream         = null;
            string vResponseFromServer = string.Empty;

            try
            {
                // Get access token
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(LocalConstants.GetGoogleTokenUrl);      // https://accounts.google.com/o/oauth2/token
                webRequest.Method = "POST";

                vParameters = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
                                            pCodeForAccessToken, LocalConstants.GetClientID, LocalConstants.GetGoogleClientSecret, LocalConstants.GetRedirectUrl);

                vByteArray               = Encoding.UTF8.GetBytes(vParameters);
                webRequest.ContentType   = LocalConstants.GetRequestContentType;
                webRequest.ContentLength = vByteArray.Length;

                vPostStream = webRequest.GetRequestStream();
                vPostStream.Write(vByteArray, 0, vByteArray.Length);
                vPostStream.Close();

                WebResponse response = webRequest.GetResponse();
                vPostStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(vPostStream);
                vResponseFromServer = reader.ReadToEnd();

                dynamic vToken = JObject.Parse(vResponseFromServer);

                OAuth2Parameters oAuthparameters = new OAuth2Parameters()
                {
                    Scope        = LocalConstants.GetGoogleScopeContactsUrl,
                    AccessToken  = vToken.access_token,
                    RefreshToken = vToken.refresh_token
                };

                RequestSettings vSettings        = new RequestSettings(string.Format("<var>{0}</var>", LocalConstants.GetGoogleAuthApplication), oAuthparameters);
                ContactsRequest vContactsRequest = new ContactsRequest(vSettings);

                ContactsQuery vContactsQuery = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                vContactsQuery.NumberToRetrieve = 5000;

                Feed <Contact> feed = vContactsRequest.Get <Contact>(vContactsQuery);

                if (feed != null && feed.Entries != null)
                {
                    foreach (Contact contact in feed.Entries)
                    {
                        foreach (EMail email in contact.Emails)
                        {
                            vEContact          = new EContact();
                            vEContact.FullName = string.IsNullOrEmpty(contact.Title) ? email.Address : contact.Title;
                            vEContact.Email    = email.Address;
                            vListOfContacts.Add(vEContact);
                        }
                    }
                }
            }
            catch (Exception vException)
            {
                throw vException;
            }

            return(vListOfContacts);
        }
Exemplo n.º 25
0
        public void CreateNewContact()
        {
            string gmailUsername;
            string syncProfile;

            LoadSettings(out gmailUsername, out syncProfile);

            ContactsRequest service;

            var scopes = new List <string>();

            //Contacts-Scope
            scopes.Add("https://www.google.com/m8/feeds");
            //Calendar-Scope
            scopes.Add(CalendarService.Scope.Calendar);

            UserCredential credential;

            byte[] jsonSecrets = Properties.Resources.client_secrets;

            using (var stream = new MemoryStream(jsonSecrets))
            {
                FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true);

                GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(stream);

                credential = GCSMOAuth2WebAuthorizationBroker.AuthorizeAsync(
                    clientSecrets.Secrets,
                    scopes.ToArray(),
                    gmailUsername,
                    CancellationToken.None,
                    fDS).
                             Result;

                OAuth2Parameters parameters = new OAuth2Parameters
                {
                    ClientId     = clientSecrets.Secrets.ClientId,
                    ClientSecret = clientSecrets.Secrets.ClientSecret,

                    // Note: AccessToken is valid only for 60 minutes
                    AccessToken  = credential.Token.AccessToken,
                    RefreshToken = credential.Token.RefreshToken
                };

                RequestSettings settings = new RequestSettings("GoContactSyncMod", parameters);

                service = new ContactsRequest(settings);
            }

            #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 == "*****@*****.**")
                {
                    service.Delete(entry);
                    Logger.Log("Deleted Google contact", EventType.Information);
                    //break;
                }
            }
            #endregion

            Contact newEntry = new Contact();
            newEntry.Title = "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);

            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);
        }
Exemplo n.º 26
0
        public void InsertExtendedPropertyContactsTest()
        {
            Tracing.TraceMsg("Entering InsertExtendedPropertyContactsTest");

            DeleteAllContacts();

            RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);
            rs.AutoPaging = true;

            FeedQuery query = new FeedQuery();
            query.Uri = new Uri(CreateUri(this.resourcePath + "contactsextendedprop.xml"));

         

            ContactsRequest cr = new ContactsRequest(rs);

            Feed<Contact> f = cr.Get<Contact>(query);

            Contact newEntry = null;

            foreach (Contact c in f.Entries)
            {
                ExtendedProperty e = c.ExtendedProperties[0];
                Assert.IsTrue(e != null);
                newEntry = c;
            }

            f = cr.GetContacts();

            Contact createdEntry = cr.Insert<Contact>(f, newEntry);

            cr.Delete(createdEntry);



   
        }