public void AddObjectTestAction(ODataFormat format, MergeOption mergeOption, SaveChangesOptions saveChangesOption) { DataServiceContextWrapper <DefaultContainer> contextWrapper = this.CreateContext(); contextWrapper.Context.MergeOption = mergeOption; if (format == ODataFormat.Json) { contextWrapper.Format.UseJson(); } contextWrapper.Configurations.RequestPipeline .OnEntryStarting(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Writing) .OnEntryEnding(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntry_Writing); Customer customer = PipelineEventsTestsHelper.CreateNewCustomer(100); contextWrapper.AddObject("Customer", customer); contextWrapper.SaveChanges(saveChangesOption); if (format == ODataFormat.Atom) { // Make the ATOM payload order consistence with JSON. Assert.IsTrue(customer.Name.EndsWith("UpdatedODataEntryPropertyValueModifyPropertyValueCustomerEntry_Writing"), "Unexpected primitive property"); } else { Assert.IsTrue(customer.Name.EndsWith("UpdatedODataEntryPropertyValue"), "Unexpected primitive property"); } Assert.IsTrue(customer.Auditing.ModifiedBy.Equals("UpdatedODataEntryPropertyValue"), "Unexpected complex property"); Assert.IsTrue(customer.PrimaryContactInfo.EmailBag.Contains("UpdatedODataEntryPropertyValue")); contextWrapper.DeleteObject(customer); contextWrapper.SaveChanges(); }
private object ConstructCollectionInstance(DataServiceQuery inner = null, DataServiceContextWrapper context = null, object entity = null, string path = null) { var mock = typeof(Mock <>) .MakeGenericType(CollectionType) .GetConstructor(PermissiveBindingFlags, null, new[] { typeof(MockBehavior), typeof(object[]) }, null) .Invoke(new object[] { MockBehavior.Default, new object[] { inner, context, entity, path } }); mock.GetType() .GetProperty("CallBase") .SetValue(mock, true); this.GetType() .GetMethods(PermissiveBindingFlags) .Where(m => m.Name.Equals("ConfigureCollectionMock")) .First(m => m.IsGenericMethod) .MakeGenericMethod(CollectionType, ConcreteType, ConcreteInterface) .Invoke(this, PermissiveBindingFlags, null, new[] { mock }, null); return(mock.GetType() .GetProperties() .Where(p => p.Name == "Object") .First(p => p.PropertyType == CollectionType) .GetValue(mock)); }
private void ExecuteActions(DataServiceContextWrapper <DefaultContainer> context, IEnumerable <OperationDescriptor> operationDescriptors) { foreach (OperationDescriptor od in operationDescriptors) { context.Execute(od.Target, "POST"); } }
private static void QueryEntityInstanceExecuteAsync(DataServiceContextWrapper <DefaultContainer> contextWrapper) { // contextWrapper.Context.UndeclaredPropertyBehavior = UndeclaredPropertyBehavior.Support; contextWrapper.Configurations.ResponsePipeline .OnEntryEnded(PipelineEventsTestsHelper.AddRemovePropertySpecialEmployeeEntry_Reading) .OnEntityMaterialized(PipelineEventsTestsHelper.AddEnumPropertySpecialEmployeeEntity_Materialized) .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Materialized); IEnumerable <SpecialEmployee> specialEmployees = null; IAsyncResult r = contextWrapper.BeginExecute <SpecialEmployee>( new Uri("Person(-10)", UriKind.Relative), result => { specialEmployees = contextWrapper.EndExecute <SpecialEmployee>(result); }, null); while (!r.IsCompleted) { Thread.Sleep(1000); } SpecialEmployee specialEmployee = specialEmployees.Single(); Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee.CarsLicensePlate, "Unexpected CarsLicensePlate"); Assert.AreEqual(1, specialEmployee.BonusLevel, "Unexpected BonusLevel"); }
private static void DataServiceCollectionTrackingItems( DataServiceContextWrapper <DefaultContainer> contextWrapper) { var query = from p in contextWrapper.Context.Customer where p.CustomerId > -100000 // try to get many for paging select new Customer() { CustomerId = p.CustomerId, Name = p.Name }; DataServiceCollection <Customer> collection = new DataServiceCollection <Customer>(query); // the collection to track items int tmpCount = collection.Count; collection.Load(contextWrapper.Context.Execute(collection.Continuation)); // for testing newly loaded item's tracking Assert.IsTrue(collection.Count > tmpCount, "Should have loaded another page."); bool someItemNotTracked = false; collection.ToList().ForEach(s => { s.Name = "value to test tracking"; EntityStates state = contextWrapper.Context.GetEntityDescriptor(s).State; someItemNotTracked = (state == EntityStates.Unchanged) || someItemNotTracked; }); Assert.IsFalse(someItemNotTracked, "All items should have been tracked."); }
private static void QueryEntityInstance(DataServiceContextWrapper <DefaultContainer> contextWrapper) { // contextWrapper.Context.UndeclaredPropertyBehavior = UndeclaredPropertyBehavior.Support; contextWrapper.Configurations.ResponsePipeline .OnEntryEnded(PipelineEventsTestsHelper.AddRemovePropertySpecialEmployeeEntry_Reading) .OnEntityMaterialized(PipelineEventsTestsHelper.AddEnumPropertySpecialEmployeeEntity_Materialized) .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Materialized); var specialEmployee = contextWrapper.CreateQuery <Person>("Person").Where(p => p.PersonId == -10).Single() as SpecialEmployee; EntityDescriptor descriptor = contextWrapper.GetEntityDescriptor(specialEmployee); Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee.CarsLicensePlate, "Unexpected CarsLicensePlate"); Assert.AreEqual(1, specialEmployee.BonusLevel, "Unexpected BonusLevel"); specialEmployee = contextWrapper.Execute <SpecialEmployee>(new Uri("Person(-10)", UriKind.Relative)).Single(); Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee.CarsLicensePlate, "Unexpected CarsLicensePlate"); Assert.AreEqual(1, specialEmployee.BonusLevel, "Unexpected BonusLevel"); DataServiceRequest[] requests = new DataServiceRequest[] { contextWrapper.CreateQuery <Person>("Person"), contextWrapper.CreateQuery <Customer>("Customer"), }; DataServiceResponse responses = contextWrapper.ExecuteBatch(requests); bool personVerified = false; bool customerVerified = false; foreach (QueryOperationResponse response in responses) { foreach (object p in response) { var specialEmployee1 = p as SpecialEmployee; Customer c = p as Customer; if (specialEmployee1 != null) { Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee1.CarsLicensePlate, "Unexpected CarsLicensePlate"); Assert.AreEqual(1, specialEmployee1.BonusLevel, "Unexpected BonusLevel"); personVerified = true; } if (c != null) { Assert.IsTrue(c.Name.EndsWith("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected primitive property"); Assert.IsTrue(c.Auditing.ModifiedBy.Equals("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected complex property"); Assert.IsTrue(c.PrimaryContactInfo.EmailBag.Contains("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected collection property"); customerVerified = true; } } } Assert.IsTrue(personVerified && customerVerified, "Some inner request does not completed correctly"); }
private static void QueryEntitySet(DataServiceContextWrapper <DefaultContainer> contextWrapper) { contextWrapper.Configurations.ResponsePipeline .OnEntryStarted(PipelineEventsTestsHelper.ModifyEntryId_Reading) .OnEntryStarted(PipelineEventsTestsHelper.ModifyEntryEditLink_ReadingStart) .OnEntryEnded(PipelineEventsTestsHelper.ModifyEntryEditLink_ReadingEnd) .OnEntryEnded(PipelineEventsTestsHelper.ModifyEntryAction_Reading) .OnNestedResourceInfoEnded(PipelineEventsTestsHelper.ModifyAssociationLinkUrl_ReadingNavigationLink) .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomer_Materialized); var entryResultsLinq = contextWrapper.CreateQuery <Customer>("Customer").ToArray(); foreach (var customer in entryResultsLinq) { PipelineEventsTestsHelper.VerifyModfiedCustomerEntry(contextWrapper, customer); } var entryResultsExecute = contextWrapper.Execute <Customer>(new Uri("Customer", UriKind.Relative)); foreach (Customer customer in entryResultsExecute) { PipelineEventsTestsHelper.VerifyModfiedCustomerEntry(contextWrapper, customer); } var customerQuery = contextWrapper.CreateQuery <Customer>("Customer"); DataServiceCollection <Customer> entryResultsCollection = new DataServiceCollection <Customer>(customerQuery); foreach (Customer customer in entryResultsCollection) { PipelineEventsTestsHelper.VerifyModfiedCustomerEntry(contextWrapper, customer); } }
private static void DataServiceCollectionSubQueryTrackingItems( DataServiceContextWrapper <DefaultContainer> contextWrapper) { var query = from p in contextWrapper.Context.Customer where p.Name != null select new Customer() { Name = p.Name, Orders = new DataServiceCollection <Order>( from r in p.Orders select new Order() { OrderId = r.OrderId, CustomerId = r.CustomerId }) }; var tmpResult0 = query.ToList()[0]; DataServiceCollection <Order> collection = tmpResult0.Orders; // the collection tracking items int tmpCount = collection.Count; collection.Load(contextWrapper.Context.Execute(collection.Continuation)); // for testing newly loaded item's tracking Assert.IsTrue(collection.Count > tmpCount, "Should have loaded another page."); bool someItemNotTracked = false; tmpResult0.Orders.ToList().ForEach(s => { EntityStates state = contextWrapper.Context.GetEntityDescriptor(s).State; s.CustomerId = s.CustomerId + 1; state = contextWrapper.Context.GetEntityDescriptor(s).State; someItemNotTracked = (state == EntityStates.Unchanged) || someItemNotTracked; }); Assert.IsFalse(someItemNotTracked, "All items should have been tracked."); }
public static void AddConcrete(this DataServiceContextWrapper context, Type concreteType, object instance) { typeof(BaseEntityType).GetProperty("Context", BindingFlags.Instance | BindingFlags.NonPublic) .SetValue(instance, context); context.AddObject(concreteType.Name + "s", instance); }
public void UpdateObjectTestAction(ODataFormat format, MergeOption mergeOption, SaveChangesOptions saveChangesOption) { DataServiceContextWrapper <DefaultContainer> contextWrapper = this.CreateContext(); contextWrapper.Context.MergeOption = mergeOption; contextWrapper.Context.AddAndUpdateResponsePreference = DataServiceResponsePreference.IncludeContent; if (format == ODataFormat.Json) { contextWrapper.Format.UseJson(); } Customer customer = PipelineEventsTestsHelper.CreateNewCustomer(200); contextWrapper.AddObject("Customer", customer); contextWrapper.SaveChanges(); contextWrapper.Configurations.RequestPipeline .OnEntryStarting(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Writing) .OnEntryEnding(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntry_Writing); customer.Name = "update"; contextWrapper.UpdateObject(customer); contextWrapper.SaveChanges(saveChangesOption); Assert.IsTrue(customer.Name.EndsWith("UpdatedODataEntryPropertyValue"), "Unexpected primitive property"); Assert.IsTrue(customer.Auditing.ModifiedBy.Equals("UpdatedODataEntryPropertyValue"), "Unexpected complex property"); Assert.IsTrue(customer.PrimaryContactInfo.EmailBag.Contains("UpdatedODataEntryPropertyValue")); contextWrapper.DeleteObject(customer); contextWrapper.SaveChanges(); }
private static void QueryEntitySetExecuteAsync(DataServiceContextWrapper<DefaultContainer> contextWrapper) { contextWrapper.Configurations.ResponsePipeline .OnEntryStarted(PipelineEventsTestsHelper.ModifyEntryId_Reading) .OnEntryStarted(PipelineEventsTestsHelper.ModifyEntryEditLink_ReadingStart) .OnEntryEnded(PipelineEventsTestsHelper.ModifyEntryEditLink_ReadingEnd) .OnEntryEnded(PipelineEventsTestsHelper.ModifyEntryAction_Reading) .OnNavigationLinkEnded(PipelineEventsTestsHelper.ModifyAssociationLinkUrl_ReadingNavigationLink) .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomer_Materialized); // cover this for Json if (contextWrapper.Format.ODataFormat == ODataFormat.Atom) { contextWrapper.Configurations.ResponsePipeline.OnNavigationLinkStarted( PipelineEventsTestsHelper.ModifyLinkName_ReadingNavigationLink); } IEnumerable<Customer> customers = null; IAsyncResult r = contextWrapper.BeginExecute<Customer>( new Uri("Customer", UriKind.Relative), result => { customers = contextWrapper.EndExecute<Customer>(result); }, null); while (!r.IsCompleted) { Thread.Sleep(1000); } foreach (Customer customer in customers) { PipelineEventsTestsHelper.VerifyModfiedCustomerEntry(contextWrapper, customer); } }
private static void AddUpdateBatchTest(DataServiceContextWrapper <DefaultContainer> contextWrapper) { contextWrapper.Configurations.RequestPipeline .OnEntryStarting(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Writing) .OnEntryEnding(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntry_Writing); Customer customer = PipelineEventsTestsHelper.CreateNewCustomer(300); contextWrapper.AddObject("Customer", customer); Customer customer2 = PipelineEventsTestsHelper.CreateNewCustomer(301); contextWrapper.AddObject("Customer", customer2); Order order = PipelineEventsTestsHelper.CreateNewOrder(300); contextWrapper.AddRelatedObject(customer, "Orders", order); contextWrapper.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset); Assert.IsTrue(customer.Name.EndsWith("UpdatedODataEntryPropertyValue"), "Unexpected primitive property"); Assert.IsTrue(customer2.Name.EndsWith("UpdatedODataEntryPropertyValue"), "Unexpected primitive property"); contextWrapper.DeleteObject(customer); contextWrapper.DeleteObject(customer2); contextWrapper.DeleteObject(order); contextWrapper.SaveChanges(); }
public StreamFetcher(DataServiceContextWrapper context, EntityBase entity, string propertyName, Client.DataServiceStreamLink link) { _context = context; _entity = entity; _link = link; _propertyName = propertyName; }
private static void QueryEntitySetExecuteAsync(DataServiceContextWrapper <DefaultContainer> contextWrapper) { contextWrapper.Configurations.ResponsePipeline .OnEntryStarted(PipelineEventsTestsHelper.ModifyEntryId_Reading) .OnEntryStarted(PipelineEventsTestsHelper.ModifyEntryEditLink_ReadingStart) .OnEntryEnded(PipelineEventsTestsHelper.ModifyEntryEditLink_ReadingEnd) .OnEntryEnded(PipelineEventsTestsHelper.ModifyEntryAction_Reading) .OnNestedResourceInfoEnded(PipelineEventsTestsHelper.ModifyAssociationLinkUrl_ReadingNavigationLink) .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomer_Materialized); IEnumerable <Customer> customers = null; IAsyncResult r = contextWrapper.BeginExecute <Customer>( new Uri("Customer", UriKind.Relative), result => { customers = contextWrapper.EndExecute <Customer>(result); }, null); while (!r.IsCompleted) { Thread.Sleep(1000); } foreach (Customer customer in customers) { PipelineEventsTestsHelper.VerifyModfiedCustomerEntry(contextWrapper, customer); } }
public static void AddRelatedConcrete(this DataServiceContextWrapper context, object instance, string propName, object relatedInstance) { typeof(BaseEntityType).GetProperty("Context", BindingFlags.Instance | BindingFlags.NonPublic) .SetValue(instance, context); context.AddRelatedObject(instance, propName, relatedInstance); }
public void ExtractMetadataReturnsNullForBadSchema(string schema) { // Act var schemaMetadata = DataServiceContextWrapper.ExtractMetadataFromSchema(schema); // Assert Assert.Null(schemaMetadata); }
private static void QueryEntityInstanceBatchAsync(DataServiceContextWrapper <DefaultContainer> contextWrapper) { contextWrapper.Context.IgnoreMissingProperties = true; contextWrapper.Configurations.ResponsePipeline .OnEntryEnded(PipelineEventsTestsHelper.AddRemovePropertySpecialEmployeeEntry_Reading) .OnEntityMaterialized(PipelineEventsTestsHelper.AddEnumPropertySpecialEmployeeEntity_Materialized) .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Materialized); DataServiceRequest[] requests = new DataServiceRequest[] { contextWrapper.CreateQuery <Person>("Person(-10)"), contextWrapper.CreateQuery <Customer>("Customer"), }; DataServiceResponse responses = null; IAsyncResult r = contextWrapper.BeginExecuteBatch( result => { responses = contextWrapper.EndExecuteBatch(result); }, null, requests); while (!r.IsCompleted) { Thread.Sleep(1000); } bool personVerified = false; bool customerVerified = false; foreach (QueryOperationResponse response in responses) { foreach (object p in response) { SpecialEmployee se1 = p as SpecialEmployee; Customer c = p as Customer; if (se1 != null) { Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", se1.CarsLicensePlate, "Unexpected CarsLicensePlate"); Assert.AreEqual(1, se1.BonusLevel, "Unexpected BonusLevel"); personVerified = true; } if (c != null) { Assert.IsTrue(c.Name.EndsWith("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected primitive property"); Assert.IsTrue(c.Auditing.ModifiedBy.Equals("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected complex property"); Assert.IsTrue(c.PrimaryContactInfo.EmailBag.Contains("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected collection property"); customerVerified = true; } } } Assert.IsTrue(personVerified && customerVerified, "Some inner request does not completed correctly"); }
public static DataServiceContextWrapper WithDefaultResolvers(this DataServiceContextWrapper context, string @namespace) { context.ResolveName = type => context.DefaultResolveNameInternal(type, @namespace, @namespace) ?? type.FullName; context.ResolveType = name => context.DefaultResolveTypeInternal(name, @namespace, @namespace); return(context); }
public void ExtractMetadataReturnsNullForBadSchema(string schema) { // Act var stream = schema == null ? (Stream)null : schema.AsStream(); var schemaMetadata = DataServiceContextWrapper.ExtractMetadataFromSchema(stream); // Assert Assert.Null(schemaMetadata); }
public static DataServiceContextWrapper GetDataServiceContext(string uri) { GetEdmxStringFromMetadataPath(uri + "$metadata"); var context = new DataServiceContextWrapper(new Uri(uri), 0, () => Task.FromResult("")); context.Format.LoadServiceModel = LoadModelFromString; context.Format.UseJson(); return context; }
public static RestShallowObjectFetcher CreateFetcher(this DataServiceContextWrapper context, Type fetcherType, string path) { var instance = Activator.CreateInstance(fetcherType) as RestShallowObjectFetcher; instance.Initialize(context, path); return(instance); }
private DataServiceContextWrapper <DefaultContainer> CreateContextWrapper() { // Return a context based on similar but not exactly matching client types. var contextWrapper = new DataServiceContextWrapper <DefaultContainer>(new DefaultContainer(this.ServiceUri)); contextWrapper.Format.UseJson(); contextWrapper.ResolveName = null; contextWrapper.ResolveType = null; return(contextWrapper); }
public static DataServiceContextWrapper GetDataServiceContext(string uri) { GetEdmxStringFromMetadataPath(uri + "$metadata"); var context = new DataServiceContextWrapper(new Uri(uri), 0, () => Task.FromResult("")); context.Format.LoadServiceModel = LoadModelFromString; context.Format.UseJson(); return(context); }
private static void QueryEntitySetNull(DataServiceContextWrapper <DefaultContainer> contextWrapper) { contextWrapper.Configurations.ResponsePipeline .OnEntryEnded(PipelineEventsTestsHelper.ChangeEntryPropertyToNull_Reading); var entryResultsExecute = contextWrapper.Execute <Customer>(new Uri("Customer", UriKind.Relative)); foreach (Customer customer in entryResultsExecute) { Assert.IsNull(customer.Auditing, "Unexpected property value"); } }
private void InsertNewRowRoundtrip(DataServiceContextWrapper <DefaultContainer> contextWrapper, Row newRow) { Guid newRowId = newRow.Id; contextWrapper.Context.AddToRow(newRow); contextWrapper.SaveChanges(); var retrievedRow = contextWrapper.CreateQuery <Row>("Row").Where(r => r.Id == newRowId).SingleOrDefault(); Assert.IsNotNull(retrievedRow, "Failed to retrieve new row"); AssertAreEqual(newRow, retrievedRow); }
/// <summary> /// Creates a wrapped DataServiceContext for the OData Service. /// </summary> /// <typeparam name="TContext">The context type being wrapped.</typeparam> /// <returns>A wrapped instance of the specified DataServiceContext type.</returns> internal virtual DataServiceContextWrapper <TContext> CreateWrappedContext <TContext>() where TContext : DataServiceContext { var context = this.serviceDescriptor.CreateDataServiceContext(this.serviceWrapper.ServiceUri) as TContext; Assert.NotNull(context); var contextWrapper = new DataServiceContextWrapper <TContext>(context) { UrlKeyDelimiter = DataServiceUrlKeyDelimiter.Parentheses }; return(contextWrapper); }
public Given_a_RestShallowObjectFetcher_Initialized() { _path = Any.String(1); _baseUri = Any.Uri(allowQuerystring: false); _context = new DataServiceContextWrapper(_baseUri, Any.EnumValue <ODataProtocolVersion>(), () => Task.FromResult(Any.String())); _fetcher = new TestRestShallowObjectFetcher(); _fetcher.Initialize(_context, _path); }
public void When_the_path_has_a_trailing_slash_GetUrl_returns_the_path_appended_to_the_Context_base_uri_with_a_single_slash() { var baseUriString = Any.Uri(allowQuerystring: false).AbsoluteUri.TrimEnd('/'); var context = new DataServiceContextWrapper(new Uri(baseUriString + "/"), Any.EnumValue <ODataProtocolVersion>(), () => Task.FromResult(Any.String())); var fetcher = new TestRestShallowObjectFetcher(); fetcher.Initialize(context, _path); fetcher.GetUrl().AbsoluteUri .Should().Be(new Uri(baseUriString + "/" + _path).AbsoluteUri); }
private void UpdateRowRoundtrip(DataServiceContextWrapper <DefaultContainer> contextWrapper, Guid rowId, Action <Row> updateRow) { Row testRow = contextWrapper.Context.Row.Where(r => r.Id == rowId).Single(); updateRow(testRow); contextWrapper.UpdateObject(testRow); contextWrapper.SaveChanges(); var retrievedRow = contextWrapper.CreateQuery <Row>("Row").Where(r => r.Id == rowId).SingleOrDefault(); Assert.IsNotNull(retrievedRow, "Failed to retrieve updated row"); AssertAreEqual(testRow, retrievedRow); }
/// <summary> /// Creates a wrapped DataServiceContext for the OData Service. /// </summary> /// <typeparam name="TContext">The context type being wrapped.</typeparam> /// <returns>A wrapped instance of the specified DataServiceContext type.</returns> internal virtual DataServiceContextWrapper <TContext> CreateWrappedContext <TContext>() where TContext : DataServiceContext { var context = this.serviceDescriptor.CreateDataServiceContext(this.serviceWrapper.ServiceUri) as TContext; Assert.NotNull(context); var contextWrapper = new DataServiceContextWrapper <TContext>(context) { UrlConventions = DataServiceUrlConventions.Default }; return(contextWrapper); }
public void When_the_path_has_a_trailing_slash_GetUrl_returns_the_path_appended_to_the_Context_base_uri_with_a_single_slash() { var baseUriString = Any.Uri(allowQuerystring: false).AbsoluteUri.TrimEnd('/'); var context = new DataServiceContextWrapper(new Uri(baseUriString + "/"), Any.EnumValue<ODataProtocolVersion>(), () => Task.FromResult(Any.String())); var fetcher = new TestRestShallowObjectFetcher(); fetcher.Initialize(context, _path); fetcher.GetUrl().AbsoluteUri .Should().Be(new Uri(baseUriString + "/" + _path).AbsoluteUri); }
public static TestRestShallowObjectFetcher CreateFetcher(DataServiceContextWrapper context, EntityBase entity) { var fetcher = new TestRestShallowObjectFetcher(); Uri fullUri; context.TryGetUri(entity, out fullUri); var baseUri = context.BaseUri.ToString().TrimEnd('/'); var resourcePath = fullUri.ToString().Substring(baseUri.Length + 1); fetcher.Initialize(context, resourcePath); return(fetcher); }
private static void PagingQueryTest(DataServiceContextWrapper <DefaultContainer> contextWrapper) { contextWrapper.Configurations.ResponsePipeline .OnFeedStarted(PipelineEventsTestsHelper.ModifyFeedId_ReadingFeed) .OnFeedEnded(PipelineEventsTestsHelper.ModifyNextlink_ReadingFeed); var entryResultsLinq = contextWrapper.CreateQuery <Customer>("Customer").Execute() as QueryOperationResponse <Customer>; entryResultsLinq.ToArray(); Assert.AreEqual("http://modifyfeedidmodifynextlink/", entryResultsLinq.GetContinuation().NextLinkUri.AbsoluteUri, "Unexpected next link"); }
public Given_a_RestShallowObjectFetcher_Initialized() { _path = Any.String(1); _baseUri = Any.Uri(allowQuerystring: false); _context = new DataServiceContextWrapper(_baseUri, Any.EnumValue<ODataProtocolVersion>(), () => Task.FromResult(Any.String())); _fetcher = new TestRestShallowObjectFetcher(); _fetcher.Initialize(_context, _path); }
public void ExtractMethodNamesFromSchemaFindsMethodNamesAndProperties(string schema, int expectedMethodCount, int expectedProperties, IEnumerable <string> sampleProperties, IEnumerable <string> expectedMethods) { // Act var schemaMetadata = DataServiceContextWrapper.ExtractMetadataFromSchema(schema); // Assert Assert.NotNull(schemaMetadata); Assert.Equal(expectedMethodCount, schemaMetadata.SupportedMethodNames.Count); Assert.Equal(expectedProperties, schemaMetadata.SupportedProperties.Count); Assert.True(schemaMetadata.SupportedProperties.IsSupersetOf(sampleProperties)); Assert.Equal(expectedMethods.ToList(), schemaMetadata.SupportedMethodNames.ToList()); }
public static void VerifyModfiedCustomerEntry(DataServiceContextWrapper<DefaultContainer> contextWrapper, Customer e) { Assert.IsTrue(e.Name.EndsWith("ModifyPropertyValueCustomer_Materialized"), "Property value not updated"); EntityDescriptor descriptor = contextWrapper.GetEntityDescriptor(e); Assert.IsTrue(descriptor.Identity.OriginalString.Contains("ModifyEntryId"), "Wrong Id"); Assert.IsTrue(descriptor.EditLink.AbsoluteUri.Contains("http://myeditlink/ModifyEntryEditLink"), "Wrong EditLink"); Assert.IsTrue(descriptor.OperationDescriptors.Where(op => op.Title == "ModifyEntryAction").Any(), "Action not added"); foreach (var linkInfo in descriptor.LinkInfos) { if (contextWrapper.Format.ODataFormat == ODataFormat.Atom) { Assert.IsTrue(linkInfo.Name.EndsWith("ModifyLinkName"), "Link name not updated"); } if (contextWrapper.Format.ODataFormat == ODataFormat.Json) { // In Jsonlight, navigation link is calculated using edit link after the reading delegates Assert.IsTrue(linkInfo.NavigationLink.AbsoluteUri.StartsWith("http://myeditlink/ModifyEntryEditLink"), "Wrong navigation link"); } Assert.AreEqual("http://modifyassociationlinkurl/", linkInfo.AssociationLink.AbsoluteUri, "AssociationLink not updated"); } }
private static void QueryEntityInstanceExecuteAsync(DataServiceContextWrapper<DefaultContainer> contextWrapper) { contextWrapper.Context.IgnoreMissingProperties = true; contextWrapper.Configurations.ResponsePipeline .OnEntryEnded(PipelineEventsTestsHelper.AddRemovePropertySpecialEmployeeEntry_Reading) .OnEntityMaterialized(PipelineEventsTestsHelper.AddEnumPropertySpecialEmployeeEntity_Materialized) .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Materialized); IEnumerable<SpecialEmployee> specialEmployees = null; IAsyncResult r = contextWrapper.BeginExecute<SpecialEmployee>( new Uri("Person(-10)", UriKind.Relative), result => { specialEmployees = contextWrapper.EndExecute<SpecialEmployee>(result); }, null); while (!r.IsCompleted) { Thread.Sleep(1000); } SpecialEmployee specialEmployee = specialEmployees.Single(); Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee.CarsLicensePlate, "Unexpected CarsLicensePlate"); Assert.AreEqual(1, specialEmployee.BonusLevel, "Unexpected BonusLevel"); }
private static void AddObjectSetLinkTestAsync(DataServiceContextWrapper<DefaultContainer> contextWrapper) { // These delegates are invoked when the client sends a single request for AddObject+SetLink contextWrapper.Configurations.RequestPipeline .OnNavigationLinkStarting(PipelineEventsTestsHelper.ModifyNavigationLink_WritingStart) .OnNavigationLinkEnding(PipelineEventsTestsHelper.ModifyNavigationLink_WritingEnd) .OnEntityReferenceLink(PipelineEventsTestsHelper.ModifyReferenceLink); Customer customer = PipelineEventsTestsHelper.CreateNewCustomer(1300); Customer customer2 = PipelineEventsTestsHelper.CreateNewCustomer(1301); Customer customer3 = PipelineEventsTestsHelper.CreateNewCustomer(1302); Customer customer4 = PipelineEventsTestsHelper.CreateNewCustomer(1303); contextWrapper.AddObject("Customer", customer); contextWrapper.AddObject("Customer", customer2); contextWrapper.AddObject("Customer", customer3); contextWrapper.AddObject("Customer", customer4); IAsyncResult r1 = contextWrapper.BeginSaveChanges( result => { contextWrapper.EndSaveChanges(result); }, null); while (!r1.IsCompleted) { Thread.Sleep(1000); } Order order = PipelineEventsTestsHelper.CreateNewOrder(1300); contextWrapper.AddObject("Order", order); contextWrapper.SetLink(order, "Customer", customer); IAsyncResult r2 = contextWrapper.BeginSaveChanges( result => { contextWrapper.EndSaveChanges(result); }, null); while (!r2.IsCompleted) { Thread.Sleep(1000); } Assert.AreEqual(1300, order.OrderId, "OrderId should not be altered in the pipeline delegates"); Customer relatedCustomer = null; IAsyncResult r3 = contextWrapper.BeginExecute<Customer>( new Uri("Order(1300)/Customer", UriKind.Relative), result => { relatedCustomer = contextWrapper.EndExecute<Customer>(result).Single(); }, null); while (!r3.IsCompleted) { Thread.Sleep(1000); } Assert.AreEqual(1302, relatedCustomer.CustomerId, "Associated CustomerId should be altered in the pipeline delegates"); contextWrapper.DeleteObject(customer); contextWrapper.DeleteObject(customer2); contextWrapper.DeleteObject(customer3); contextWrapper.DeleteObject(customer4); contextWrapper.DeleteObject(order); IAsyncResult r4 = contextWrapper.BeginSaveChanges( result => { contextWrapper.EndSaveChanges(result); }, null); while (!r4.IsCompleted) { Thread.Sleep(1000); } }
private static void CancelRequestTest(DataServiceContextWrapper<DefaultContainer> contextWrapper) { contextWrapper.Configurations.RequestPipeline .OnEntryStarting(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Writing) .OnEntryEnding(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntry_Writing); Customer customer = PipelineEventsTestsHelper.CreateNewCustomer(); contextWrapper.AddObject("Customer", customer); IAsyncResult result = contextWrapper.BeginSaveChanges(null, null); contextWrapper.CancelRequest(result); Assert.IsTrue(customer.Name.EndsWith("ModifyPropertyValueCustomerEntity_Writing"), "Unexpected primitive property"); }
private void ExecuteActions(DataServiceContextWrapper<DefaultContainer> context, IEnumerable<OperationDescriptor> operationDescriptors) { foreach (OperationDescriptor od in operationDescriptors) { context.Execute(od.Target, "POST"); } }
private void InsertNewRowRoundtrip(DataServiceContextWrapper<DefaultContainer> contextWrapper, Row newRow) { Guid newRowId = newRow.Id; contextWrapper.Context.AddToRow(newRow); contextWrapper.SaveChanges(); var retrievedRow = contextWrapper.CreateQuery<Row>("Row").Where(r => r.Id == newRowId).SingleOrDefault(); Assert.IsNotNull(retrievedRow, "Failed to retrieve new row"); AssertAreEqual(newRow, retrievedRow); }
private void UpdateRowRoundtrip(DataServiceContextWrapper<DefaultContainer> contextWrapper, Guid rowId, Action<Row> updateRow) { Row testRow = contextWrapper.Context.Row.Where(r => r.Id == rowId).Single(); updateRow(testRow); contextWrapper.UpdateObject(testRow); contextWrapper.SaveChanges(); var retrievedRow = contextWrapper.CreateQuery<Row>("Row").Where(r => r.Id == rowId).SingleOrDefault(); Assert.IsNotNull(retrievedRow, "Failed to retrieve updated row"); AssertAreEqual(testRow, retrievedRow); }
private void CompareErrors(DataServiceContextWrapper<DefaultContainer>[] contexts, Action<DataServiceContextWrapper<DefaultContainer>> test) { Debug.Assert(contexts.Length == 2); var results = new ResponseDetails[2]; int i = 0; foreach (var context in contexts) { var responseDetails = new ResponseDetails(); try { test(context); } catch (Exception ex) { responseDetails.Exception = ex; } Assert.IsNotNull(responseDetails.Exception, "Expected exception but none was thrown"); responseDetails.StatusCode = this.lastResponseStatusCode; results[i++] = responseDetails; } Assert.AreEqual(results[0].StatusCode, results[1].StatusCode); AssertExceptionsAreEqual(results[0].Exception, results[1].Exception); }
private DataServiceContextWrapper<DefaultContainer> CreateContextWrapper() { // Return a context based on similar but not exactly matching client types. var contextWrapper = new DataServiceContextWrapper<DefaultContainer>(new DefaultContainer(this.ServiceUri)); contextWrapper.Format.UseJson(); contextWrapper.ResolveName = null; contextWrapper.ResolveType = null; return contextWrapper; }
private static void DataServiceCollectionTrackingItems( DataServiceContextWrapper<DefaultContainer> contextWrapper) { var query = from p in contextWrapper.Context.Customer where p.CustomerId > -100000 // try to get many for paging select new Customer() { CustomerId = p.CustomerId, Name = p.Name }; DataServiceCollection<Customer> collection = new DataServiceCollection<Customer>(query); // the collection to track items int tmpCount = collection.Count; collection.Load(contextWrapper.Context.Execute(collection.Continuation)); // for testing newly loaded item's tracking Assert.IsTrue(collection.Count > tmpCount, "Should have loaded another page."); bool someItemNotTracked = false; collection.ToList().ForEach(s => { s.Name = "value to test tracking"; EntityStates state = contextWrapper.Context.GetEntityDescriptor(s).State; someItemNotTracked = (state == EntityStates.Unchanged) || someItemNotTracked; }); Assert.IsFalse(someItemNotTracked, "All items should have been tracked."); }
private static void DataServiceCollectionSubQueryTrackingItems( DataServiceContextWrapper<DefaultContainer> contextWrapper) { var query = from p in contextWrapper.Context.Customer where p.Name != null select new Customer() { Name = p.Name, Orders = new DataServiceCollection<Order>( from r in p.Orders select new Order() { OrderId = r.OrderId, CustomerId = r.CustomerId }) }; var tmpResult0 = query.ToList()[0]; DataServiceCollection<Order> collection = tmpResult0.Orders; // the collection tracking items int tmpCount = collection.Count; collection.Load(contextWrapper.Context.Execute(collection.Continuation)); // for testing newly loaded item's tracking Assert.IsTrue(collection.Count > tmpCount, "Should have loaded another page."); bool someItemNotTracked = false; tmpResult0.Orders.ToList().ForEach(s => { EntityStates state = contextWrapper.Context.GetEntityDescriptor(s).State; s.CustomerId = s.CustomerId + 1; state = contextWrapper.Context.GetEntityDescriptor(s).State; someItemNotTracked = (state == EntityStates.Unchanged) || someItemNotTracked; }); Assert.IsFalse(someItemNotTracked, "All items should have been tracked."); }
private static void MergeProjectionAndQueryOptionTest( DataServiceContextWrapper<DefaultContainer> contextWrapper) { var query = from p in contextWrapper.Context.Product.AddQueryOption("$select", "ProductId") where p.ProductId == -10 select new Product() { Description = p.Description, Photos = p.Photos }; Uri uri = ((DataServiceQuery<Product>)query).RequestUri; Assert.AreEqual("?$expand=Photos&$select=Description,ProductId", uri.Query); Assert.IsTrue(query.ToList().Count == 1); }
private void SetContextWrapper() { contextWrapper = this.CreateWrappedContext<DefaultContainer>(); }
private static void QueryEntityInstanceBatchAsync(DataServiceContextWrapper<DefaultContainer> contextWrapper) { contextWrapper.Context.IgnoreMissingProperties = true; contextWrapper.Configurations.ResponsePipeline .OnEntryEnded(PipelineEventsTestsHelper.AddRemovePropertySpecialEmployeeEntry_Reading) .OnEntityMaterialized(PipelineEventsTestsHelper.AddEnumPropertySpecialEmployeeEntity_Materialized) .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Materialized); DataServiceRequest[] requests = new DataServiceRequest[] { contextWrapper.CreateQuery<Person>("Person(-10)"), contextWrapper.CreateQuery<Customer>("Customer"), }; DataServiceResponse responses = null; IAsyncResult r = contextWrapper.BeginExecuteBatch( result => { responses = contextWrapper.EndExecuteBatch(result); }, null, requests); while (!r.IsCompleted) { Thread.Sleep(1000); } bool personVerified = false; bool customerVerified = false; foreach (QueryOperationResponse response in responses) { foreach (object p in response) { SpecialEmployee se1 = p as SpecialEmployee; Customer c = p as Customer; if (se1 != null) { Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", se1.CarsLicensePlate, "Unexpected CarsLicensePlate"); Assert.AreEqual(1, se1.BonusLevel, "Unexpected BonusLevel"); personVerified = true; } if (c != null) { Assert.IsTrue(c.Name.EndsWith("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected primitive property"); Assert.IsTrue(c.Auditing.ModifiedBy.Equals("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected complex property"); Assert.IsTrue(c.PrimaryContactInfo.EmailBag.Contains("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected collection property"); customerVerified = true; } } } Assert.IsTrue(personVerified && customerVerified, "Some inner request does not completed correctly"); }