// [Ignore] // - this test requires user interaction
        public async Task CreateCalendar()
        {
            var auth = new GoogleOAuth2("email profile https://www.googleapis.com/auth/calendar");

            _token = await auth.Authenticate(_token);

            Assert.IsNotNull(_token, "auth failed");

            using (var client = new HttpClient(MockInitialization.Handler, false))
            {
                client.BaseAddress = new Uri("https://www.googleapis.com/calendar/v3/");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token);

                using (dynamic proxy = new DynamicRestClient(client))
                {
                    dynamic calendar = new ExpandoObject();
                    calendar.summary = "unit_testing";

                    var list = await proxy.calendars.post(calendar);

                    Assert.IsNotNull(list);
                    Assert.AreEqual("unit_testing", list.summary);
                }
            }
        }
Example #2
0
        private async Task Authorize()
        {
            dynamic keys = await GetAppCredentials("Facebook");

            string clientId = keys.client_id;

            IDeviceOAuth2Stepwise auth = new DeviceOAuth(EndPointInfo.Facebook, "public_profile", clientId);
            var info = await auth.StartAuthorization();

            var msg = $"Navigate to {info.VerificationUri} \nEnter this code: {info.UserCode}";

            Notify.Text = msg;

            var token = await auth.WaitForUserConsent(info);

            var defaults = new DynamicRestClientDefaults()
            {
                AuthScheme = "Bearer",
                AuthToken  = token.AccessToken
            };

            dynamic client = new DynamicRestClient("https://graph.facebook.com/v2.3/me", defaults);

            dynamic v = await client.get(fields : "name");

            Notify.Text   = "";
            UserName.Text = v.name;
        }
        public void Cancel()
        {
            string key = CredentialStore.RetrieveObject("bing.key.json").Key;

            using (dynamic client = new DynamicRestClient("http://dev.virtualearth.net/REST/v1/"))
            using (var source = new CancellationTokenSource())
            {
                // run request on a different thread and do not await thread
                Task t = client.Locations.get(source.Token, postalCode: "55116", countryRegion: "US", key: key);

                // cancel on unit test thread
                source.Cancel();

                try
                {
                    // this will throw
                    Task.WaitAll(t);
                    Assert.Fail("Task was not cancelled");
                }
                catch (AggregateException e)
                {
                    Assert.IsTrue(e.InnerExceptions.OfType<TaskCanceledException>().Any());
                }
            }
        }
Example #4
0
        private async Task Authorize()
        {
            dynamic keys = await GetAppCredentials("Facebook");
            string clientId = keys.client_id;

            IDeviceOAuth2Stepwise auth = new DeviceOAuth(EndPointInfo.Facebook, "public_profile", clientId);
            var info = await auth.StartAuthorization();
            
            var msg = $"Navigate to {info.VerificationUri} \nEnter this code: {info.UserCode}";
            Notify.Text = msg;

            var token = await auth.WaitForUserConsent(info);

            var defaults = new DynamicRestClientDefaults()
            {
                AuthScheme = "Bearer",
                AuthToken = token.AccessToken
            };

            dynamic client = new DynamicRestClient("https://graph.facebook.com/v2.3/me", defaults);

            dynamic v = await client.get(fields: "name");
            Notify.Text = "";
            UserName.Text = v.name;
        }
Example #5
0
        public void Cancel()
        {
            string key = CredentialStore.RetrieveObject("bing.key.json").Key;

            using (dynamic client = new DynamicRestClient("http://dev.virtualearth.net/REST/v1/"))
                using (var source = new CancellationTokenSource())
                {
                    // run request on a different thread and do not await thread
                    Task t = client.Locations.get(source.Token, postalCode: "55116", countryRegion: "US", key: key);

                    // cancel on unit test thread
                    source.Cancel();

                    try
                    {
                        // this will throw
                        Task.WaitAll(t);
                        Assert.Fail("Task was not cancelled");
                    }
                    catch (AggregateException e)
                    {
                        Assert.IsTrue(e.InnerExceptions.OfType <TaskCanceledException>().Any());
                    }
                }
        }
Example #6
0
        public void CancelPassesToConfigurationCallback()
        {
            using (var source = new CancellationTokenSource())
            {
                // the cancellation token here is the one we passed in below
                using (dynamic client = new DynamicRestClient("https://www.googleapis.com/oauth2/v1/userinfo", null,
                                                              async(request, cancelToken) =>
                {
                    Assert.AreEqual(source.Token, cancelToken);

                    var oauth = new GoogleOAuth2("email profile");
                    var authToken = await oauth.Authenticate("", cancelToken);
                    request.Headers.Authorization = new AuthenticationHeaderValue("OAuth", authToken);
                }))
                {
                    // run request on a different thread and do not await thread
                    Task t = client.oauth2.v1.userinfo.get(source.Token);

                    // cancel on unit test thread
                    source.Cancel();

                    try
                    {
                        // this will throw
                        Task.WaitAll(t);
                        Assert.Fail("Task was not cancelled");
                    }
                    catch (AggregateException e)
                    {
                        Assert.IsTrue(e.InnerExceptions.OfType <TaskCanceledException>().Any());
                    }
                }
            }
        }
Example #7
0
        public async Task MultiPartUploadObject()
        {
            var auth = new GoogleOAuth2("email profile https://www.googleapis.com/auth/devstorage.read_write");

            _token = await auth.Authenticate(_token);

            Assert.IsNotNull(_token, "auth failed");

            var defaults = new DynamicRestClientDefaults()
            {
                AuthScheme = "OAuth",
                AuthToken  = _token
            };

            dynamic google = new DynamicRestClient("https://www.googleapis.com/", defaults);

            using (var stream = new StreamInfo(File.OpenRead(@"D:\temp\test2.png"), "image/png"))
            {
                dynamic metaData = new ExpandoObject();
                metaData.name = "test2";
                dynamic result = await google.upload.storage.v1.b.unit_tests.o.post(metaData, stream, uploadType : new PostUrlParam("multipart"));

                Assert.IsNotNull(result);
            }
        }
Example #8
0
        private static async Task EnumerateObjects(string project)
        {
            var auth  = new GoogleOAuth2("https://www.googleapis.com/auth/devstorage.read_write");
            var token = await auth.Authenticate("");

            var defaults = new DynamicRestClientDefaults()
            {
                AuthScheme = "OAuth",
                AuthToken  = token
            };

            dynamic google         = new DynamicRestClient("https://www.googleapis.com/", defaults);
            dynamic bucketEndPoint = google.storage.v1.b;
            dynamic buckets        = await bucketEndPoint.get(project : project);

            foreach (var bucket in buckets.items)
            {
                Console.WriteLine("bucket {0}: {1}", bucket.id, bucket.name);

                dynamic contents = await bucketEndPoint(bucket.id).o.get();

                foreach (var item in contents.items)
                {
                    Console.WriteLine("\tid: {0}", item.id);
                    Console.WriteLine("\tname: {0}", item.name);
                    Console.WriteLine("\tcontent type: {0}", item.contentType);
                    Console.WriteLine("\t-----");
                }
            }
        }
Example #9
0
        private async Task <TokenInfo> RefreshAccessToken(TokenInfo token, CancellationToken cancelToken)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token");
            }
            if (!token.CanRefresh)
            {
                throw new InvalidOperationException("Token is not refreshable");
            }

            using (dynamic tokenEndPoint = new DynamicRestClient(_endPoint.AuthUri))
            {
                var response = await tokenEndPoint(_endPoint.TokenPath).post(cancelToken, client_id: _clientId, client_secret: _clientSecret, refresh_token: token.RefreshToken, grant_type: "refresh_token") as IDictionary <string, object>;

                return(new TokenInfo()
                {
                    Site = _endPoint.Name,
                    RefreshToken = token.RefreshToken,
                    AccessToken = (string)response["access_token"],
                    Expiry = DateTime.UtcNow + TimeSpan.FromSeconds((long)response["expires_in"]),
                    Scheme = _endPoint.Scheme
                });
            }
        }
Example #10
0
        private static async Task EnumerateObjects(string project)
        {
            var auth = new GoogleOAuth2("https://www.googleapis.com/auth/devstorage.read_write");
            var token = await auth.Authenticate("");

            var defaults = new DynamicRestClientDefaults()
            {
                AuthScheme = "OAuth",
                AuthToken = token
            };

            dynamic google = new DynamicRestClient("https://www.googleapis.com/", defaults);
            dynamic bucketEndPoint = google.storage.v1.b;
            dynamic buckets = await bucketEndPoint.get(project: project);

            foreach (var bucket in buckets.items)
            {
                Console.WriteLine("bucket {0}: {1}", bucket.id, bucket.name);

                dynamic contents = await bucketEndPoint(bucket.id).o.get();

                foreach (var item in contents.items)
                {
                    Console.WriteLine("\tid: {0}", item.id);
                    Console.WriteLine("\tname: {0}", item.name);
                    Console.WriteLine("\tcontent type: {0}", item.contentType);
                    Console.WriteLine("\t-----");
                }
            }
        }
Example #11
0
        public async Task EscapeParameterName()
        {
            using (var client = new HttpClient(MockInitialization.Handler, false))
            {
                client.BaseAddress = new Uri("http://congress.api.sunlightfoundation.com");
                string key = CredentialStore.RetrieveObject("sunlight.key.json").Key;
                client.DefaultRequestHeaders.Add("X-APIKEY", key);

                using (dynamic proxy = new DynamicRestClient(client))
                {
                    // this is the mechanism by which parameter names that are not valid c# property names can be used
                    var parameters = new Dictionary <string, object>()
                    {
                        { "chamber", "senate" },
                        { "history.house_passage_result", "pass" }
                    };

                    dynamic result = await proxy.bills.get(paramList : parameters);

                    Assert.IsNotNull(result);
                    Assert.IsNotNull(result.results);
                    Assert.IsTrue(result.results.Count > 0);

                    foreach (dynamic bill in result.results)
                    {
                        Assert.AreEqual("senate", bill.chamber);
                        Assert.AreEqual("pass", bill.history.house_passage_result);
                    }
                }
            }
        }
        public void CancelPassesToConfigurationCallback()
        {
            using (var source = new CancellationTokenSource())
            {
                // the cancellation token here is the one we passed in below
                using (dynamic client = new DynamicRestClient("https://www.googleapis.com/oauth2/v1/userinfo", null,
                    async (request, cancelToken) =>
                    {
                        Assert.AreEqual(source.Token, cancelToken);

                        var oauth = new GoogleOAuth2("email profile");
                        var authToken = await oauth.Authenticate("", cancelToken);
                        request.Headers.Authorization = new AuthenticationHeaderValue("OAuth", authToken);
                    }))
                {
                    // run request on a different thread and do not await thread
                    Task t = client.oauth2.v1.userinfo.get(source.Token);

                    // cancel on unit test thread
                    source.Cancel();

                    try
                    {
                        // this will throw
                        Task.WaitAll(t);
                        Assert.Fail("Task was not cancelled");
                    }
                    catch (AggregateException e)
                    {
                        Assert.IsTrue(e.InnerExceptions.OfType<TaskCanceledException>().Any());
                    }
                }
            }
        }
        //  [Ignore] // - this test requires user interaction
        public async Task DeleteCalendar()
        {
            var auth = new GoogleOAuth2("email profile https://www.googleapis.com/auth/calendar");

            _token = await auth.Authenticate(_token);

            Assert.IsNotNull(_token, "auth failed");

            using (var client = new HttpClient(MockInitialization.Handler, false))
            {
                client.BaseAddress = new Uri("https://www.googleapis.com/calendar/v3/");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token);

                using (dynamic proxy = new DynamicRestClient(client))
                {
                    var list = await proxy.users.me.calendarList.get();

                    Assert.IsNotNull(list);

                    string id = ((IEnumerable <dynamic>)(list.items)).Where(cal => cal.summary == "unit_testing").Select(cal => cal.id).FirstOrDefault();
                    Assert.IsFalse(string.IsNullOrEmpty(id), "calendar does not exist so we can't delete it");

                    var result = await proxy.calendars(id).delete();

                    Assert.IsNull(result);

                    //var list2 = await proxy.users.me.calendarList.get();
                    //Assert.IsNotNull(list2);
                    //var id2 = ((IEnumerable<dynamic>)(list2.items)).Where(cal => cal.summary == "unit_testing").Select(cal => (string)cal.id).FirstOrDefault();

                    //Assert.IsTrue(string.IsNullOrEmpty(id2), "calendar seems to have not been deleted");
                }
            }
        }
        public async Task DeserializeToGenericType()
        {
            dynamic google = new DynamicRestClient("https://www.googleapis.com/");
            dynamic bucket = google.storage.v1.b("uspto-pair");

            Bucket metaData = await bucket.get<Bucket>();
            Assert.IsNotNull(metaData);
            Assert.AreEqual(metaData.name, "uspto-pair");
        }
        private static async Task<dynamic> RefreshAccessToken(dynamic access, CancellationToken cancelToken)
        {
            dynamic key = CredentialStore.RetrieveObject("google.key.json").installed;

            dynamic google = new DynamicRestClient("https://accounts.google.com/o/oauth2/");
            var response = await google.token.post(cancelToken, client_id: key.client_id, client_secret: key.client_secret, refresh_token: access.refresh_token, grant_type: "refresh_token");

            response.refresh_token = access.refresh_token; // the new access token doesn't have a new refresh token so move our current one here for long term storage
            return response;
        }
Example #16
0
        private static async Task <dynamic> RefreshAccessToken(dynamic access, CancellationToken cancelToken)
        {
            dynamic key = CredentialStore.RetrieveObject("google.key.json").installed;

            dynamic google   = new DynamicRestClient("https://accounts.google.com/o/oauth2/");
            var     response = await google.token.post(cancelToken, client_id : key.client_id, client_secret : key.client_secret, refresh_token : access.refresh_token, grant_type : "refresh_token");

            response.refresh_token = access.refresh_token; // the new access token doesn't have a new refresh token so move our current one here for long term storage
            return(response);
        }
        public async Task DeserializeToGenericType()
        {
            dynamic google = new DynamicRestClient("https://www.googleapis.com/");
            dynamic bucket = google.storage.v1.b("uspto-pair");

            Bucket metaData = await bucket.get <Bucket>();

            Assert.IsNotNull(metaData);
            Assert.AreEqual(metaData.name, "uspto-pair");
        }
        public async Task DownloadJsonFile()
        {
            using (dynamic client = new DynamicRestClient("https://storage.googleapis.com/pictureframe/settings.json"))
            {
                var result = await client.get();

                Assert.IsNotNull(result);
                Assert.AreEqual(10000, result.settingCheckInterval);
            }
        }
        public async Task DeserializeToString()
        {
            using (dynamic google = new DynamicRestClient("https://www.google.com/", MockInitialization.Handler))
            {
                string content = await google.get(typeof(string));

                Assert.IsFalse(string.IsNullOrEmpty(content));
                Assert.IsTrue(content.StartsWith("<!doctype html>"));
            }
        }
        public async Task DeserializeToString()
        {
            using (dynamic google = new DynamicRestClient("https://www.google.com/", MockInitialization.Handler))
            {
                string content = await google.get(typeof(string));

                Assert.IsFalse(string.IsNullOrEmpty(content));
                Assert.IsTrue(content.StartsWith("<!doctype html>"));
            }
        }
        public async Task EscapeUriSegmentsUsingClient()
        {
            using (dynamic client = new DynamicRestClient("http://openstates.org/api/v1/", MockInitialization.Handler))
            {
                string key    = CredentialStore.RetrieveObject("sunlight.key.json").Key;
                var    result = await client.bills.mn("2013s1")("SF 1").get(apikey: key);

                Assert.IsNotNull(result);
                Assert.IsTrue(result.id == "MNB00017167");
            }
        }
        public async Task ExplicitGetInvokeUsingClient()
        {
            using (dynamic client = new DynamicRestClient("http://openstates.org/api/v1/", MockInitialization.Handler))
            {
                string  key    = CredentialStore.RetrieveObject("sunlight.key.json").Key;
                dynamic result = await client.metadata.mn.get(apikey : key);

                Assert.IsNotNull(result);
                Assert.AreEqual("Minnesota", result.name);
            }
        }
        public async Task ExplicitGetInvokeUsingClient()
        {
            using (dynamic client = new DynamicRestClient("http://openstates.org/api/v1/", MockInitialization.Handler))
            {
                string key = CredentialStore.RetrieveObject("sunlight.key.json").Key;
                dynamic result = await client.metadata.mn.get(apikey: key);

                Assert.IsNotNull(result);
                Assert.AreEqual("Minnesota", result.name);
            }
        }
        public async Task EscapeUriSegmentsUsingClient()
        {
            using (dynamic client = new DynamicRestClient("http://openstates.org/api/v1/", MockInitialization.Handler))
            {
                string key = CredentialStore.RetrieveObject("sunlight.key.json").Key;
                var result = await client.bills.mn("2013s1")("SF 1").get(apikey: key);

                Assert.IsNotNull(result);
                Assert.IsTrue(result.id == "MNB00017167");
            }
        }
        public async Task BasicCallback()
        {
            dynamic client = new DynamicRestClient("http://dev.virtualearth.net/REST/v1/",
                                                   configureRequest: (request, token) =>
            {
                Debug.WriteLine(request.RequestUri);
                return(Task.CompletedTask);
            });

            dynamic result = await client.Locations.get(postalCode : "55116", countryRegion : "US", key : "key");
        }
Example #26
0
        /// <summary>
        /// This authenticates against user and requires user interaction to authorize the unit test to access apis
        /// This will do the auth, put the auth code on the clipboard and then open a browser with the app auth permission page
        /// The auth code needs to be sent back to google
        ///
        /// This should only need to be done once because the access token will be stored and refreshed for future test runs
        /// </summary>
        /// <returns></returns>
        private async Task <dynamic> GetNewAccessToken(CancellationToken cancelToken)
        {
            dynamic key = CredentialStore.RetrieveObject("google.key.json").installed;

            dynamic google   = new DynamicRestClient("https://accounts.google.com/o/oauth2/");
            var     response = await google.device.code.post(cancelToken, client_id : key.client_id, scope : _scope);

            Debug.WriteLine((string)response.user_code);

            Console.WriteLine("Requested permissions are:");
            Console.WriteLine(_scope);
            Console.WriteLine("");
            Console.WriteLine("Navigate to {0} in a web browser", response.verification_url);
            Console.WriteLine("Enter this code to authorize access: " + response.user_code);
            Console.WriteLine("");

            // use clip.exe to put the user code on the clipboard
            Process p = new Process();

            p.StartInfo.FileName  = "cmd.exe";
            p.StartInfo.Arguments = string.Format("/c echo {0} | clip", response.user_code);
            p.Start();

            // this requires user permission - open a broswer - enter the user_code which is now in the clipboard
            Process.Start((string)response.verification_url);

            long expiration = response.expires_in;
            long interval   = response.interval;
            long time       = interval;

            // we are using the device flow so enter the code in the browser
            // here poll google for success
            while (time < expiration)
            {
                Thread.Sleep((int)interval * 1000);
                dynamic tokenResonse = await google.token.post(cancelToken, client_id : key.client_id, client_secret : key.client_secret, code : response.device_code, grant_type : "http://oauth.net/grant_type/device/1.0");

                try
                {
                    if (tokenResonse.access_token != null)
                    {
                        return(tokenResonse);
                    }
                }
                catch (RuntimeBinderException)
                {
                }

                time += interval;
            }

            throw new OperationCanceledException("Authorization from user timed out");
        }
        public async Task GetNonJsonContent()
        {
            using (dynamic google = new DynamicRestClient("https://www.googleapis.com/", MockInitialization.Handler))
            {
                dynamic zip = google.storage.v1.b("uspto-pair").o("applications%2F05900002.zip");

                byte[] zipBytes = await zip.get(typeof(byte[]), generation : 1370956749027000, alt : "media");

                Assert.IsNotNull(zipBytes);
                Assert.IsTrue(zipBytes.Any());
            }
        }
        public async Task GetNonJsonContent()
        {
            using (dynamic google = new DynamicRestClient("https://www.googleapis.com/", MockInitialization.Handler))
            {
                dynamic zip = google.storage.v1.b("uspto-pair").o("applications%2F05900002.zip");

                byte[] zipBytes = await zip.get(typeof(byte[]), generation: 1370956749027000, alt: "media");

                Assert.IsNotNull(zipBytes);
                Assert.IsTrue(zipBytes.Any());
            }
        }
        public async Task ReservedWordNameEscapeWithCSharpSyntax()
        {
            using (dynamic client = new DynamicRestClient("http://openstates.org/api/v1/", MockInitialization.Handler))
            {
                string key = CredentialStore.RetrieveObject("sunlight.key.json").Key;

                //escape the reserved word "long" with an @ symbol
                var result = await client.legislators.geo.get(apikey : key, lat : 44.926868, @long : -93.214049);

                Assert.IsNotNull(result);
                Assert.IsTrue(result.Count > 0);
            }
        }
        public async Task DeserializeToByteArray()
        {
            using (dynamic google = new DynamicRestClient("https://www.google.com/", MockInitialization.Handler))
            {
                byte[] content = await google.get(typeof(byte[]));

                Assert.IsNotNull(content);
                Assert.IsTrue(content.Length > 0);

                var s = Encoding.UTF8.GetString(content);
                Assert.IsFalse(string.IsNullOrEmpty(s));
                Assert.IsTrue(s.StartsWith("<!doctype html>"));
            }
        }
        public async Task GetPublicBucket()
        {
            using (dynamic google = new DynamicRestClient("https://www.googleapis.com/", MockInitialization.Handler))
            {
                dynamic bucket = google.storage.v1.b("uspto-pair");

                dynamic metaData = await bucket.get();
                Assert.IsNotNull(metaData);

                dynamic objects = await bucket.o.get();
                Assert.IsNotNull(objects);
                Assert.IsTrue(objects.items.Count > 0);
            }
        }
 public async Task UserSuppliedAcceptHeaderOverridesDefaultAcceptHeaders()
 {
     var defaults = new DynamicRestClientDefaults();
     defaults.DefaultHeaders.Add("AccEpt", "application/json");
     
     using (dynamic google = new DynamicRestClient("https://www.googleapis.com/", MockInitialization.Handler, false, defaults))
     using (HttpResponseMessage response = await google.storage.v1.b("uspto-pair").get(typeof(HttpResponseMessage)))
     {
         response.EnsureSuccessStatusCode();
         Assert.IsNotNull(response.RequestMessage.Headers.Accept);
         Assert.AreEqual(1, response.RequestMessage.Headers.Accept.Count);
         Assert.AreEqual("application/json", response.RequestMessage.Headers.Accept.First().MediaType);
     }
 }
 public async Task ReturnResponseStream()
 {
     using (dynamic google = new DynamicRestClient("https://www.google.com/", MockInitialization.Handler))
         using (Stream responseStream = await google.get(typeof(Stream)))
         {
             Assert.IsNotNull(responseStream);
             using (var reader = new StreamReader(responseStream))
             {
                 var content = reader.ReadToEnd();
                 Assert.IsNotNull(content);
                 Assert.IsTrue(content.StartsWith("<!doctype html>"));
             }
         }
 }
        public async Task DeserializeToByteArray()
        {
            using (dynamic google = new DynamicRestClient("https://www.google.com/", MockInitialization.Handler))
            {
                byte[] content = await google.get(typeof(byte[]));

                Assert.IsNotNull(content);
                Assert.IsTrue(content.Length > 0);

                var s = Encoding.UTF8.GetString(content);
                Assert.IsFalse(string.IsNullOrEmpty(s));
                Assert.IsTrue(s.StartsWith("<!doctype html>"));
            }
        }
Example #35
0
        public async Task GetPublicBucket()
        {
            dynamic google = new DynamicRestClient("https://www.googleapis.com/");
            dynamic bucket = google.storage.v1.b("uspto-pair");

            dynamic metaData = await bucket.get();

            Assert.IsNotNull(metaData);

            dynamic objects = await bucket.o.get();

            Assert.IsNotNull(objects);
            Assert.IsTrue(objects.items.Count > 0);
        }
Example #36
0
        public async Task UploadPhoto()
        {
            var key      = CredentialStore.RetrieveObject("flickr.key.json");
            var defaults = new DynamicRestClientDefaults();

            defaults.DefaultParameters.Add("format", "json");
            defaults.DefaultParameters.Add("api_key", key.Key);
            defaults.DefaultParameters.Add("nojsoncallback", "1");

            dynamic client = new DynamicRestClient("https://up.flickr.com/services/", defaults);

            dynamic result = await client.upload.post(photo : File.OpenRead(@"D:\temp\test.png"));

            Assert.IsNotNull(result);
        }
Example #37
0
        public async Task FindUserByName()
        {
            var key = CredentialStore.RetrieveObject("flickr.key.json");
            var defaults = new DynamicRestClientDefaults();
            defaults.DefaultParameters.Add("format", "json");
            defaults.DefaultParameters.Add("api_key", key.Key);
            defaults.DefaultParameters.Add("nojsoncallback", "1");

            using (dynamic client = new DynamicRestClient("https://api.flickr.com/services/rest/", MockInitialization.Handler, false, defaults))
            {
                dynamic result = await client.get(method: "flickr.people.findByUsername", username: "******");
                Assert.IsNotNull(result);
                Assert.AreEqual("9039518@N03", result.user.id);
            }
        }
Example #38
0
        public async Task UploadPhoto()
        {
            var key = CredentialStore.RetrieveObject("flickr.key.json");
            var defaults = new DynamicRestClientDefaults();
            defaults.DefaultParameters.Add("format", "json");
            defaults.DefaultParameters.Add("api_key", key.Key);
            defaults.DefaultParameters.Add("nojsoncallback", "1");

            using (dynamic client = new DynamicRestClient("https://up.flickr.com/services/", MockInitialization.Handler, false, defaults))
            {
                dynamic result = await client.upload.post(photo: File.OpenRead(@"D:\temp\test.png"));

                Assert.IsNotNull(result);
            }
        }
Example #39
0
        public async Task UserSuppliedAcceptHeaderOverridesDefaultAcceptHeaders()
        {
            var defaults = new DynamicRestClientDefaults();

            defaults.DefaultHeaders.Add("AccEpt", "application/json");

            using (dynamic google = new DynamicRestClient("https://www.googleapis.com/", MockInitialization.Handler, false, defaults))
                using (HttpResponseMessage response = await google.storage.v1.b("uspto-pair").get(typeof(HttpResponseMessage)))
                {
                    response.EnsureSuccessStatusCode();
                    Assert.IsNotNull(response.RequestMessage.Headers.Accept);
                    Assert.AreEqual(1, response.RequestMessage.Headers.Accept.Count);
                    Assert.AreEqual("application/json", response.RequestMessage.Headers.Accept.First().MediaType);
                }
        }
        public async Task DefaultAuthHeader()
        {
            var defaults = new DynamicRestClientDefaults();

            string key = CredentialStore.RetrieveObject("sunlight.key.json").Key;
            defaults.DefaultHeaders.Add("X-APIKEY", key);

            using (dynamic client = new DynamicRestClient("http://openstates.org/api/v1/", defaults))
            {
                var result = await client.bills.mn("2013s1")("SF 1").get();

                Assert.IsNotNull(result);
                Assert.IsTrue(result.id == "MNB00017167");
            }
        }
        public async Task DeserializeToStaticType()
        {
            using (dynamic google = new DynamicRestClient("https://www.googleapis.com/", MockInitialization.Handler))
            {
                dynamic bucketEndPoint = google.storage.v1.b("uspto-pair");

                dynamic dynamicBucket = await bucketEndPoint.get();
                Assert.IsNotNull(dynamicBucket);
                Assert.AreEqual(dynamicBucket.name, "uspto-pair");

                Bucket staticBucket = await bucketEndPoint.get(typeof(Bucket));
                Assert.IsNotNull(staticBucket);
                Assert.AreEqual(staticBucket.name, "uspto-pair");
            }
        }
Example #42
0
        private async Task <TokenInfo> PollForUserAuth(AuthInfo authInfo, CancellationToken cancelToken)
        {
            if (authInfo == null)
            {
                throw new ArgumentNullException("authInfo");
            }

            using (dynamic authEndPoint = new DynamicRestClient(_endPoint.AuthUri))
            {
                // here poll for success
                while (DateTimeOffset.UtcNow < authInfo.Expiration)
                {
                    await Task.Delay(authInfo.PollInterval * 1000);

                    // check the oauth token endpoint ot see if access has been authorized yet
                    using (HttpResponseMessage message = await authEndPoint(_endPoint.TokenPath).post(typeof(HttpResponseMessage), cancelToken, client_id: _clientId, client_secret: _clientSecret, code: authInfo.DeviceCode, type: "device_token", grant_type: "http://oauth.net/grant_type/device/1.0"))
                    {
                        // not all endpoints return the same status code while waiting for user authorization
                        if (message.StatusCode != _endPoint.PendingStatusCode)
                        {
                            message.EnsureSuccessStatusCode();
                        }

                        var tokenResponse = await message.Deserialize <dynamic>(new JsonSerializerSettings()) as IDictionary <string, object>;

                        if (tokenResponse.ContainsKey("access_token"))
                        {
                            return(new TokenInfo()
                            {
                                Site = _endPoint.Name,
                                AccessToken = (string)tokenResponse["access_token"],
                                RefreshToken = tokenResponse.ContainsKey("refresh_token") ? (string)tokenResponse["refresh_token"] : null,
                                Expiry = tokenResponse.ContainsKey("expires_in") ? DateTime.UtcNow + TimeSpan.FromSeconds((long)tokenResponse["expires_in"]) : DateTime.MaxValue,
                                Scheme = _endPoint.Scheme
                            });
                        }

                        tokenResponse.ThrowIfError();

                        // if we made it this far it inidcates that the rest endpoint is still in a pending state, so go around again
                    }

                    OnWaitingForConfirmation((int)(authInfo.Expiration - DateTimeOffset.UtcNow).TotalSeconds);
                }

                throw new TimeoutException("Access timeout expired");
            }
        }
        public async Task GetMethodSegmentWithArgs()
        {
            using (var client = new HttpClient(MockInitialization.Handler, false))
            {
                client.BaseAddress = new Uri("http://openstates.org/api/v1/");
                string key = CredentialStore.RetrieveObject("sunlight.key.json").Key;
                client.DefaultRequestHeaders.Add("X-APIKEY", key);

                using (dynamic proxy = new DynamicRestClient(client))
                {
                    var result = await proxy.bills.mn("2013s1")("SF 1").get();
                    Assert.IsNotNull(result);
                    Assert.AreEqual("MNB00017167", result.id);
                }
            }
        }
        public async Task ExplicitGetInvoke()
        {
            using (var client = new HttpClient(MockInitialization.Handler, false))
            {
                client.BaseAddress = new Uri("http://openstates.org/api/v1/");
                string key = CredentialStore.RetrieveObject("sunlight.key.json").Key;
                client.DefaultRequestHeaders.Add("X-APIKEY", key);

                using (dynamic proxy = new DynamicRestClient(client))
                {
                    dynamic result = await proxy.metadata.mn.get();
                    Assert.IsNotNull(result);
                    Assert.AreEqual("Minnesota", result.name);
                }
            }
        }
        public async Task DefaultAuthHeader()
        {
            var defaults = new DynamicRestClientDefaults();

            string key = CredentialStore.RetrieveObject("sunlight.key.json").Key;

            defaults.DefaultHeaders.Add("X-APIKEY", key);

            using (dynamic client = new DynamicRestClient("http://openstates.org/api/v1/", defaults))
            {
                var result = await client.bills.mn("2013s1")("SF 1").get();

                Assert.IsNotNull(result);
                Assert.IsTrue(result.id == "MNB00017167");
            }
        }
Example #46
0
        public async Task FindUserByName()
        {
            var key      = CredentialStore.RetrieveObject("flickr.key.json");
            var defaults = new DynamicRestClientDefaults();

            defaults.DefaultParameters.Add("format", "json");
            defaults.DefaultParameters.Add("api_key", key.Key);
            defaults.DefaultParameters.Add("nojsoncallback", "1");

            dynamic client = new DynamicRestClient("https://api.flickr.com/services/rest/", defaults);

            dynamic result = await client.get(method : "flickr.people.findByUsername", username : "******");

            Assert.IsNotNull(result);
            Assert.AreEqual("9039518@N03", (string)result.user.id);
        }
        public async Task GetMethod2PathAsProperty2Params()
        {
            dynamic client = new DynamicRestClient("http://openstates.org/api/v1/");

            string key = CredentialStore.RetrieveObject("sunlight.key.json").Key;

            var parameters = new Dictionary <string, object>()
            {
                { "lat", 44.926868 },
                { "long", -93.214049 } // since long is a keyword we need to pass arguments in a Dictionary
            };
            var result = await client.legislators.geo.get(paramList : parameters, apikey : key);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Count > 0);
        }
        public async Task GetMethod2PathAsProperty2Params()
        {
            using (dynamic client = new DynamicRestClient("http://openstates.org/api/v1/", MockInitialization.Handler))
            {
                string key = CredentialStore.RetrieveObject("sunlight.key.json").Key;

                var parameters = new Dictionary<string, object>()
            {
                { "lat", 44.926868 },
                { "long", -93.214049 } // since long is a keyword, pass arguments in a Dictionary
            };
                var result = await client.legislators.geo.get(paramList: parameters, apikey: key);
                Assert.IsNotNull(result);
                Assert.IsTrue(result.Count > 0);
            }
        }
Example #49
0
        public async Task AuthenticateAndGetUserName()
        {
            dynamic google = new DynamicRestClient("https://www.googleapis.com/", null, async(request, cancelToken) =>
            {
                // this demonstrates how t use the configuration callback to handle authentication
                var auth  = new GoogleOAuth2("email profile");
                var token = await auth.Authenticate("", cancelToken);
                Assert.IsNotNull(token, "auth failed");

                request.Headers.Authorization = new AuthenticationHeaderValue("OAuth", token);
            });

            var profile = await google.oauth2.v1.userinfo.get();

            Assert.IsNotNull(profile);
            Assert.AreEqual("Kackman", (string)profile.family_name);
        }
        public async Task CoordinateFromPostalCode()
        {
            using (dynamic client = new DynamicRestClient("http://dev.virtualearth.net/REST/v1/", MockInitialization.Handler))
            {
                string key = CredentialStore.RetrieveObject("bing.key.json").Key;

                dynamic result = await client.Locations.get(postalCode: "55116", countryRegion: "US", key: key);

                Assert.AreEqual(200, result.statusCode);
                Assert.IsTrue(result.resourceSets.Count > 0);
                Assert.IsTrue(result.resourceSets[0].resources.Count > 0);

                var r = result.resourceSets[0].resources[0].point.coordinates;
                Assert.IsTrue((44.9108238220215).AboutEqual((double)r[0]));
                Assert.IsTrue((-93.1702041625977).AboutEqual((double)r[1]));
            }
        }
        public async Task GetPublicBucket()
        {
            var responses = await Package.Current.InstalledLocation.GetFolderAsync("MockResponses");
            var store = new StorageFolderResponseStore(responses);
            using (var handler = new FakeHttpMessageHandler(store))
            using (dynamic google = new DynamicRestClient("https://www.googleapis.com/", handler))
            {
                dynamic bucket = google.storage.v1.b("uspto-pair");

                dynamic metaData = await bucket.get();
                Assert.IsNotNull(metaData);

                dynamic objects = await bucket.o.get();
                Assert.IsNotNull(objects);
                Assert.IsTrue(objects.items.Count > 0);
            }
        }
        public async Task DeserializeToStaticType()
        {
            using (dynamic google = new DynamicRestClient("https://www.googleapis.com/", MockInitialization.Handler))
            {
                dynamic bucketEndPoint = google.storage.v1.b("uspto-pair");

                dynamic dynamicBucket = await bucketEndPoint.get();

                Assert.IsNotNull(dynamicBucket);
                Assert.AreEqual(dynamicBucket.name, "uspto-pair");

                Bucket staticBucket = await bucketEndPoint.get(typeof(Bucket));

                Assert.IsNotNull(staticBucket);
                Assert.AreEqual(staticBucket.name, "uspto-pair");
            }
        }
        public async Task UploadObject()
        {
            var auth = MockInitialization.GetAuthClient("email profile https://www.googleapis.com/auth/devstorage.read_write");
            _token = await auth.Authenticate(_token);
            Assert.IsNotNull(_token, "auth failed");

            var defaults = new DynamicRestClientDefaults()
            {
                AuthScheme = "OAuth",
                AuthToken = _token
            };
            using (dynamic google = new DynamicRestClient("https://www.googleapis.com/", MockInitialization.Handler, false, defaults))
            using (var stream = new StreamInfo(File.OpenRead(@"D:\temp\test.png"), "image/png"))
            {
                dynamic result = await google.upload.storage.v1.b.unit_tests.o.post(stream, name: new PostUrlParam("test_object"), uploadType: new PostUrlParam("media"));
                Assert.IsNotNull(result);
            }
        }
        [Ignore] // drive scopes don't work with device pin based oauth2 - ignore for now
        public async Task UploadFile()
        {
            var auth = MockInitialization.GetAuthClient("email profile https://www.googleapis.com/auth/devstorage.read_write");
            _token = await auth.Authenticate(_token);
            Assert.IsNotNull(_token, "auth failed");

            var defaults = new DynamicRestClientDefaults()
            {
                AuthScheme = "OAuth",
                AuthToken = _token
            };

            using (dynamic google = new DynamicRestClient("https://www.googleapis.com/", MockInitialization.Handler, false, defaults))
            {
                dynamic result = await google.upload.drive.v2.files.post(File.OpenRead(@"D:\temp\test.png"), uploadType: "media", title: "unit_test.jpg");

                Assert.IsNotNull(result);
            }
        }
        public async Task AuthenticateAndGetUserName()
        {
            using (dynamic google = new DynamicRestClient("https://www.googleapis.com/", MockInitialization.Handler, false, null, 
                async (request, cancelToken) =>
                {
                    // this demonstrates how to use the configuration callback to handle authentication 
                    var auth = MockInitialization.GetAuthClient("email profile");
                    var token = await auth.Authenticate("", cancelToken);
                    Assert.IsNotNull(token, "auth failed");

                    request.Headers.Authorization = new AuthenticationHeaderValue("OAuth", token);
                }))
            {
                var profile = await google.oauth2.v1.userinfo.get();

                Assert.IsNotNull(profile);
                Assert.AreEqual("Kackman", profile.family_name);
            }
        }
        //  [Ignore] // - this test requires user interaction
        public async Task GetUserProfile()
        {
            var auth = new GoogleOAuth2("email profile");
            _token = await auth.Authenticate(_token);
            Assert.IsNotNull(_token, "auth failed");

            using (var client = new HttpClient(MockInitialization.Handler, false))
            {
                client.BaseAddress = new Uri("https://www.googleapis.com");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token);

                using (dynamic proxy = new DynamicRestClient(client))
                {
                    var profile = await proxy.oauth2.v1.userinfo.get();

                    Assert.IsNotNull(profile);
                    Assert.AreEqual("Kackman", profile.family_name);
                }
            }
        }
        //  [Ignore] // - this test requires user interaction
        public async Task GetCalendarList()
        {
            var auth = new GoogleOAuth2("email profile https://www.googleapis.com/auth/calendar");
            _token = await auth.Authenticate(_token);
            Assert.IsNotNull(_token, "auth failed");

            using (var client = new HttpClient(MockInitialization.Handler, false))
            {
                client.BaseAddress = new Uri("https://www.googleapis.com/calendar/v3/");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token);

                using (dynamic proxy = new DynamicRestClient(client))
                {
                    var list = await proxy.users.me.calendarList.get();

                    Assert.IsNotNull(list);
                    Assert.AreEqual("calendar#calendarList", list.kind);
                }
            }
        }
        public async Task GetMethod2PathAsProperty2Params()
        {
            using (var client = new HttpClient(MockInitialization.Handler, false))
            {
                client.BaseAddress = new Uri("http://openstates.org/api/v1/");
                string key = CredentialStore.RetrieveObject("sunlight.key.json").Key;
                client.DefaultRequestHeaders.Add("X-APIKEY", key);

                using (dynamic proxy = new DynamicRestClient(client))
                {
                    var parameters = new Dictionary<string, object>()
                    {
                        { "lat", 44.926868 },
                        { "long", -93.214049 } // since long is a keyword we need to pass arguments in a Dictionary
                    };
                    var result = await proxy.legislators.geo.get(paramList: parameters);
                    Assert.IsNotNull(result);
                    Assert.IsTrue(result.Count > 0);
                }
            }
        }
        public async Task GetFormattedAddressFromCoordinate()
        {
            using (var client = new HttpClient(MockInitialization.Handler, false))
            {
                client.BaseAddress = new Uri("http://dev.virtualearth.net/REST/v1/");

                string key = CredentialStore.RetrieveObject("bing.key.json").Key;

                using (dynamic proxy = new DynamicRestClient(client))
                {
                    var result = await proxy.Locations("44.9108238220215,-93.1702041625977").get(includeEntityTypes: "Address,PopulatedPlace,Postcode1,AdminDivision1,CountryRegion", key: key);

                    Assert.AreEqual(200, (int)result.statusCode);
                    Assert.IsTrue(result.resourceSets.Count > 0);
                    Assert.IsTrue(result.resourceSets[0].resources.Count > 0);

                    var address = result.resourceSets[0].resources[0].address.formattedAddress;
                    Assert.AreEqual("1012 Davern St, St Paul, MN 55116", address);
                }
            }
        }
        public async Task CreateGoogleCalendarUsingClient()
        {
            using (dynamic google = new DynamicRestClient("https://www.googleapis.com/calendar/v3/", MockInitialization.Handler, false, null, 
                async (request, cancelToken) =>
                {
                    // this demonstrates how to use the configuration callback to handle authentication 
                    var auth = MockInitialization.GetAuthClient("email profile https://www.googleapis.com/auth/calendar");
                    var token = await auth.Authenticate("", cancelToken);
                    Assert.IsNotNull(token, "auth failed");

                    request.Headers.Authorization = new AuthenticationHeaderValue("OAuth", token);
                }))
            {
                dynamic calendar = new ExpandoObject();
                calendar.summary = "unit_testing";

                var list = await google.calendars.post(calendar);

                Assert.IsNotNull(list);
                Assert.AreEqual(list.summary, "unit_testing");
            }
        }