/// <summary> /// Instantiates a new Serializer class and calls WriteEntry method on it. /// </summary> /// <param name="dataServiceContext"></param> /// <returns></returns> private static Person SetupSerializerAndCallWriteEntry(DataServiceContext dataServiceContext) { Person person = new Person(); Address address = new Address(); Car car1 = new Car(); person.Cars.Add(car1); person.HomeAddress = address; dataServiceContext.AttachTo("Cars", car1); dataServiceContext.AttachTo("Addresses", address); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = person; var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { new LinkDescriptor(person, "Cars", car1, clientModel), new LinkDescriptor(person, "HomeAddress", address, clientModel) }; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); return person; }
/// <summary> /// Instantiates a new Serializer class and calls WriteEntry method on it. /// </summary> /// <param name="dataServiceContext"></param> /// <returns></returns> private static Person SetupSerializerAndCallWriteEntry(DataServiceContext dataServiceContext) { Person person = new Person(); Address address = new Address(); Car car1 = new Car(); person.Cars.Add(car1); person.HomeAddress = address; dataServiceContext.AttachTo("Cars", car1); dataServiceContext.AttachTo("Addresses", address); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = person; var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { new LinkDescriptor(person, "Cars", car1, clientModel), new LinkDescriptor(person, "HomeAddress", address, clientModel) }; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); return(person); }
public virtual void PostGetUpdateAndDelete(Type entityType, string entitySetName) { // clear respository this.ClearRepository(entitySetName); Random r = new Random(RandomSeedGenerator.GetRandomSeed()); // post new entity to repository var value = InstanceCreator.CreateInstanceOf(entityType, r, new CreatorSettings() { NullValueProbability = 0.0 }); DataServiceContext ctx = WriterClient(new Uri(this.BaseAddress), DataServiceProtocolVersion.V3); ctx.AddObject(entitySetName, value); ctx.SaveChanges(); // get collection of entities from repository ctx = ReaderClient(new Uri(this.BaseAddress), DataServiceProtocolVersion.V3); var entities = ctx.CreateQuery <Vehicle>(entitySetName); var beforeUpdate = entities.ToList().First(); AssertExtension.PrimitiveEqual(value, beforeUpdate); // update entity and verify if it's saved ctx = WriterClient(new Uri(this.BaseAddress), DataServiceProtocolVersion.V3); ctx.AttachTo(entitySetName, beforeUpdate); beforeUpdate.Name = InstanceCreator.CreateInstanceOf <string>(r); ctx.UpdateObject(beforeUpdate); ctx.SaveChanges(); // retrieve the updated entity ctx = ReaderClient(new Uri(this.BaseAddress), DataServiceProtocolVersion.V3); entities = ctx.CreateQuery <Vehicle>(entitySetName); var afterUpdate = entities.Where(e => e.Id == beforeUpdate.Id).First(); Assert.Equal(beforeUpdate.Name, afterUpdate.Name); // delete entity ctx = WriterClient(new Uri(this.BaseAddress), DataServiceProtocolVersion.V3); ctx.AttachTo(entitySetName, afterUpdate); ctx.DeleteObject(afterUpdate); ctx.SaveChanges(); // ensure that the entity has been deleted ctx = ReaderClient(new Uri(this.BaseAddress), DataServiceProtocolVersion.V3); entities = ctx.CreateQuery <Vehicle>(entitySetName); Assert.Equal(0, entities.ToList().Count()); // clear repository this.ClearRepository(entitySetName); }
public void SerializeEnity_TwoNavigationLinksInJsonFormat() { var person = new Person { ID = 100, Name = "Bing", }; var car1 = new Car { ID = 1001 }; var car2 = new Car { ID = 1002 }; DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc")); dataServiceContext.AttachTo("Persons", person); dataServiceContext.AttachTo("Cars", car1); dataServiceContext.AttachTo("Cars", car2); dataServiceContext.AddLink(person, "Cars", car1); dataServiceContext.AddLink(person, "Cars", car2); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = person; entityDescriptor.EditLink = new Uri("http://www.foo.com/custom"); var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { new LinkDescriptor(person, "Cars", car1, clientModel), new LinkDescriptor(person, "Cars", car2, clientModel) }; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); // read result: MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream); stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); payload.Should().Be( "{\"ID\":100,\"Name\":\"Bing\",\"[email protected]\":[\"http://www.odata.org/service.svc/Cars(1001)\",\"http://www.odata.org/service.svc/Cars(1002)\"]}"); }
/// <summary> /// Gets the execution progress of the task. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A function delegate that returns the future result to be available through the Task.</returns> public Task GetExecutionProgressTask(CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(this.Id)) { // The job was not submitted yet. throw new InvalidOperationException(StringTable.InvalidOperationGetExecutionProgressTaskForNotSubmittedJob); } DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext(); dataContext.AttachTo(JobBaseCollection.JobSet, this); return(Task.Factory.StartNew( t => { JobData data = (JobData)t; while (!IsFinalJobState(GetExposedState(data.State))) { Thread.Sleep(JobInterval); cancellationToken.ThrowIfCancellationRequested(); JobState previousState = GetExposedState(data.State); data.JobEntityRefresh(dataContext); if (previousState != GetExposedState(data.State)) { this.OnStateChanged(new JobStateChangedEventArgs(previousState, GetExposedState(data.State))); } } }, this, cancellationToken)); }
/// <summary> /// Cancels the async. /// </summary> /// <returns>A function delegate that returns the future result to be available through the Task.</returns> public Task CancelAsync() { if (string.IsNullOrWhiteSpace(this.Id)) { // The job was not submitted yet. throw new InvalidOperationException(StringTable.InvalidOperationCancelForNotSubmittedJob); } Uri uri = new Uri( string.Format(CultureInfo.InvariantCulture, "/CancelJob?jobid='{0}'", HttpUtility.UrlEncode(Id)), UriKind.Relative); DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext(); dataContext.IgnoreResourceNotFoundException = false; dataContext.AttachTo(JobBaseCollection.JobSet, this); return(dataContext .ExecuteAsync <string>(uri, this) .ContinueWith( t => { t.ThrowIfFaulted(); JobData data = (JobData)t.AsyncState; data.JobEntityRefresh(dataContext); })); }
private static Uri ExecuteAssetDeleteRequest(AssetDeleteOptionsRequestAdapter adapter) { Uri uri = null; var context = new DataServiceContext(new Uri("http://127.0.0.1/" + Guid.NewGuid().ToString())); bool sendingRequestCalled = false; context.SendingRequest2 += delegate(object o, SendingRequest2EventArgs args) { sendingRequestCalled = true; uri = args.RequestMessage.Url; }; try { AssetData asset = new AssetData() { Id = Guid.NewGuid().ToString() }; context.AttachTo("Assets", asset); context.DeleteObject(asset); adapter.Adapt(context); context.SaveChanges(); } catch (DataServiceRequestException ex) { Debug.WriteLine(ex.Message); } Assert.IsTrue(sendingRequestCalled); return(uri); }
private static Uri ExecuteAssetDeleteRequest( AssetDeleteOptionsRequestAdapter adapter) { Uri uri = null; var context = new DataServiceContext(new Uri("http://127.0.0.1/" + Guid.NewGuid().ToString())); bool sendingRequestCalled = false; context.SendingRequest2 += delegate(object o, SendingRequest2EventArgs args) { sendingRequestCalled = true; uri = args.RequestMessage.Url; }; try { AssetData asset = new AssetData() {Id = Guid.NewGuid().ToString()}; context.AttachTo("Assets", asset); context.DeleteObject(asset); adapter.Adapt(context); context.SaveChanges(); } catch (DataServiceRequestException ex) { Debug.WriteLine(ex.Message); } Assert.IsTrue(sendingRequestCalled); return uri; }
private Task <IIngestManifestAsset> CreateAsync(IIngestManifest ingestManifest, IAsset asset, CancellationToken token, Action <IngestManifestAssetData> continueWith) { IngestManifestCollection.VerifyManifest(ingestManifest); DataServiceContext dataContext = _cloudMediaContext.DataContextFactory.CreateDataServiceContext(); var data = new IngestManifestAssetData { ParentIngestManifestId = ingestManifest.Id }; dataContext.AddObject(IngestManifestAssetCollection.EntitySet, data); dataContext.AttachTo(AssetCollection.AssetSet, asset); dataContext.SetLink(data, "Asset", asset); Task <IIngestManifestAsset> task = dataContext.SaveChangesAsync(data).ContinueWith <IIngestManifestAsset>(t => { t.ThrowIfFaulted(); token.ThrowIfCancellationRequested(); IngestManifestAssetData ingestManifestAsset = (IngestManifestAssetData)t.AsyncState; continueWith(ingestManifestAsset); return(ingestManifestAsset); }, TaskContinuationOptions.ExecuteSynchronously); return(task); }
public void ContextShouldCreateStructuredValueOnAttach() { var ctx = new DataServiceContext(new Uri("http://test.org/"), ODataProtocolVersion.V4); ctx.AttachTo("Customers", new Customer()); ctx.Entities[0].EdmValue.Should().BeAssignableTo <ClientEdmStructuredValue>(); }
/// <summary> /// Executes the <see cref="DataDeleteRequest{TEntity}" />. /// </summary> /// <param name="parameters"></param> /// <returns></returns> public override Message Execute(DataRequestParameters parameters) { if (parameters == null) { throw new ArgumentNullException("parameters"); } if (Entities == null || !Entities.Any()) { throw new ArgumentException("Could not execute request because no entities have been set."); } DataServiceContext serviceContext = Resolve(parameters); foreach (TEntity entity in Entities) { if (!serviceContext.Entities.Contains(serviceContext.GetEntityDescriptor(entity))) { serviceContext.AttachTo(parameters.EntitySet, entity); } serviceContext.DeleteObject(entity); } serviceContext.SaveChanges(); return(null); }
public void ClientSerializeGeographyTest_Update() { DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost")); ctx.AttachTo("Entities", testEntity); ctx.UpdateObject(testEntity); ClientSerializeGeographyTest_Validate(ctx); }
public void TestUpdateObject() { var contact = new Contact { Email = "[email protected]", Name = "new name" }; _resourceFinderMock.Setup( resourceFinder => resourceFinder.GetResource(It.IsAny <IQueryable <Contact> >(), typeof(Contact).FullName)) .Returns(contact) .AtMostOnce(); Setup(session => session.Store(It.Is <Contact>(actual => actual == contact))) .AtMostOnce(); Setup(session => session.Commit()) .AtMostOnce(); Playback(() => { var context = new DataServiceContext(ServiceUri); context.AttachTo("Contacts", contact); context.UpdateObject(contact); context.SaveChanges(); }); }
/// <summary> /// Asynchronously deletes this instance. /// </summary> /// <returns>A function delegate that returns the future result to be available through the Task.</returns> public Task DeleteAsync() { DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext(); dataContext.AttachTo(FileSet, this); dataContext.DeleteObject(this); return(dataContext.SaveChangesAsync(this)); }
/// <summary> /// Deletes the manifest asset file asynchronously. /// </summary> /// <returns><see cref="Task"/></returns> public Task DeleteAsync() { DataServiceContext dataContext = _cloudMediaContext.DataContextFactory.CreateDataServiceContext(); dataContext.AttachTo(IngestManifestFileCollection.EntitySet, this); dataContext.DeleteObject(this); return(dataContext.SaveChangesAsync(this)); }
private void ClaimTest(Message testMessage) { DataServiceContext AstoriaTestService = null; AstoriaTestService = GetServiceContext(); AstoriaTestService.UsePostTunneling = true; AstoriaTestService.AttachTo("Messages", testMessage); AstoriaTestService.BeginSaveChanges(PostTestWorkRespose, AstoriaTestService); }
/// <summary> /// Delete this instance of notification endpoint object in asynchronous mode. /// </summary> /// <returns>Task of deleting the notification endpoint.</returns> public Task DeleteAsync() { DataServiceContext dataContext = _cloudMediaContext.DataContextFactory.CreateDataServiceContext(); dataContext.AttachTo(NotificationEndPointCollection.NotificationEndPoints, this); dataContext.DeleteObject(this); return(dataContext.SaveChangesAsync(this)); }
private async Task <DataServiceResponse> UpdateEntity <T>(T from, T to, string entitySetName) { DataServiceContext client = WriterClient(new Uri(BaseAddress), ODataProtocolVersion.V4); client.AttachTo(entitySetName, from); client.UpdateObject(to); return(await client.SaveChangesAsync()); }
private async Task <DataServiceResponse> DeleteEntityAsync <T>(T entity, string entitySetName) { DataServiceContext context = WriterClient(new Uri(BaseAddress), ODataProtocolVersion.V4); context.AttachTo(entitySetName, entity); context.DeleteObject(entity); return(await context.SaveChangesAsync()); }
public void TestCollectionDelete() { var cc = new Contact { Email = "[email protected]", Name = "def" }; var message = new Message { Id = Guid.NewGuid(), CC = new List <Contact> { cc } }; _resourceFinderMock.Setup( resourceFinder => resourceFinder.GetResource(It.IsAny <IQueryable <Message> >(), null)) .Returns(message) .AtMostOnce(); _resourceFinderMock.Setup( resourceFinder => resourceFinder.GetResource(It.IsAny <IQueryable <Contact> >(), null)) .Returns(cc) .AtMostOnce(); Setup(session => session.Store(It.Is <Message>(actual => actual == message && actual.CC.Count == 0))) .AtMostOnce(); Setup(session => session.Commit()) .AtMostOnce(); var context = new DataServiceContext(ServiceUri); Playback(() => { context.AttachTo("Contacts", cc); context.AttachTo("Messages", message); context.DeleteLink(message, "CC", cc); context.SaveChanges(); }); }
public virtual void AddAndRemoveBaseNavigationPropertyInDerivedType() { // clear respository this.ClearRepository("InheritanceTests_Cars"); Random r = new Random(RandomSeedGenerator.GetRandomSeed()); // post new entity to repository CreatorSettings creatorSettings = new CreatorSettings() { NullValueProbability = 0, }; var car = InstanceCreator.CreateInstanceOf <Car>(r, creatorSettings); var vehicle = InstanceCreator.CreateInstanceOf <Vehicle>(r, creatorSettings); DataServiceContext ctx = WriterClient(new Uri(this.BaseAddress), ODataProtocolVersion.V4); ctx.AddObject("InheritanceTests_Cars", car); ctx.AddRelatedObject(car, "BaseTypeNavigationProperty", vehicle); ctx.SaveChangesAsync().Wait(); ctx = ReaderClient(new Uri(this.BaseAddress), ODataProtocolVersion.V4); var cars = ctx.CreateQuery <Car>("InheritanceTests_Cars"); var actual = cars.ExecuteAsync().Result.First(); ctx.LoadPropertyAsync(actual, "BaseTypeNavigationProperty").Wait(); AssertExtension.PrimitiveEqual(vehicle, actual.BaseTypeNavigationProperty[0]); ctx = WriterClient(new Uri(this.BaseAddress), ODataProtocolVersion.V4); ctx.AttachTo("InheritanceTests_Cars", actual); ctx.AttachTo("InheritanceTests_Vehicles", actual.BaseTypeNavigationProperty[0]); ctx.DeleteLink(actual, "BaseTypeNavigationProperty", actual.BaseTypeNavigationProperty[0]); ctx.SaveChangesAsync().Wait(); ctx = ReaderClient(new Uri(this.BaseAddress), ODataProtocolVersion.V4); cars = ctx.CreateQuery <Car>("InheritanceTests_Cars"); actual = cars.ExecuteAsync().Result.First(); ctx.LoadPropertyAsync(actual, "BaseTypeNavigationProperty").Wait(); Assert.Empty(actual.BaseTypeNavigationProperty); this.ClearRepository("InheritanceTests_Cars"); }
public void TestReferenceUpdate() { var message = new Message { Id = Guid.NewGuid(), Body = "Hi!", To = new Contact { Email = "[email protected]" } }; var newContact = new Contact { Email = "[email protected]" }; _resourceFinderMock.Setup( resourceFinder => resourceFinder.GetResource(It.IsAny <IQueryable <Message> >(), null)) .Returns(message) .AtMostOnce(); _resourceFinderMock.Setup( resourceFinder => resourceFinder.GetResource(It.IsAny <IQueryable <Contact> >(), null)) .Returns(newContact) .AtMostOnce(); Setup(session => session.Store(It.Is <Message>(actual => actual == message && actual.To == newContact))) .AtMostOnce(); Setup(session => session.Commit()) .AtMostOnce(); var context = new DataServiceContext(ServiceUri); Playback(() => { context.AttachTo("Contacts", newContact); context.AttachTo("Messages", message); context.SetLink(message, "To", newContact); context.SaveChanges(); }); }
/// <summary> /// Deletes this instance. /// </summary> /// <returns>A function delegate.</returns> public Task DeleteAsync() { ContentKeyBaseCollection.VerifyContentKey(this); DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext(); dataContext.AttachTo(ContentKeyCollection.ContentKeySet, this); dataContext.DeleteObject(this); return(dataContext.SaveChangesAsync(this)); }
public void AttachShouldFailOnNullKeys() { var ctx = new DataServiceContext(new Uri("http://test.org/test")); Action withNullKey = () => ctx.AttachTo("EntitySet1", new SingleKeyType { Property = null }); withNullKey.ShouldThrow <InvalidOperationException>().WithMessage(Strings.Context_NullKeysAreNotSupported("Property")); withNullKey = () => ctx.AttachTo("EntitySet1", new CompositeKeyType { Property1 = null, Property2 = "bar" }); withNullKey.ShouldThrow <InvalidOperationException>().WithMessage(Strings.Context_NullKeysAreNotSupported("Property1")); withNullKey = () => ctx.AttachTo("EntitySet1", new CompositeKeyType { Property1 = "foo", Property2 = null }); withNullKey.ShouldThrow <InvalidOperationException>().WithMessage(Strings.Context_NullKeysAreNotSupported("Property2")); }
/// <summary> /// Asynchronously deletes this asset instance. /// </summary> /// <returns>A function delegate that returns the future result to be available through the Task.</returns> public Task DeleteAsync() { AssetCollection.VerifyAsset(this); DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext(); dataContext.AttachTo(AssetCollection.AssetSet, this); this.InvalidateContentKeysCollection(); dataContext.DeleteObject(this); return(dataContext.SaveChangesAsync(this)); }
void PushResponseToQueue(Message request, Message response) { DataServiceContext AstoriaTestService = null; AstoriaTestService = GetServiceContext(); AstoriaTestService.UsePostTunneling = true; AstoriaTestService.AttachTo("Messages", request); AstoriaTestService.DeleteObject(request); //response.MessageID = 5000; AstoriaTestService.AddObject("Messages", response); AstoriaTestService.BeginSaveChanges(SaveChangesOptions.None, PostTestWorkRespose, AstoriaTestService); }
public void SerializeEnity_NullableEnumProperty() { MyEntity1 myEntity1 = new MyEntity1() { ID = 2, MyColorValue = null, MyFlagsColorValue = MyFlagsColor.Blue, ComplexValue1Value = new ComplexValue1() { MyColorValue = MyColor.Green, MyFlagsColorValue = MyFlagsColor.Red }, MyFlagsColorCollection1 = new List <MyFlagsColor>() { MyFlagsColor.Blue, MyFlagsColor.Red, MyFlagsColor.Red }, MyColorCollection = new List <MyColor?> { MyColor.Green, null } }; DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc")); dataServiceContext.EnableAtom = true; dataServiceContext.Format.UseAtom(); dataServiceContext.AttachTo("MyEntitySet1", myEntity1); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = myEntity1; var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { }; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); // read result: MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream); stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); payload = Regex.Replace(payload, "<updated>[^<]*</updated>", ""); payload.Should().Be( "{\"ComplexValue1Value\":{\"MyColorValue\":\"Green\",\"MyFlagsColorValue\":\"Red\",\"StringValue\":null},\"ID\":2,\"MyColorCollection\":[\"Green\",null],\"MyColorValue\":null,\"MyFlagsColorCollection1\":[\"Blue\",\"Red\",\"Red\"],\"MyFlagsColorValue\":\"Blue\"}"); }
/// <summary> /// Creates the locator async. /// </summary> /// <param name="locatorType">Type of the locator.</param> /// <param name="asset">The asset.</param> /// <param name="accessPolicy">The access policy.</param> /// <param name="startTime">The start time.</param> /// <returns>A function delegate that returns the future result to be available through the Task<ILocator>.</returns> public Task <ILocator> CreateLocatorAsync(LocatorType locatorType, IAsset asset, IAccessPolicy accessPolicy, DateTime?startTime) { AccessPolicyBaseCollection.VerifyAccessPolicy(accessPolicy); AssetCollection.VerifyAsset(asset); AssetData assetData = (AssetData)asset; LocatorData locator = new LocatorData { AccessPolicy = (AccessPolicyData)accessPolicy, Asset = assetData, Type = (int)locatorType, StartTime = startTime, }; locator.InitCloudMediaContext(this._cloudMediaContext); DataServiceContext dataContext = this.DataContextFactory.CreateDataServiceContext(); dataContext.AttachTo(AssetCollection.AssetSet, asset); dataContext.AttachTo(AccessPolicyBaseCollection.AccessPolicySet, accessPolicy); dataContext.AddObject(LocatorSet, locator); dataContext.SetLink(locator, AccessPolicyPropertyName, accessPolicy); dataContext.SetLink(locator, AssetPropertyName, asset); return(dataContext .SaveChangesAsync(locator) .ContinueWith <ILocator>( t => { t.ThrowIfFaulted(); assetData.InvalidateLocatorsCollection(); return (LocatorData)t.AsyncState; }, TaskContinuationOptions.ExecuteSynchronously)); }
/// <summary> /// Asynchronously saves this instance. /// </summary> /// <returns>A function delegate that returns the future result to be available through the Task.</returns> public Task UpdateAsync() { if (this.Asset.State != AssetState.Initialized) { throw new NotSupportedException(StringTable.NotSupportedFileInfoSave); } DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext(); dataContext.AttachTo(FileSet, this); dataContext.UpdateObject(this); return(dataContext.SaveChangesAsync(this)); }
public static T CreateEntity <T>(DataServiceContext ctx, string entitySetName, EntityStates state, DataServiceQuery <T> query) where T : class, new() { T entity = null; try { switch (state) { case EntityStates.Added: entity = new T(); ctx.AddObject(entitySetName, entity); break; case EntityStates.Deleted: entity = CreateEntity(ctx, entitySetName, EntityStates.Unchanged, query); ctx.DeleteObject(entity); break; case EntityStates.Detached: entity = query.Execute().Single(); Assert.AreEqual(MergeOption.NoTracking != ctx.MergeOption, ctx.Detach(entity)); break; case EntityStates.Unchanged: entity = query.Execute().Single(); if (MergeOption.NoTracking == ctx.MergeOption) { ctx.AttachTo(entitySetName, entity); } break; case EntityStates.Modified: entity = CreateEntity(ctx, entitySetName, EntityStates.Unchanged, query); ctx.UpdateObject(entity); break; default: Assert.Fail(String.Format("unexpected state encountered: {0}", state)); break; } } catch (Exception ex) { Assert.Fail("{0}", ex); } return(entity); }
/// <summary> /// Asynchronously deletes this <see cref="IJobTemplate"/>. /// </summary> /// <returns>A function delegate that returns the future result to be available through the Task.</returns> public Task DeleteAsync() { if (string.IsNullOrWhiteSpace(this.Id)) { // The job template was not saved. throw new InvalidOperationException(StringTable.InvalidOperationDeleteForNotSavedJobTemplate); } DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext(); dataContext.AttachTo(JobTemplateBaseCollection.JobTemplateSet, this); dataContext.DeleteObject(this); return(dataContext.SaveChangesAsync(this)); }
/// <summary> /// Asynchronously updates this asset instance. /// </summary> /// <returns>A function delegate that returns the future result to be available through the Task.</returns> public Task UpdateAsync() { AssetCollection.VerifyAsset(this); DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext(); dataContext.AttachTo(AssetCollection.AssetSet, this); dataContext.UpdateObject(this); return(dataContext.SaveChangesAsync(this).ContinueWith <IAsset>( t => { t.ThrowIfFaulted(); AssetData data = (AssetData)t.AsyncState; return data; })); }
public void ContextShouldCreateStructuredValueOnAttach() { var ctx = new DataServiceContext(new Uri("http://test.org/"), ODataProtocolVersion.V4); ctx.AttachTo("Customers", new Customer()); ctx.Entities[0].EdmValue.Should().BeAssignableTo<ClientEdmStructuredValue>(); }
private static void AttachAndLog(StringBuilder output, DataServiceContext ctx, string entitySetName, object entity) { try { ctx.AttachTo(entitySetName, entity); EntityDescriptor entityDescriptor = ctx.Entities[0]; entityDescriptor.Identity.Should().Be(entityDescriptor.EditLink.AbsoluteUri); output.AppendLine(entityDescriptor.EditLink.OriginalString); ctx.Detach(entity); } catch (Exception e) { var exception = e; while (exception != null) { output.Append(exception.GetType().FullName); output.Append(": "); output.AppendLine(exception.Message); exception = exception.InnerException; } } }
public void AttachShouldFailOnNullKeys() { var ctx = new DataServiceContext(new Uri("http://test.org/test")); Action withNullKey = () => ctx.AttachTo("EntitySet1", new SingleKeyType { Property = null }); withNullKey.ShouldThrow<InvalidOperationException>().WithMessage(Strings.Context_NullKeysAreNotSupported("Property")); withNullKey = () => ctx.AttachTo("EntitySet1", new CompositeKeyType { Property1 = null, Property2 = "bar" }); withNullKey.ShouldThrow<InvalidOperationException>().WithMessage(Strings.Context_NullKeysAreNotSupported("Property1")); withNullKey = () => ctx.AttachTo("EntitySet1", new CompositeKeyType { Property1 = "foo", Property2 = null }); withNullKey.ShouldThrow<InvalidOperationException>().WithMessage(Strings.Context_NullKeysAreNotSupported("Property2")); }
/// <summary> /// Applies this state to the specfied <paramref name="target"/> such that after invocation, /// the target in the given <paramref name="context"/> is in this state. /// </summary> /// <param name="context">Context to apply changes to.</param> /// <param name="target">Target to change state on.</param> /// <param name="entitySetName">Name of entity set (necessary for certain transitions).</param> public void ApplyToObject(DataServiceContext context, object target, string entitySetName) { if (context == null) { throw new ArgumentNullException("context"); } if (target == null) { throw new ArgumentNullException("target"); } EntityStates current = GetStateForEntity(context, target); if (current == this.state) { return; } switch (this.state) { case EntityStates.Added: if (current != EntityStates.Detached) { context.Detach(target); } context.AddObject(entitySetName, target); break; case EntityStates.Detached: context.Detach(target); break; case EntityStates.Deleted: if (current == EntityStates.Detached) { context.AttachTo(entitySetName, target); } context.DeleteObject(target); break; case EntityStates.Modified: if (current == EntityStates.Detached) { context.AttachTo(entitySetName, target); } context.UpdateObject(target); break; case EntityStates.Unchanged: if (current != EntityStates.Detached) { context.Detach(target); } context.AttachTo(entitySetName, target); break; } }
public void SerializeEnity_TwoNavigationLinksInJsonFormat() { var person = new Person { ID = 100, Name = "Bing", }; var car1 = new Car { ID = 1001 }; var car2 = new Car { ID = 1002 }; DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc")); dataServiceContext.AttachTo("Persons", person); dataServiceContext.AttachTo("Cars", car1); dataServiceContext.AttachTo("Cars", car2); dataServiceContext.AddLink(person, "Cars", car1); dataServiceContext.AddLink(person, "Cars", car2); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = person; entityDescriptor.EditLink = new Uri("http://www.foo.com/custom"); var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { new LinkDescriptor(person, "Cars", car1, clientModel), new LinkDescriptor(person, "Cars", car2, clientModel)}; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); // read result: MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream); stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); payload.Should().Be( "{\"ID\":100,\"Name\":\"Bing\",\"[email protected]\":[\"http://www.odata.org/service.svc/Cars(1001)\",\"http://www.odata.org/service.svc/Cars(1002)\"]}"); }
private void ProcessForeignKeys(DataServiceContext dataServiceContext, object dataObject, IDictionary values) { foreach (string key in values.Keys) { // Check if it looks like a FK, e.g. Category.CategoryID string[] parts = key.Split('.'); if (parts.Length != 2) continue; // Get the name of the entity ref property, e.g. Category string entityRefPropertyName = parts[0]; // Get the PropertyInfo for the entity ref property PropertyInfo propInfo = dataObject.GetType().GetProperty(entityRefPropertyName); object entityRefObject = null; if (values[key] != null) { // Create an 'empty' related entity, e.g a Category entityRefObject = Activator.CreateInstance(propInfo.PropertyType); // Set the PK in the related entity, e.g. set the CategoryID in the Category PropertyInfo subPropInfo = propInfo.PropertyType.GetProperty(parts[1]); subPropInfo.SetValue( entityRefObject, Convert.ChangeType(values[key], subPropInfo.PropertyType), null); } // Find the entity set property for the association table e.g. Categories PropertyInfo entitySetProp = DataServiceUtilities.FindEntitySetProperty( dataServiceContext.GetType(), propInfo.PropertyType); // Attach the related entity and set it as the link on the main entity if (entitySetProp != null) { if (entityRefObject != null) { dataServiceContext.AttachTo(entitySetProp.Name, entityRefObject); } dataServiceContext.SetLink(dataObject, entityRefPropertyName, entityRefObject); } } }
public void SerializeEnity_NullableEnumProperty() { MyEntity1 myEntity1 = new MyEntity1() { ID = 2, MyColorValue = null, MyFlagsColorValue = MyFlagsColor.Blue, ComplexValue1Value = new ComplexValue1() { MyColorValue = MyColor.Green, MyFlagsColorValue = MyFlagsColor.Red }, MyFlagsColorCollection1 = new List<MyFlagsColor>() { MyFlagsColor.Blue, MyFlagsColor.Red, MyFlagsColor.Red }, MyColorCollection = new List<MyColor?> { MyColor.Green, null } }; DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc")); dataServiceContext.EnableAtom = true; dataServiceContext.Format.UseAtom(); dataServiceContext.AttachTo("MyEntitySet1", myEntity1); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = myEntity1; var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { }; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); // read result: MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream); stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); payload = Regex.Replace(payload, "<updated>[^<]*</updated>", ""); payload.Should().Be( "{\"ComplexValue1Value\":{\"MyColorValue\":\"Green\",\"MyFlagsColorValue\":\"Red\",\"StringValue\":null},\"ID\":2,\"MyColorCollection\":[\"Green\",null],\"MyColorValue\":null,\"MyFlagsColorCollection1\":[\"Blue\",\"Red\",\"Red\"],\"MyFlagsColorValue\":\"Blue\"}"); }
public void SerializeEnity_EnumProperty() { MyEntity1 myEntity1 = new MyEntity1() { ID = 2, MyColorValue = MyColor.Yellow, MyFlagsColorValue = MyFlagsColor.Blue, ComplexValue1Value = new ComplexValue1() { MyColorValue = MyColor.Green, MyFlagsColorValue = MyFlagsColor.Red }, MyFlagsColorCollection1 = new List<MyFlagsColor>() { MyFlagsColor.Blue, MyFlagsColor.Red, MyFlagsColor.Red }, MyColorCollection = new List<MyColor?>() }; DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc")); dataServiceContext.EnableAtom = true; dataServiceContext.Format.UseAtom(); dataServiceContext.AttachTo("MyEntitySet1", myEntity1); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); headers.SetHeader("Content-Type", "application/atom+xml;odata.metadata=minimal"); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = myEntity1; var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { }; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); // read result: MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream); stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); payload = Regex.Replace(payload, "<updated>[^<]*</updated>", ""); payload.Should().Be( "<?xml version=\"1.0\" encoding=\"utf-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\" " + "xmlns:d=\"http://docs.oasis-open.org/odata/ns/data\" xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\" " + "xmlns:georss=\"http://www.georss.org/georss\" xmlns:gml=\"http://www.opengis.net/gml\">" + "<id />" + "<title />" + //"<updated>2013-11-11T19:29:54Z</updated>" + "<author><name /></author>" + "<content type=\"application/xml\">" + "<m:properties>" + "<d:ComplexValue1Value>" + "<d:MyColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyColor\">Green</d:MyColorValue>" + "<d:MyFlagsColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyFlagsColor\">Red</d:MyFlagsColorValue>" + "<d:StringValue m:null=\"true\" />" + "</d:ComplexValue1Value>" + "<d:ID m:type=\"Int64\">2</d:ID>" + "<d:MyColorCollection />" + "<d:MyColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyColor\">Yellow</d:MyColorValue>" + "<d:MyFlagsColorCollection1>" + "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Blue</m:element>" + "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Red</m:element>" + "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Red</m:element>" + "</d:MyFlagsColorCollection1>" + "<d:MyFlagsColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyFlagsColor\">Blue</d:MyFlagsColorValue>" + "</m:properties>" + "</content>" + "</entry>"); }
private void InnerSubmit(DataServiceContext dataContext) { if (!string.IsNullOrWhiteSpace(this.TemplateId)) { dataContext.AddObject(JobBaseCollection.JobSet, this); foreach (IAsset asset in this.InputMediaAssets) { AssetData target = asset as AssetData; if (target == null) { throw new ArgumentException(StringTable.ErrorInputTypeNotSupported); } dataContext.AttachTo(AssetCollection.AssetSet, asset); dataContext.AddLink(this, InputMediaAssetsPropertyName, target); } } else { X509Certificate2 certToUse = null; Verify(this); dataContext.AddObject(JobBaseCollection.JobSet, this); List<AssetData> inputAssets = new List<AssetData>(); AssetNamingSchemeResolver<AssetData, OutputAsset> assetNamingSchemeResolver = new AssetNamingSchemeResolver<AssetData, OutputAsset>(inputAssets); foreach (ITask task in ((IJob)this).Tasks) { Verify(task); TaskData taskData = (TaskData)task; if (task.Options.HasFlag(TaskOptions.ProtectedConfiguration)) { ProtectTaskConfiguration(taskData, ref certToUse, dataContext); } taskData.TaskBody = CreateTaskBody(assetNamingSchemeResolver, task.InputAssets.ToArray(), task.OutputAssets.ToArray()); taskData.InputMediaAssets.AddRange(task.InputAssets.OfType<AssetData>().ToArray()); taskData.OutputMediaAssets.AddRange( task.OutputAssets .OfType<OutputAsset>() .Select( c => { AssetData assetData = new AssetData { Name = c.Name, Options = (int)c.Options, AlternateId = c.AlternateId }; assetData.InitCloudMediaContext(this._cloudMediaContext); return assetData; }) .ToArray()); dataContext.AddRelatedObject(this, TasksPropertyName, taskData); } foreach (IAsset asset in inputAssets) { dataContext.AttachTo(AssetCollection.AssetSet, asset); dataContext.AddLink(this, InputMediaAssetsPropertyName, asset); } } }