public void EFFK_1To1_BasicInsertAndBind_Batch_ChangedUriCompositionRulesOnServer()
        {
            // Fix URI composition in Astoria for V3 payloads
            ctx            = new DataServiceContext(web.ServiceRoot, Microsoft.OData.Client.ODataProtocolVersion.V4);
            ctx.EnableAtom = true;
            ctx.Format.UseAtom();
            // Create new office type
            EFFKClient.Office o = new EFFKClient.Office()
            {
                ID = 1, BuildingName = "Building 35", FloorNumber = 2, OfficeNumber = 2173
            };
            ctx.AddObject("CustomObjectContext.Offices", o);

            // create new employee type
            EFFKClient.Worker e = new EFFKClient.Worker()
            {
                ID = 1, FirstName = "Pratik", LastName = "Patel"
            };
            ctx.AddObject("CustomObjectContext.Workers", e);

            // Establish relationship between employee and office
            ctx.SetLink(o, "Worker", e);
            ctx.SetLink(e, "Office", o);
            ctx.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);

            // clean the context
            ctx.DeleteObject(e);
            ctx.DeleteObject(o);
            ctx.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);
        }
Exemple #2
0
        public virtual void RemoveRow(int rowIndex)
        {
            if (DataServiceContext == null || PrimaryKey == string.Empty)
            {
                return;
            }
            object cellValue = Grid.GetFocusedRowCellValue(PrimaryKey);

            if (cellValue == null)
            {
                return;
            }
            string stringCellValue = cellValue.ToString();
            var    en = DataServiceContext.Entities.GetEnumerator();

            while (en.MoveNext())
            {
                if (en.Current.Identity.EndsWith(string.Format("({0})", stringCellValue)))
                {
                    DataServiceContext.DeleteObject(en.Current.Entity);
                    DataServiceContext.SaveChanges();
                    UpdateDataSource();
                    break;
                }
            }
        }
 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;
 }
Exemple #4
0
        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);
        }
Exemple #5
0
        /// <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 TestDeleteObject()
        {
            var contact = new Contact {
                Email = "[email protected]", Name = "abc"
            };

            _resourceFinderMock.Setup(
                resourceFinder => resourceFinder.GetResource(It.IsAny <IQueryable <Contact> >(), null))
            .Returns(contact)
            .AtMostOnce();

            Setup(session => session.Delete(It.Is <Contact>(actual => actual == contact)))
            .AtMostOnce();

            Setup(session => session.Commit())
            .AtMostOnce();

            Playback(() =>
            {
                var context = new DataServiceContext(ServiceUri);
                context.AttachTo("Contacts", contact);
                context.DeleteObject(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));
        }
        /// <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));
        }
Exemple #10
0
        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());
        }
Exemple #11
0
        public void DeleteItem()
        {
            DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost/Chapter9/MovieService.svc"));

            MovieService.Film FilmToDelete =
                ctx.Execute <MovieService.Film>(new Uri("Films(1)", UriKind.Relative)).First();
            ctx.DeleteObject(FilmToDelete);
            ctx.SaveChanges();
        }
Exemple #12
0
        protected override void RemoveItem(int index)
        {
            if (context != null && this.Count > index)
            {
                context.DeleteObject(this[index]);
            }

            base.RemoveItem(index);
        }
        /// <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));
        }
        //<snippetCustomersOrdersDeleteRelated>
        // Method that is called when the CollectionChanged event is handled.
        private bool OnCollectionChanged(
            EntityCollectionChangedParams entityCollectionChangedinfo)
        {
            if (entityCollectionChangedinfo.Action ==
                NotifyCollectionChangedAction.Remove)
            {
                // Delete the related items when an order is deleted.
                if (entityCollectionChangedinfo.TargetEntity.GetType() == typeof(Order))
                {
                    // Get the context and object from the supplied parameter.
                    DataServiceContext context = entityCollectionChangedinfo.Context;
                    Order deletedOrder         = entityCollectionChangedinfo.TargetEntity as Order;

                    if (deletedOrder.Order_Details.Count == 0)
                    {
                        // Load the related OrderDetails.
                        context.LoadProperty(deletedOrder, "Order_Details");
                    }

                    // Delete the order and its related items;
                    foreach (Order_Detail item in deletedOrder.Order_Details)
                    {
                        context.DeleteObject(item);
                    }

                    // Delete the order and then return true since the object is already deleted.
                    context.DeleteObject(deletedOrder);

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                // Use the default behavior.
                return(false);
            }
        }
Exemple #15
0
        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);
        }
        /// <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));
        }
Exemple #17
0
        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 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));
        }
Exemple #20
0
        public void CRUDEntitySetShouldWork()
        {
            Random r             = new Random(RandomSeedGenerator.GetRandomSeed());
            var    entitySetName = "UnicodeRouteTests_Todoü";
            var    uri           = new Uri(this.BaseAddress + "/odataü");
            // post new entity to repository
            var value = InstanceCreator.CreateInstanceOf <UnicodeRouteTests_Todoü>(r);
            var ctx   = new DataServiceContext(uri, DataServiceProtocolVersion.V3);

            ctx.AddObject(entitySetName, value);
            ctx.SaveChanges();

            // get collection of entities from repository
            ctx = new DataServiceContext(uri, DataServiceProtocolVersion.V3);
            IEnumerable <UnicodeRouteTests_Todoü> entities = ctx.CreateQuery <UnicodeRouteTests_Todoü>(entitySetName);
            var beforeUpdate = entities.ToList().First();

            AssertExtension.PrimitiveEqual(value, beforeUpdate);

            // update entity and verify if it's saved
            ctx = new DataServiceContext(uri, DataServiceProtocolVersion.V3);
            ctx.AttachTo(entitySetName, beforeUpdate);
            beforeUpdate.Nameü = InstanceCreator.CreateInstanceOf <string>(r);

            ctx.UpdateObject(beforeUpdate);
            ctx.SaveChanges();
            ctx      = new DataServiceContext(uri, DataServiceProtocolVersion.V3);
            entities = ctx.CreateQuery <UnicodeRouteTests_Todoü>(entitySetName);
            var afterUpdate = entities.ToList().First();

            AssertExtension.PrimitiveEqual(beforeUpdate, afterUpdate);
            //var afterUpdate = entities.Where(FilterByPk(entityType, GetIDValue(beforeUpdate))).First();

            var response = ctx.LoadProperty(afterUpdate, "Nameü");

            Assert.Equal(200, response.StatusCode);

            // delete entity
            ctx = new DataServiceContext(uri, DataServiceProtocolVersion.V3);
            ctx.AttachTo(entitySetName, afterUpdate);
            ctx.DeleteObject(afterUpdate);
            ctx.SaveChanges();
            ctx      = new DataServiceContext(uri, DataServiceProtocolVersion.V3);
            entities = ctx.CreateQuery <UnicodeRouteTests_Todoü>(entitySetName);
            Assert.Equal(0, entities.ToList().Count());
        }
Exemple #21
0
 public virtual void RemoveSelectedRows()
 {
     int[] selectedRowsHandles = Grid.GetSelectedRowHandles();
     if (selectedRowsHandles != null || selectedRowsHandles.Length > 0)
     {
         List <object> rowKeys = new List <object>();
         foreach (int index in selectedRowsHandles)
         {
             rowKeys.Add(Grid.GetCellValue(index, PrimaryKey));
         }
         foreach (object cellValue in rowKeys)
         {
             var en = DataServiceContext.Entities.GetEnumerator();
             if (cellValue == null)
             {
                 continue;
             }
             string stringCellValue = cellValue.ToString();
             int    currIndex       = 0;
             while (en.MoveNext())
             {
                 if (en.Current.Identity.EndsWith(string.Format("({0})", stringCellValue)))
                 {
                     DataServiceContext.DeleteObject(en.Current.Entity);
                 }
                 currIndex++;
             }
             DataServiceContext.SaveChanges();
             UpdateDataSource();
         }
     }
     else if (Grid.CurrentItem != null)
     {
         RemoveRow();
     }
 }
        /// <summary>
        /// Asynchronously revokes the specified Locator, denying any access it provided.
        /// </summary>
        /// <returns>A function delegate that returns the future result to be available through the Task&lt;ILocator&gt;.</returns>
        public Task DeleteAsync()
        {
            LocatorBaseCollection.VerifyLocator(this);

            DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext();

            dataContext.AttachTo(LocatorBaseCollection.LocatorSet, this);
            dataContext.DeleteObject(this);
            var cloudContext = this._cloudMediaContext;

            return(dataContext
                   .SaveChangesAsync(this)
                   .ContinueWith(
                       t =>
            {
                t.ThrowIfFaulted();

                LocatorData data = (LocatorData)t.AsyncState;

                if (cloudContext != null)
                {
                    var cloudContextAsset = (AssetData)cloudContext.Assets.Where(c => c.Id == data.AssetId).FirstOrDefault();
                    if (cloudContextAsset != null)
                    {
                        cloudContextAsset.InvalidateLocatorsCollection();
                    }
                }


                if (data.Asset != null)
                {
                    data.Asset.InvalidateLocatorsCollection();
                }
            },
                       TaskContinuationOptions.ExecuteSynchronously));
        }
        public void UpdateNamedStreamOnDeletedEntity()
        {
            // Calling SetSaveStream on deleted entity is not supported
            // Populate the context with a single customer instance
            string payload = AtomParserTests.AnyEntry(
                id: Id,
                properties: Properties,
                links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType));

            using (PlaybackService.OverridingPlayback.Restore())
            {
                PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                context.EnableAtom = true;
                DataServiceQuery<Customer> q = (DataServiceQuery<Customer>)context.CreateQuery<Customer>("Customers").Where(c1 => c1.ID == 1);
                Customer c = ((IEnumerable<Customer>)DataServiceContextTestUtil.ExecuteQuery(context, q, QueryMode.AsyncExecute)).Single();

                context.DeleteObject(c);

                try
                {
                    context.SetSaveStream(c, "Thumbnail", new MemoryStream(), true /*closeStream*/, "image/jpeg");
                }
                catch (DataServiceClientException ex)
                {
                    Assert.AreEqual(ex.Message, DataServicesClientResourceUtil.GetString("Context_SetSaveStreamOnInvalidEntityState", EntityStates.Deleted), "Error Message not as expected");
                }
            }
        }
            public void Collection_BatchIDataServiceHostAndChangeTracking()
            {
                DSPMetadata metadata = CreateMetadataForXFeatureEntity();

                TestUtil.RunCombinations(
                    new bool[] { false, true },
                    new bool[] { false, true },
                    new Type[] { typeof(IDataServiceHost), typeof(IDataServiceHost2) },
                    (sendAsBatch, replaceOnUpdate, hostInterfaceType) => {

                    DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, Writable = true, HostInterfaceType = hostInterfaceType };
                    
                    DSPContext data = new DSPContext();
                    service.CreateDataSource = (m) => { return data; };
                    // This test operates just on 2 entities - so let's take just first two from the set
                    List<object> testEntities = CreateClientTestEntities().Take(2).ToList<object>();
                    SaveChangesOptions saveOptions = 
                        (sendAsBatch ? SaveChangesOptions.BatchWithSingleChangeset : SaveChangesOptions.None) | 
                        (replaceOnUpdate ? SaveChangesOptions.ReplaceOnUpdate : SaveChangesOptions.None);

                    using (TestWebRequest request = service.CreateForInProcessWcf())
                    using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
                    {
                        DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
                        request.StartService();

                        // Add entities
                        DataServiceContext ctx = new DataServiceContext(new Uri(request.BaseUri), ODataProtocolVersion.V4);
                        ctx.EnableAtom = true;
                        ctx.Format.UseAtom();
                        foreach (XFeatureTestsEntity entity in testEntities)
                        {
                            ctx.AddObject("Entities", entity);
                        }
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Added);
                        ctx.SaveChanges(saveOptions);
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged);
                        VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));

                        // Change one of the entities
                        ((XFeatureTestsEntity)testEntities[0]).Structs.RemoveAt(0);
                        ctx.UpdateObject(testEntities[0]);
                        VerifyStateOfEntities(ctx, new[] { testEntities[0] }, EntityStates.Modified);
                        VerifyStateOfEntities(ctx, new[] { testEntities[1] }, EntityStates.Unchanged);
                        ctx.SaveChanges(saveOptions);
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged);
                        VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));

                        // Change collection in both entities
                        List<string> tempCollection = ((XFeatureTestsEntity)testEntities[0]).Strings;
                        ((XFeatureTestsEntity)testEntities[0]).Strings = ((XFeatureTestsEntity)testEntities[1]).Strings;
                        ((XFeatureTestsEntity)testEntities[1]).Strings = tempCollection;
                        ctx.UpdateObject(testEntities[0]);
                        ctx.UpdateObject(testEntities[1]);
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Modified);
                        ctx.SaveChanges(saveOptions);
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged);
                        VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));

                        // Delete entities
                        ctx.DeleteObject(testEntities[0]);
                        ctx.DeleteObject(testEntities[1]);
                        VerifyStateOfEntities(ctx, testEntities, EntityStates.Deleted);
                        ctx.SaveChanges(saveOptions);
                        testEntities.RemoveAt(0);
                        testEntities.RemoveAt(0);
                        VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));
                    }
                });
            }
Exemple #25
0
        public void EFFK_1To1_BasicInsert_Bind_Delete()
        {
            // Create new office type
            EFFKClient.Office o = new EFFKClient.Office()
            {
                ID = 1, BuildingName = "Building 35", FloorNumber = 2, OfficeNumber = 2173
            };
            ctx.AddObject("CustomObjectContext.Offices", o);

            // create new employee type
            EFFKClient.Worker e = new EFFKClient.Worker()
            {
                ID = 1, FirstName = "Pratik", LastName = "Patel"
            };
            ctx.AddObject("CustomObjectContext.Workers", e);
            ctx.SaveChanges();

            // Establish relationship between employee and office again. This operation should be no-op
            ctx.SetLink(o, "Worker", e);
            ctx.SaveChanges();

            ctx.SetLink(e, "Office", o);
            ctx.SaveChanges();

            // clean the tests by deleting the office instance created by this test
            ctx.DeleteObject(e);
            ctx.DeleteObject(o);
            ctx.SaveChanges();

            Assert.AreEqual(ctx.CreateQuery <EFFKClient.Worker>("CustomObjectContext.Workers").Count(), 0, "There should be no workers left");
            Assert.AreEqual(ctx.CreateQuery <EFFKClient.Office>("CustomObjectContext.Offices").Count(), 0, "There should be no offices left");
        }
Exemple #26
0
        /// <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;
            }
        }
Exemple #27
0
        public void EFFK_1To1_BasicInsertAndBind_Batch_ChangedUriCompositionRulesOnServer()
        {
            // Fix URI composition in Astoria for V3 payloads
            ctx = new DataServiceContext(web.ServiceRoot, Microsoft.OData.Client.ODataProtocolVersion.V4);
            ctx.EnableAtom = true;
            ctx.Format.UseAtom();
            // Create new office type
            EFFKClient.Office o = new EFFKClient.Office() { ID = 1, BuildingName = "Building 35", FloorNumber = 2, OfficeNumber = 2173 };
            ctx.AddObject("CustomObjectContext.Offices", o);

            // create new employee type
            EFFKClient.Worker e = new EFFKClient.Worker() { ID = 1, FirstName = "Pratik", LastName = "Patel" };
            ctx.AddObject("CustomObjectContext.Workers", e);

            // Establish relationship between employee and office
            ctx.SetLink(o, "Worker", e);
            ctx.SetLink(e, "Office", o);
            ctx.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);

            // clean the context
            ctx.DeleteObject(e);
            ctx.DeleteObject(o);
            ctx.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);
        }
            public void Collection_Blobs()
            {
                DSPMetadata metadata = CreateMetadataForXFeatureEntity(true);

                DSPServiceDefinition service = new DSPServiceDefinition() { 
                    Metadata = metadata, 
                    Writable = true, 
                    SupportMediaResource = true,
                    MediaResourceStorage = new DSPMediaResourceStorage()
                };

                byte[] clientBlob = new byte[] { 0xcc, 0x10, 0x00, 0xff };

                DSPContext data = new DSPContext();
                service.CreateDataSource = (m) => { return data; };

                using (TestWebRequest request = service.CreateForInProcessWcf())
                using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
                {
                    DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
                    request.StartService();

                    XFeatureTestsMLE clientMle = new XFeatureTestsMLE() {
                        ID = 1,
                        Description = "Entity 1",
                        Strings = new List<string>(new string[] { "string 1", "string 2", string.Empty }),
                        Structs = new List<XFeatureTestsComplexType>(new XFeatureTestsComplexType[] {
                                    new XFeatureTestsComplexType() { Text = "text 1" },
                                    new XFeatureTestsComplexType() { Text = "text 2" }}) };


                    DataServiceContext ctx = new DataServiceContext(new Uri(request.BaseUri), ODataProtocolVersion.V4);
                    ctx.EnableAtom = true;
                    ctx.Format.UseAtom();

                    ctx.AddObject("Entities", clientMle);
                    ctx.SetSaveStream(clientMle, new MemoryStream(clientBlob), true, "application/octet-stream", clientMle.ID.ToString());
                    ctx.SaveChanges();
                    VerifyMLEs(service, clientMle, clientBlob);

                    // Read stream and verify stream contents
                    using (Stream serverStream = ctx.GetReadStream(clientMle).Stream)
                    {
                        VerifyStream(clientBlob, serverStream);
                    }

                    // modify MLE and the corresponding stream 
                    clientMle.Structs.Add(new XFeatureTestsComplexType() { Text = "text 3" });
                    clientMle.Strings.RemoveAt(0);
                    clientBlob[0] ^= 0xff;
                    ctx.UpdateObject(clientMle);
                    ctx.SetSaveStream(clientMle, new MemoryStream(clientBlob), true, "application/octet-stream", clientMle.ID.ToString());
                    ctx.SaveChanges();
                    VerifyMLEs(service, clientMle, clientBlob);

                    // delete MLE
                    ctx.DeleteObject(clientMle);
                    ctx.SaveChanges();

                    Assert.IsNull((DSPResource)service.CurrentDataSource.GetResourceSetEntities("Entities").
                            FirstOrDefault(e => (int)(((DSPResource)e).GetValue("ID")) == (int)clientMle.GetType().GetProperty("ID").GetValue(clientMle, null)),
                            "MLE has not been deleted.");

                    Assert.AreEqual(0, service.MediaResourceStorage.Content.Count(), "The stream on the server has not been deleted.");
                };
            }
 /// <summary>
 /// Changes the state of the specified object to be deleted in the System.Data.Services.Client.DataServiceContext.
 /// Remarks:
 ///     Existing objects in the Added state become detached.
 /// </summary>
 /// <param name="entity">The tracked entity to be changed to the deleted state.</param>
 public void DeleteObject(object entity)
 {
     _dataContext.DeleteObject(entity);
 }
Exemple #30
0
        /// <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 Collection_ChangeInterceptors()
            {
                var metadata = CreateMetadataForXFeatureEntity();

                InterceptorServiceDefinition service = new InterceptorServiceDefinition()
                {
                    Metadata = metadata,
                    CreateDataSource = (m) => new DSPContext(),
                    Writable = true,
                    EnableChangeInterceptors = true
                };

                // client cases
                TestUtil.RunCombinations(new string[] { "POST", "PUT", "PATCH", "DELETE" }, new bool[] { false, true }, (httpMethod, batch) =>
                {
                    using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
                    using (TestWebRequest request = service.CreateForInProcessWcf())
                    {
                        DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
                        request.Accept = "application/atom+xml,application/xml";
                        request.StartService();

                        DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                        ctx.EnableAtom = true;
                        ctx.Format.UseAtom();

                        if (httpMethod != "POST")
                        {
                            service.EnableChangeInterceptors = false;
                            PopulateClientContextWithTestEntities(ctx);
                            service.EnableChangeInterceptors = true;
                        }

                        ctx.IgnoreResourceNotFoundException = true;

                        var resource = ctx.CreateQuery<XFeatureTestsEntity>("Entities").FirstOrDefault();
                        SaveChangesOptions saveOptions = batch ? SaveChangesOptions.BatchWithSingleChangeset : SaveChangesOptions.None;
                        switch (httpMethod)
                        {
                            case "POST":
                                resource = new XFeatureTestsEntity() { ID = 42, Strings = new List<string>(), Structs = new List<XFeatureTestsComplexType>() };
                                ctx.AddObject("Entities", resource);
                                break;
                            case "PUT":
                                saveOptions |= SaveChangesOptions.ReplaceOnUpdate;
                                ctx.UpdateObject(resource);
                                break;
                            case "PATCH":
                                ctx.UpdateObject(resource);
                                break;
                            case "DELETE":
                                ctx.DeleteObject(resource);
                                break;
                        }
                        ctx.SaveChanges(saveOptions);

                        Assert.AreEqual((int?)resource.ID, service.ChangeInterceptorCalledOnEntityId, "The change interceptor was not called or it was called with a wrong entity");
                        service.ChangeInterceptorCalledOnEntityId = null;
                    }
                });

                service.EnableChangeInterceptors = true;
                service.ChangeInterceptorCalledOnEntityId = null;

                // server cases (these operations can't be done using client API)
                TestUtil.RunCombinations(
                    new string[] { "Strings", "Structs" }, 
                    new string[] { UnitTestsUtil.MimeApplicationXml}, 
                    (collectionPropertyName, format) =>
                {
                    using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
                    using (TestWebRequest request = service.CreateForInProcessWcf())
                    {
                        DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
                        request.StartService();

                        DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                        ctx.EnableAtom = true;
                        ctx.Format.UseAtom();
                        service.EnableChangeInterceptors = false;
                        PopulateClientContextWithTestEntities(ctx);
                        service.EnableChangeInterceptors = true;

                        // Get the collection property payload
                        var payload = UnitTestsUtil.GetResponseAsAtomXLinq(request, "/Entities(1)/" + collectionPropertyName, format);

                        // And send a PUT with that payload back
                        request.HttpMethod = "PUT";
                        request.Accept = format;
                        request.RequestContentType = format;
                        request.RequestUriString = "/Entities(1)/" + collectionPropertyName;
                        request.SetRequestStreamAsText(payload.ToString());
                        request.SendRequest();

                        Assert.AreEqual((int?)1, service.ChangeInterceptorCalledOnEntityId, "The change interceptor was not called or it was called with a wrong entity");
                        service.ChangeInterceptorCalledOnEntityId = null;
                    }
                });
            }