public async Task FindAllPeople()
        {
            var client = new ODataClient(new ODataClientSettings
            {
                BaseUri = _serviceUri,
                IncludeAnnotationsInResults = true
            });
            var annotations = new ODataFeedAnnotations();

            int count = 0;
            var people = await client
                .For<PersonWithAnnotations>("Person")
                .FindEntriesAsync(annotations);
            count += people.Count();

            while (annotations.NextPageLink != null)
            {
                people = await client
                    .For<PersonWithAnnotations>()
                    .FindEntriesAsync(annotations.NextPageLink, annotations);
                count += people.Count();

                foreach (var person in people)
                {
                    Assert.NotNull(person.Annotations.Id);
                    Assert.NotNull(person.Annotations.ReadLink);
                    Assert.NotNull(person.Annotations.EditLink);
                }
            }

            Assert.Equal(count, annotations.Count);
        }
 public async Task FindEntryNuGetV1()
 {
     var client = new ODataClient("http://nuget.org/api/v1");
     var package = await client.FindEntryAsync("Packages?$filter=Title eq 'EntityFramework'");
     Assert.NotNull(package["Id"]);
     Assert.NotNull(package["Authors"]);
 }
        internal EntityTracker(ODataClient oDataClient, object entity)
        {
            Contract.Requires<ArgumentNullException>(oDataClient != null);
            Contract.Requires<ArgumentNullException>(entity != null);

            _oDataClient = oDataClient;
            _entity = entity;
            _entityTypeInfo = oDataClient.GetEntityTypeInfoFor(entity.GetType());

            if (_entityTypeInfo == null)
            {
                throw new ArgumentException("Entity type " + entity.GetType() + " is unknown in the OData Client.");
            }

            _linkCollectionTrackers = new LinkCollectionTracker[_entityTypeInfo.CollectionProperties.Length];
            for (int i = 0; i < _entityTypeInfo.CollectionProperties.Length; ++i)
            {
                PropertyInfo property = _entityTypeInfo.CollectionProperties[i];
                IEnumerable collection = (IEnumerable) property.GetValue(_entity, null);
                if (collection != null)
                {
                    _linkCollectionTrackers[i] = new LinkCollectionTracker(this, property.Name, collection);
                }
            }

            INotifyPropertyChanged inpc = _entity as INotifyPropertyChanged;
            if (inpc != null)
            {
                // Use change tracking for more efficiency (possibly)
                inpc.PropertyChanged += OnPropertyChanged;
            }
        }
Esempio n. 4
0
        public void RetrieveSchemaFromUrlWithoutFilename()
        {
            var client = new ODataClient("http://vancouverdataservice.cloudapp.net/v1/impark");

            var schema = client.Schema;

            Assert.IsTrue(schema.Tables.Any());
        }
Esempio n. 5
0
        public void TypedCombinedConditionsFromODataOrg()
        {
			var client = new ODataClient("http://services.odata.org/V2/OData/OData.svc/");
            var product = client
                .For<ODataOrgProduct>("Product")
                .Filter(x => x.Name == "Bread" && x.Price < 1000)
                .FindEntry();
            Assert.AreEqual(2.5m, product.Price);
        }
Esempio n. 6
0
 static void AddProduct(Default.Container container, ODataClient.OData.Models.Product product)
 {
     container.AddToProducts(product);
     var serviceResponse = container.SaveChanges();
     foreach (var operationResponse in serviceResponse)
     {
         Console.WriteLine("Response: {0}", operationResponse.StatusCode);
     }
 }
Esempio n. 7
0
 public void AllEntriesFromODataOrg()
 {
     var client = new ODataClient("http://services.odata.org/V3/OData/OData.svc/");
     var products = client
         .For("Product")
         .FindEntries();
     Assert.IsNotNull(products);
     Assert.AreNotEqual(0, products.Count());
 }
 public void CombinedConditionsFromODataOrg()
 {
     var client = new ODataClient("http://services.odata.org/V3/OData/OData.svc/");
     var x = ODataFilter.Expression;
     var product = client
         .For("Product")
         .Filter(x.Name == "Bread" && x.Price < 1000)
         .FindEntry();
     Assert.Equal(2.5m, product["Price"]);
 }
Esempio n. 9
0
        public TestBase()
        {
#if NETFX_CORE
            _serviceUri = "http://NORTHWIND/Northwind/Northwind.svc/";
#else
            _service = new TestService(typeof(NorthwindService));
            _serviceUri = _service.ServiceUri.AbsoluteUri;
#endif
            _client = CreateClientWithDefaultSettings();
        }
Esempio n. 10
0
 public void GetEntryNonExistingIgnoreException()
 {
     var settings = new ODataClientSettings
     {
         UrlBase = _serviceUri,
         IgnoreResourceNotFoundException = true,
     };
     var client = new ODataClient(settings);
     Assert.Null(client.GetEntry("Products", new Entry() { { "ProductID", -1 } }));
 }
Esempio n. 11
0
 public async Task AsyncWithPartialFailures()
 {
     using (var batch = new ODataBatch(_serviceUri))
     {
         var client = new ODataClient(batch);
         await client.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test1" }, { "UnitPrice", 10m } }, false);
         await client.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test2" }, { "UnitPrice", 10m }, { "SupplierID", 0xFFFF } }, false);
         Assert.Throws<WebRequestException>(() => batch.Complete());
     }
 }
Esempio n. 12
0
 public void SyncWithAllFailures()
 {
     using (var batch = new ODataBatch(_serviceUri))
     {
         var client = new ODataClient(batch);
         client.InsertEntry("Products", new Entry() { { "UnitPrice", 10m } }, false);
         client.InsertEntry("Products", new Entry() { { "UnitPrice", 20m } }, false);
         Assert.Throws<WebRequestException>(() => batch.Complete());
     }
 }
Esempio n. 13
0
        public void DynamicCombinedConditionsFromODataOrg()
        {
			var client = new ODataClient("http://services.odata.org/V2/OData/OData.svc/");
			var x = ODataDynamic.Expression;
			var product = client
				.For(x.Product)
				.Filter(x.Name == "Bread" && x.Price < 1000)
				.FindEntry();
			Assert.AreEqual(2.5m, product.Price);
        }
		public void AllEntriesFromODataOrg()
        {
			AsyncContext.Run (async () => 
				{
					var client = new ODataClient("http://services.odata.org/V3/OData/OData.svc/");
					var products = await client
						.For("Product")
						.FindEntriesAsync();
					Assert.IsNotNull(products);
					Assert.AreNotEqual(0, products.Count());
				});
        }
        public async Task FindSinglePersonWithEntryAnnotations()
        {
            var client = new ODataClient(new ODataClientSettings
            {
                BaseUri = _serviceUri,
                IncludeAnnotationsInResults = true
            });
            var person = await client
                .For<PersonWithAnnotations>("Person")
                .Filter(x => x.UserName == "russellwhyte")
                .FindEntryAsync();

            Assert.NotNull(person.Annotations.Id);
        }
Esempio n. 16
0
        public async Task AsyncWithSuccess()
        {
            using (var batch = new ODataBatch(_serviceUri))
            {
                var client = new ODataClient(batch);
                await client.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test1" }, { "UnitPrice", 10m } }, false);
                await client.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test2" }, { "UnitPrice", 20m } }, false);
                batch.Complete();
            }

            var product = await _client.FindEntryAsync("Products?$filter=ProductName eq 'Test1'");
            Assert.NotNull(product);
            product = await _client.FindEntryAsync("Products?$filter=ProductName eq 'Test2'");
            Assert.NotNull(product);
        }
Esempio n. 17
0
        public void CheckODataOrgNorthwindSchema()
        {
            var client = new ODataClient("http://services.odata.org/Northwind/Northwind.svc/");

            var table = client.Schema.FindTable("Product");
            Assert.Equal("ProductID", table.PrimaryKey[0]);

            var association = table.FindAssociation("Categories");
            Assert.Equal("Categories", association.ReferenceTableName);
            Assert.Equal("0..1", association.Multiplicity);

            table = client.Schema.FindTable("Employees");
            association = table.FindAssociation("Employees");
            Assert.Equal("Employees", association.ReferenceTableName);
            Assert.Equal("0..1", association.Multiplicity);
        }
 public async Task FilterWithMetadataDocument()
 {
     var metadataDocument = await _client.GetMetadataDocumentAsync();
     ODataClient.ClearMetadataCache();
     var settings = new ODataClientSettings()
     {
         BaseUri = _serviceUri,
         PayloadFormat = _payloadFormat,
         MetadataDocument = metadataDocument,
     };
     var client = new ODataClient(settings);
     var products = await client
         .For("Products")
         .Filter("Name eq 'Milk'")
         .FindEntriesAsync();
     Assert.Equal("Milk", products.Single()["Name"]);
 }
Esempio n. 19
0
        public void CheckPluralsightComSchema()
        {
            var client = new ODataClient("http://pluralsight.com/odata/");

            var table = client.Schema.FindTable("Modules");
            Assert.AreEqual("Title", table.PrimaryKey[0]);

            Assert.IsNotNull(table.FindColumn("Author"));
            Assert.IsNotNull(table.FindColumn("Description"));

            var association = table.FindAssociation("Course");
            Assert.AreEqual("Courses", association.ReferenceTableName);
            Assert.AreEqual("*", association.Multiplicity);

            Assert.AreEqual(5, client.Schema.EntityTypes.Count());
            Assert.AreEqual(0, client.Schema.ComplexTypes.Count());
        }
        public async Task UpdateEntryNoResult()
        {
            var client = new ODataClient(CreateDefaultSettings().WithHttpMock());
            var key    = new Entry()
            {
                { "ProductID", 1 }
            };
            var product = await client.UpdateEntryAsync("Products", key, new Entry()
            {
                { "ProductName", "Chai" }, { "UnitPrice", 123m }
            }, false);

            Assert.Null(product);

            product = await client.GetEntryAsync("Products", key);

            Assert.Equal(123m, product["UnitPrice"]);
        }
        public async Task DeleteEntry()
        {
            var client  = new ODataClient(CreateDefaultSettings().WithHttpMock());
            var product = await client.InsertEntryAsync("Products", new Entry()
            {
                { "ProductName", "Test3" }, { "UnitPrice", 18m }
            }, true);

            product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test3'");

            Assert.NotNull(product);

            await client.DeleteEntryAsync("Products", product);

            product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test3'");

            Assert.Null(product);
        }
        public async Task DeleteEntrySubCollectionWithAnnotations()
        {
            var client = new ODataClient(CreateDefaultSettings().WithAnnotations().WithHttpMock());
            var ship   = await client.InsertEntryAsync("Transport/Ships", new Entry()
            {
                { "ShipName", "Test3" }
            }, true);

            ship = await client.FindEntryAsync("Transport?$filter=TransportID eq " + ship["TransportID"]);

            Assert.NotNull(ship);

            await client.DeleteEntryAsync("Transport", ship);

            ship = await client.FindEntryAsync("Transport?$filter=TransportID eq " + ship["TransportID"]);

            Assert.Null(ship);
        }
        public async Task SuccessWithResults()
        {
            var     settings = CreateDefaultSettings().WithHttpMock();
            Product product1 = null;
            Product product2 = null;

            var batch = new ODataBatch(settings);

            batch += async c => product1 = await c
                                           .For <Product>()
                                           .Set(new Product()
            {
                ProductName = "Test1", UnitPrice = 10m
            })
                                           .InsertEntryAsync();

            batch += async c => product2 = await c
                                           .For <Product>()
                                           .Set(new Product()
            {
                ProductName = "Test2", UnitPrice = 20m
            })
                                           .InsertEntryAsync();

            await batch.ExecuteAsync();

            Assert.NotEqual(0, product1.ProductID);
            Assert.NotEqual(0, product2.ProductID);

            var client = new ODataClient(settings);

            product1 = await client
                       .For <Product>()
                       .Filter(x => x.ProductName == "Test1")
                       .FindEntryAsync();

            Assert.NotNull(product1);
            product2 = await client
                       .For <Product>()
                       .Filter(x => x.ProductName == "Test2")
                       .FindEntryAsync();

            Assert.NotNull(product2);
        }
        public async Task Get_movie_count_by_year_untyped()
        {
            var settings = CreateDefaultSettings().WithHttpMock();
            var client   = new ODataClient(settings);
            var result   = await client
                           .WithExtensions()
                           .For <Movie>()
                           .Apply(b => b.GroupBy((x, a) => new
            {
                x.Year,
                Count = a.Count()
            }))
                           .OrderByDescending(x => x.Count)
                           .FindEntriesAsync();

            Assert.Equal(3, result.Count());
            Assert.Equal(new [] { 1990, 1989, 1995 }, result.Select(x => x.Year).ToArray());
            Assert.Equal(new [] { 10, 9, 1 }, result.Select(x => x.Count).ToArray());
        }
        public async Task FunctionWithComplexType()
        {
            var client  = new ODataClient(CreateDefaultSettings().WithHttpMock());
            var address = new Address {
                City = "Oslo", Country = "Norway", Region = "Oslo", PostalCode = "1234"
            };
            var result = await client
                         .Unbound <IDictionary <string, object> >()
                         .Action("PassThroughAddress")
                         .Set(new Entry()
            {
                { "address", address }
            })
                         .ExecuteAsSingleAsync();

            result = result["PassThroughAddress"] as IDictionary <string, object>;
            Assert.Equal("Oslo", result["City"]);
            Assert.Equal("Norway", result["Country"]);
        }
Esempio n. 26
0
        public async Task ExpandMultipleLevelsWithCollectionAndSelect()
        {
            var client  = new ODataClient(CreateDefaultSettings().WithHttpMock());
            var product = (await client
                           .For("Products")
                           .OrderBy("ProductID")
                           .Expand("Category/Products/Category")
                           .Select(new[] { "Category/Products/Category/CategoryName" })
                           .FindEntriesAsync()).Last();

            Assert.Equal(1, product.Count);
            Assert.Equal(1, (product["Category"] as IDictionary <string, object>).Count);
            Assert.Equal(1, (((product["Category"] as IDictionary <string, object>)["Products"] as IEnumerable <object>)
                             .First() as IDictionary <string, object>).Count);
            Assert.Equal(1, ((((product["Category"] as IDictionary <string, object>)["Products"] as IEnumerable <object>)
                              .First() as IDictionary <string, object>)["Category"] as IDictionary <string, object>).Count);
            Assert.Equal("Condiments", ((((product["Category"] as IDictionary <string, object>)["Products"] as IEnumerable <object>)
                                         .First() as IDictionary <string, object>)["Category"] as IDictionary <string, object>)["CategoryName"]);
        }
Esempio n. 27
0
        public virtual async Task TestTimeZonesInUrlWithClientDemand()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                ODataClient client = testEnvironment.Server.BuildODataClient(token: token, beforeRequest: message =>
                {
                    message.Headers.Add("Desired-Time-Zone", "Iran Standard Time");
                    message.Headers.Add("Current-Time-Zone", "Afghanistan Standard Time");
                });

                IEnumerable <TestModel> testModels = await client.Controller <TestModelsController, TestModel>()
                                                     .Filter(tm => tm.DateProperty == new DateTimeOffset(2016, 1, 1, 9, 30, 0, TimeSpan.Zero))
                                                     .FindEntriesAsync();

                Assert.AreEqual(1, testModels.Count());
            }
        }
Esempio n. 28
0
        public async Task FilterWithMetadataDocument()
        {
            var metadataDocument = await _client.GetMetadataDocumentAsync();

            ODataClient.ClearMetadataCache();
            var settings = new ODataClientSettings()
            {
                BaseUri          = _serviceUri,
                PayloadFormat    = _payloadFormat,
                MetadataDocument = metadataDocument,
            };
            var client   = new ODataClient(settings);
            var products = await client
                           .For("Products")
                           .Filter("Name eq 'Milk'")
                           .FindEntriesAsync();

            Assert.Equal("Milk", products.Single()["Name"]);
        }
Esempio n. 29
0
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation <NavigationPage>("Nav");

            containerRegistry.RegisterForNavigation <LoginView, LoginViewModel>("Login");
            containerRegistry.RegisterForNavigation <MainView, MainViewModel>("Main");

            Simple.OData.Client.V4Adapter.Reference();

            containerRegistry.GetBuilder().Register(c =>
            {
                ISecurityService securityService = c.Resolve <ISecurityService>();
                ODataClient odataClient          = new ODataClient(new ODataClientSettings(new Uri(c.Resolve <IConfigProvider>().HostUri, "odata/Test/"))
                {
                    OnCreateMessageHandler = () => new TokenHandler(securityService, new HttpClientHandler())
                });
                return(odataClient);
            });

            containerRegistry.GetBuilder().Register(c =>
            {
                ISecurityService securityService = c.Resolve <ISecurityService>();
                HttpClient httpClient            = new HttpClient(new TokenHandler(securityService, new HttpClientHandler()))
                {
                    BaseAddress = c.Resolve <IConfigProvider>().HostUri
                };
                return(httpClient);
            }).SingleInstance();

            containerRegistry.GetBuilder().Register(c =>
            {
                IConfigProvider configProvider = c.Resolve <IConfigProvider>();
                return(new TokenClient(address: new Uri(configProvider.HostUri, "core/connect/token").ToString(), clientId: configProvider.OAuthResourceOwnerFlowClientId, clientSecret: configProvider.OAuthResourceOwnerFlowSecret));
            }).SingleInstance();

            containerRegistry.RegisterSingleton <BitOAuth2Authenticator>();
            containerRegistry.RegisterSingleton <OAuthLoginPresenter>();
            containerRegistry.RegisterSingleton <ISecurityService, DefaultSecurityService>();
            containerRegistry.RegisterSingleton <IConfigProvider, TestConfigProvider>();
            containerRegistry.RegisterSingleton <IDateTimeProvider, DefaultDateTimeProvider>();

            containerRegistry.GetBuilder().Register(c => AccountStore.Create()).SingleInstance();
        }
        public async void OnSearchTextChanged()
        {
            _CancellationTokenSource.Cancel();

            _CancellationTokenSource = new CancellationTokenSource();

            if (!string.IsNullOrEmpty(SearchText) && SearchText.Length > 2)
            {
                var customers = (await ODataClient.Customers()
                                 .Where(c => c.FirstName.Contains(SearchText) || c.LastName.Contains(SearchText))
                                 .FindEntriesAsync(_CancellationTokenSource.Token)).ToList();

                Customers = new ObservableCollection <CustomerDto>(customers);
            }
            else
            {
                await Get();
            }
        }
        public async Task InterceptRequestAsync()
        {
            var settings = new ODataClientSettings
            {
                BaseUri            = _serviceUri,
                BeforeRequestAsync = x =>
                {
                    x.Method = new HttpMethod("PUT");
                    var tcs  = new TaskCompletionSource <HttpRequestMessage>();
                    var task = tcs.Task;
                    tcs.SetResult(x);

                    return(task);
                }
            };
            var client = new ODataClient(settings);

            await AssertThrowsAsync <WebRequestException>(async() => await client.FindEntriesAsync("Products"));
        }
Esempio n. 32
0
        async Task DeleteCustomer(CustomerDto customerDto)
        {
            try
            {
                customerDto.CurrentState = State.Saving;

                await ODataClient.Customers()
                .Key(customerDto.Id)
                .DeleteEntryAsync();

                CustomersView.Remove(customerDto);

                await UserDialogs.AlertAsync($"{customerDto.FullName} Successfully Deleted!");
            }
            finally
            {
                customerDto.CurrentState = State.None;
            }
        }
    public async Task UpdateDerived()
    {
        var client = new ODataClient(CreateDefaultSettings().WithHttpMock());
        var x      = ODataDynamic.Expression;
        var ship   = await client
                     .For(x.Transport)
                     .As(x.Ship)
                     .Set(x.ShipName = "Test1")
                     .InsertEntryAsync();

        ship = await client
               .For(x.Transport)
               .As(x.Ship)
               .Key(ship.TransportID)
               .Set(x.ShipName = "Test2")
               .UpdateEntryAsync();

        Assert.Equal("Test2", ship.ShipName);
    }
Esempio n. 34
0
        public void CheckODataOrgODataSchema()
        {
			var client = new ODataClient("http://services.odata.org/V3/OData/OData.svc/");

			var table = client.Schema.FindTable("Product");
			Assert.AreEqual("ID", table.PrimaryKey[0]);

			var association = table.FindAssociation("Category_Products");
			Assert.AreEqual("Categories", association.ReferenceTableName);
			Assert.AreEqual("*", association.Multiplicity);

			var function = client.Schema.FindFunction("GetProductsByRating");
			Assert.AreEqual(RestVerbs.GET, function.HttpMethod);
			Assert.AreEqual("rating", function.Parameters[0]);

			Assert.AreEqual(10, client.Schema.EntityTypes.Count());
			Assert.AreEqual(1, client.Schema.ComplexTypes.Count());
			Assert.AreEqual(5, client.Schema.ComplexTypes.First().Properties.Count());
        }
Esempio n. 35
0
        public async Task SelectMultipleRename()
        {
            var settings = new ODataClientSettings
            {
                BaseUri = _serviceUri,
                IgnoreUnmappedProperties = true,
            };
            var client = new ODataClient(CreateDefaultSettings().WithHttpMock());
            //var client = new ODataClient(settings);

            var product = await client
                          .For <ProductWithUnmappedProperty>("Products")
                          .Filter(x => x.ProductName == "Chai")
                          .Select(x => new { x.ProductID, UnmappedName = x.ProductName })
                          .FindEntryAsync();

            Assert.Equal("Chai", product.UnmappedName);
            Assert.Null(product.ProductName);
        }
Esempio n. 36
0
        public async Task TestPartialUpdate()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                ODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                long modelBeforeUpdateId = await client.Controller <TestModelsController, TestModel>()
                                           .Top(1)
                                           .Select(t => t.Id)
                                           .FindScalarAsync <long>();

                TestModel modelAfterUpdate = await client.Controller <TestModelsController, TestModel>()
                                             .Key(modelBeforeUpdateId)
                                             .Set(new { StringProperty = "Test2" })
                                             .UpdateEntryAsync();

                Assert.AreEqual("Test2", modelAfterUpdate.StringProperty);

                TestModelsController testModelsController = TestDependencyManager.CurrentTestDependencyManager.Objects
                                                            .OfType <TestModelsController>()
                                                            .Last();

                A.CallTo(() => testModelsController.PartialUpdate(modelBeforeUpdateId,
                                                                  A <Delta <TestModel> > .That.Matches(
                                                                      testModelDelta =>
                                                                      testModelDelta.GetChangedPropertyNames().Single() == nameof(TestModel.StringProperty)),
                                                                  A <CancellationToken> .Ignored))
                .MustHaveHappened(Repeated.Exactly.Once);

                IRepository <TestModel> testModelsRepository =
                    TestDependencyManager.CurrentTestDependencyManager.Objects
                    .OfType <IRepository <TestModel> >()
                    .Last();

                A.CallTo(() => testModelsRepository.UpdateAsync(
                             A <TestModel> .That.Matches(testModel => testModel.StringProperty == "Test2"),
                             A <CancellationToken> .Ignored))
                .MustHaveHappened(Repeated.Exactly.Once);
            }
        }
Esempio n. 37
0
        public async Task NestedBatch()
        {
            var settings = CreateDefaultSettings().WithHttpMock();
            var batch1   = new ODataBatch(settings);

            batch1 += c => c.InsertEntryAsync("Products", new Entry()
            {
                { "ProductName", "Test1" }, { "UnitPrice", 10m }
            }, false);
            batch1 += c => c.InsertEntryAsync("Products", new Entry()
            {
                { "ProductName", "Test2" }, { "UnitPrice", 20m }
            }, false);

            var batch2 = new ODataBatch(settings);

            batch2 += c => c.InsertEntryAsync("Products", new Entry()
            {
                { "ProductName", "Test3" }, { "UnitPrice", 30m }
            }, false);
            batch2 += c => c.InsertEntryAsync("Products", new Entry()
            {
                { "ProductName", "Test4" }, { "UnitPrice", 40m }
            }, false);
            await batch2.ExecuteAsync();

            await batch1.ExecuteAsync();

            var client  = new ODataClient(settings);
            var product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test1'");

            Assert.NotNull(product);
            product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test2'");

            Assert.NotNull(product);
            product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test3'");

            Assert.NotNull(product);
            product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test4'");

            Assert.NotNull(product);
        }
        public async Task MetadataErrorIsNotCached()
        {
            var baseUri  = new Uri("ftp://localhost/");
            var settings = new ODataClientSettings {
                BaseUri = baseUri
            };

            var client = new ODataClient(settings);

            try
            {
                await client.GetMetadataAsync();
            }
            catch (ArgumentException)
            {
                //only HTTP and HTTPS supported
            }
            catch (AggregateException ex)
            {
                ex = ex.Flatten();
                if (ex.InnerExceptions.Count != 1)
                {
                    throw;
                }
                var arg = ex.InnerException as ArgumentException;
                if (arg == null)
                {
                    throw;
                }
                //only HTTP and HTTPS supported
            }

            var wasCached = true;
            var cached    = EdmMetadataCache.GetOrAdd("ftp://localhost/", x =>
            {
                wasCached = false;
                return(null);
            });

            Assert.False(wasCached);
            Assert.Null(cached);
        }
        //private IODataClient SetOdataSettingsAndReturnFOClient()
        //{
        //    string apiEndpoint = configuration[AppConfigurationKeys.FOApiEndpoint] + configuration[AppConfigurationKeys.FOApiEndpointSuffix];
        //    var settings = new ODataClientSettings(new Uri(apiEndpoint));
        //    settings.BeforeRequest += SetRequestHeadersForFOToken;
        //    var client = new ODataClient(settings);
        //    return client;
        //}



        public static async Task <ODataClient> GetODataClient()
        {
            string token = await GetAccessToken();

            string apiEndPoint = "https://cfxdev.api.crm.dynamics.com/";

            apiEndPoint = apiEndPoint + "api/data/v9.1/";

            var settings = new ODataClientSettings(new Uri(apiEndPoint));

            settings.BeforeRequest += delegate(HttpRequestMessage message)
            {
                message.Headers.Add("Authorization", "Bearer " + token);
                // message.Headers.Add("Prefer", "odata.include-annotations=\"*\"");
                message.Headers.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
            };
            var client = new ODataClient(settings);

            return(client);
        }
        public void TypedWithPluralizerFromODataOrg()
        {
            AsyncContext.Run(async () =>
            {
                var client = new ODataClient("http://services.odata.org/V2/OData/OData.svc/");
                var products = await client
                    .For<Product>()
                    .FindEntriesAsync();
                Assert.AreNotEqual(0, products.Count());
            });

            AsyncContext.Run(async () =>
            {
                var client = new ODataClient("http://services.odata.org/V2/OData/OData.svc/");
                var products = await client
                    .For<Products>()
                    .FindEntriesAsync();
                Assert.AreNotEqual(0, products.Count());
            });
        }
Esempio n. 41
0
        public async Task CheckODataOrgNorthwindSchema()
        {
            var client = new ODataClient("http://services.odata.org/V2/Northwind/Northwind.svc/");
            var schema = await client.GetSchemaAsync();

            var table = schema.FindTable("Product");
            Assert.AreEqual("ProductID", table.PrimaryKey[0]);

            var association = table.FindAssociation("Categories");
            Assert.AreEqual("Categories", association.ReferenceTableName);
            Assert.AreEqual("0..1", association.Multiplicity);

            table = schema.FindTable("Employees");
            association = table.FindAssociation("Employees");
            Assert.AreEqual("Employees", association.ReferenceTableName);
            Assert.AreEqual("0..1", association.Multiplicity);

            Assert.AreEqual(26, schema.EntityTypes.Count());
            Assert.AreEqual(0, schema.ComplexTypes.Count());
        }
    public async Task ErrorMessage_ResponseContent()
    {
        try
        {
            var client = new ODataClient(CreateDefaultSettings(x =>
                                                               x.WebRequestExceptionMessageSource = WebRequestExceptionMessageSource.ResponseContent));

            await client
            .For("Products")
            .Filter("NonExistingProperty eq 1")
            .FindEntryAsync().ConfigureAwait(false);

            Assert.False(true, "Expected exception");
        }
        catch (WebRequestException ex)
        {
            Assert.NotNull(ex.Message);
            Assert.Equal(ex.Response, ex.Message);
        }
    }
    public async Task UpdateDerived()
    {
        var client = new ODataClient(CreateDefaultSettings().WithHttpMock());
        var ship   = await client
                     .For <Transport>()
                     .As <Ship>()
                     .Set(new Ship {
            ShipName = "Test1"
        })
                     .InsertEntryAsync().ConfigureAwait(false);

        ship = await client
               .For <Transport>()
               .As <Ship>()
               .Key(ship.TransportID)
               .Set(new { ShipName = "Test2" })
               .UpdateEntryAsync().ConfigureAwait(false);

        Assert.Equal("Test2", ship.ShipName);
    }
Esempio n. 44
0
        public async Task DeleteByKey()
        {
            var client  = new ODataClient(CreateDefaultSettings().WithHttpMock());
            var product = await client
                          .For <Product>()
                          .Set(new { ProductName = "Test1", UnitPrice = 18m })
                          .InsertEntryAsync();

            await client
            .For <Product>()
            .Key(product.ProductID)
            .DeleteEntryAsync();

            product = await client
                      .For <Product>()
                      .Filter(x => x.ProductName == "Test1")
                      .FindEntryAsync();

            Assert.Null(product);
        }
Esempio n. 45
0
        public void TypedWithPluralizerFromODataOrg()
        {
            AsyncContext.Run(async() =>
            {
                var client   = new ODataClient("http://services.odata.org/V2/OData/OData.svc/");
                var products = await client
                               .For <Product>()
                               .FindEntriesAsync();
                Assert.AreNotEqual(0, products.Count());
            });

            AsyncContext.Run(async() =>
            {
                var client   = new ODataClient("http://services.odata.org/V2/OData/OData.svc/");
                var products = await client
                               .For <Products>()
                               .FindEntriesAsync();
                Assert.AreNotEqual(0, products.Count());
            });
        }
        public async Task ErrorMessage_PhraseAndContent()
        {
            try
            {
                var client = new ODataClient(CreateDefaultSettings(x =>
                                                                   x.WebRequestExceptionMessageSource = WebRequestExceptionMessageSource.Both));

                await client
                .For("Products")
                .Filter("NonExistingProperty eq 1")
                .FindEntryAsync();

                Assert.False(true, "Expected exception");
            }
            catch (WebRequestException ex)
            {
                Assert.NotNull(ex.Message);
                Assert.True(ex.Message.Contains(ex.ReasonPhrase) && ex.Message.Contains(ex.Response));
            }
        }
        public async Task MetadataIsCached()
        {
            var settings = new ODataClientSettings {
                BaseUri = _serviceUri
            };
            var client = new ODataClient(settings);

            await client.GetMetadataAsync();

            EdmMetadataCache.GetOrAdd(_serviceUri.ToString(), x => throw new Exception("metadata was not cached."));

            settings.BeforeRequest = x => throw new Exception("metadata cache was not used.");
            await client.GetMetadataAsync();

            settings = new ODataClientSettings {
                BaseUri = _serviceUri, BeforeRequest = x => throw new Exception("not reusing settings will defeat metadata cache.")
            };
            client = new ODataClient(settings);
            await client.GetMetadataAsync();
        }
Esempio n. 48
0
        public async Task LinkEntry()
        {
            var client   = new ODataClient(CreateDefaultSettings().WithHttpMock());
            var category = await client.InsertEntryAsync("Categories", new Entry()
            {
                { "CategoryName", "Test4" }
            }, true);

            var product = await client.InsertEntryAsync("Products", new Entry()
            {
                { "ProductName", "Test5" }
            }, true);

            await client.LinkEntryAsync("Products", product, "Category", category);

            product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test5'");

            Assert.NotNull(product["CategoryID"]);
            Assert.Equal(category["CategoryID"], product["CategoryID"]);
        }
Esempio n. 49
0
    public async Task DeleteByKey()
    {
        var client  = new ODataClient(CreateDefaultSettings().WithHttpMock());
        var product = await client
                      .For("Products")
                      .Set(new { ProductName = "Test1", UnitPrice = 18m })
                      .InsertEntryAsync().ConfigureAwait(false);

        await client
        .For("Products")
        .Key(product["ProductID"])
        .DeleteEntryAsync().ConfigureAwait(false);

        product = await client
                  .For("Products")
                  .Filter("ProductName eq 'Test1'")
                  .FindEntryAsync().ConfigureAwait(false);

        Assert.Null(product);
    }
        public virtual async Task WebApiTraceWritterShouldLogCorrelationIdAndExceptionDetails()
        {
            IEmailService emailService = A.Fake <IEmailService>();

            A.CallTo(() => emailService.SendEmail(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Throws(new AppException("Test"));

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs
            {
                AdditionalDependencies = manager =>
                {
                    manager.RegisterInstance(emailService);
                }
            }))
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                ODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                try
                {
                    await client.Controller <TestModelsController, TestModel>()
                    .Action(nameof(TestModelsController.SendEmail))
                    .Set(new TestModelsController.EmailParameters {
                        to = "Someone", title = "Email title", message = "Email message"
                    })
                    .ExecuteAsync();

                    Assert.Fail();
                }
                catch (WebRequestException)
                {
                    ILogger logger = TestDependencyManager.CurrentTestDependencyManager.Objects
                                     .OfType <ILogger>().Last();

                    Assert.IsTrue(logger.LogData.Single(ld => ld.Key == "X-CorrelationId").Value is Guid);
                    Assert.AreEqual(typeof(AppException).GetTypeInfo().FullName, logger.LogData.Single(ld => ld.Key == "WebExceptionType").Value);
                    Assert.IsTrue(((string)(logger.LogData.Single(ld => ld.Key == "WebException").Value)).Contains("Bit.Owin.Exceptions.AppException: Test"));
                }
            }
        }
Esempio n. 51
0
        public async Task InsertUpdateDeleteSeparateBatchesRenewHttpConnection()
        {
            var settings = CreateDefaultSettings().WithHttpMock();
            var batch    = new ODataBatch(settings);

            batch += c => c.InsertEntryAsync("Products", new Entry()
            {
                { "ProductName", "Test12" }, { "UnitPrice", 21m }
            }, false);
            await batch.ExecuteAsync();

            var client = new ODataClient(new ODataClientSettings {
                BaseUri = _serviceUri, RenewHttpConnection = true
            });
            var product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test12'");

            Assert.Equal(21m, product["UnitPrice"]);
            var key = new Entry()
            {
                { "ProductID", product["ProductID"] }
            };

            batch  = new ODataBatch(settings);
            batch += c => c.UpdateEntryAsync("Products", key, new Entry()
            {
                { "UnitPrice", 22m }
            });
            await batch.ExecuteAsync();

            product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test12'");

            Assert.Equal(22m, product["UnitPrice"]);

            batch  = new ODataBatch(settings);
            batch += c => c.DeleteEntryAsync("Products", key);
            await batch.ExecuteAsync();

            product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test12'");

            Assert.Null(product);
        }
Esempio n. 52
0
        private async void syncCauseData()
        {
            // flag == false;
            IsProgress = true;
            isHits     = false;
            try
            {
                if (flag == false)
                {
                    var x      = ODataDynamic.Expression;
                    var client = new ODataClient("http://NWGateway.indience.in:8000/sap/opu/odata/sap/ZGWS_PM_RWO_SRV/");


                    var sproductList = await client.For("CauseSet").FindEntriesAsync();

                    var data = sproductList;
                    //foreach (var data in sproductList)
                    //{
                    //    int ID = int.Parse(data["ID"].ToString());

                    //    using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
                    //    {
                    //        conn.RunInTransaction(() =>
                    //        {
                    //            conn.Insert(new Products(data["Name"].ToString(), ID, data["Description"].ToString()));
                    //        });
                    //    }
                    //}
                    //flag = true;
                    //IsProgress = false;
                    //isHits = true;

                    //await _dialogService.ShowMessage("Sync Successfully Check Your Data Base..!", "Success");
                    //ProductsListCollection = new DatabaseHelperClass().ReadAllProducts();
                }
            }
            catch (Exception e)
            {
                await _dialogService.ShowMessage(e.Message, "Warning");
            }
        }
        public async Task InsertUsingModifiedSchema()
        {
            await AssertThrowsAsync<Microsoft.Data.OData.ODataException>(async () => 
                await _client.InsertEntryAsync("Customers", new Entry() { { "CompanyName", null } }));

            var metadataDocument = await _client.GetMetadataDocumentAsync();
            metadataDocument = metadataDocument.Replace(@"Name=""CompanyName"" Type=""Edm.String"" Nullable=""false""", @"Name=""CompanyName"" Type=""Edm.String"" Nullable=""true""");
            ODataClient.ClearMetadataCache();
            var settings = new ODataClientSettings
            {
                BaseUri = _serviceUri,
                MetadataDocument = metadataDocument,
            };
            var client = new ODataClient(settings);
            var model = await client.GetMetadataAsync<IEdmModel>();
            var type = model.FindDeclaredType("NorthwindModel.Customers");
            var property = (type as IEdmEntityType).DeclaredProperties.Single(x => x.Name == "CompanyName");
            Assert.Equal(true, property.Type.IsNullable);

            await AssertThrowsAsync<WebRequestException>(async () => 
                await client.InsertEntryAsync("Customers", new Entry() { { "CompanyName", null } }));

            ODataClient.ClearMetadataCache();
        }
Esempio n. 54
0
 public void AllDerivedClassEntriesWithResourceTypes()
 {
     var clientSettings = new ODataClientSettings
     {
         UrlBase = _serviceUri,
         IncludeResourceTypeInEntryProperties = true,
     };
     var client = new ODataClient(clientSettings);
     var transport = client
         .For<Transport>()
         .As<Ship>()
         .FindEntries();
     Assert.Equal("Titanic", transport.Single().ShipName);
 }
Esempio n. 55
0
 public void BaseClassEntriesWithResourceTypes()
 {
     var clientSettings = new ODataClientSettings
     {
         UrlBase = _serviceUri,
         IncludeResourceTypeInEntryProperties = true,
     };
     var client = new ODataClient(clientSettings);
     var transport = client
         .For<Transport>()
         .FindEntries();
     Assert.Equal(2, transport.Count());
 }
 public async Task AllDerivedClassEntriesWithAnnotations()
 {
     var clientSettings = new ODataClientSettings
     {
         BaseUri = _serviceUri,
         IncludeAnnotationsInResults = true,
     };
     var client = new ODataClient(clientSettings);
     var transport = await client
         .For<Transport>()
         .As<Ship>()
         .FindEntriesAsync();
     Assert.Equal("Titanic", transport.Single().ShipName);
 }
 public async Task BaseClassEntriesWithAnnotations()
 {
     var clientSettings = new ODataClientSettings
     {
         BaseUri = _serviceUri,
         IncludeAnnotationsInResults = true,
     };
     var client = new ODataClient(clientSettings);
     var transport = await client
         .For<Transport>()
         .FindEntriesAsync();
     Assert.Equal(2, transport.Count());
 }
        public async Task SelectMultipleRename()
        {
            var settings = new ODataClientSettings
            {
                BaseUri = _serviceUri,
                IgnoreUnmappedProperties = true,
            };
            var client = new ODataClient(settings);

            var product = await client
                .For<ProductWithUnmappedProperty>("Products")
                .Filter(x => x.ProductName == "Chai")
                .Select(x => new { x.ProductID, UnmappedName = x.ProductName })
                .FindEntryAsync();
            Assert.Equal("Chai", product.UnmappedName);
            Assert.Null(product.ProductName);
        }
        public async Task IgnoredUnmappedColumn()
        {
            var settings = new ODataClientSettings
            {
                BaseUri = _serviceUri,
                IgnoreUnmappedProperties = true,
            };
            var client = new ODataClient(settings);

            var product = await client
                .For<ProductWithUnmappedProperty>("Products")
                .Set(new ProductWithUnmappedProperty { ProductName = "Test1" })
                .InsertEntryAsync();

            await client
                .For<ProductWithUnmappedProperty>("Products")
                .Key(product.ProductID)
                .Set(new ProductWithUnmappedProperty { ProductName = "Test2" })
                .UpdateEntryAsync(false);

            product = await client
                .For<ProductWithUnmappedProperty>("Products")
                .Key(product.ProductID)
                .FindEntryAsync();
            Assert.Equal("Test2", product.ProductName);
        }
        public async Task UpdateEntrySubcollectionWithAnnotations()
        {
            var clientSettings = new ODataClientSettings
            {
                BaseUri = _serviceUri,
                IncludeAnnotationsInResults = true,
            };
            var client = new ODataClient(clientSettings);
            var ship = await client.InsertEntryAsync("Transport/Ships", new Entry() { { "ShipName", "Test1" } }, true);
            var key = new Entry() { { "TransportID", ship["TransportID"] } };
            await client.UpdateEntryAsync("Transport/Ships", key, new Entry() { { "ShipName", "Test2" }, { FluentCommand.ResourceTypeLiteral, "Ships" } });

            ship = await client.GetEntryAsync("Transport", key);
            Assert.Equal("Test2", ship["ShipName"]);
        }