Exemplo n.º 1
0
        public async Task BasicPatchTests([CombinatorialValues("movies", "movies_pagesize")] string table)
        {
            var id       = GetRandomId();
            var expected = MovieServer.GetMovieById(id) !;

            expected.Title  = "Test Movie Title";
            expected.Rating = "PG-13";
            var patchDoc = new PatchOperation[]
            {
                new PatchOperation("replace", "title", "Test Movie Title"),
                new PatchOperation("replace", "rating", "PG-13")
            };

            var response = await MovieServer.SendPatch($"tables/{table}/{id}", patchDoc);

            await AssertResponseWithLoggingAsync(HttpStatusCode.OK, response);

            var result = response.DeserializeContent <ClientMovie>();
            var stored = MovieServer.GetMovieById(id);

            AssertEx.SystemPropertiesSet(stored, StartTime);
            AssertEx.SystemPropertiesChanged(expected, stored);
            AssertEx.SystemPropertiesMatch(stored, result);
            Assert.Equal <IMovie>(expected, result !);
            AssertEx.ResponseHasConditionalHeaders(stored, response);
        }
Exemplo n.º 2
0
        public async Task AllowBatchingRequestsSendsToExecutor_PatchStream()
        {
            (ContainerInternal container, Mock <BatchAsyncContainerExecutor> mockedExecutor) = this.CreateMockBulkCosmosClientContext();

            dynamic testItem = new
            {
                id = Guid.NewGuid().ToString(),
                pk = "FF627B77-568E-4541-A47E-041EAC10E46F",
            };

            List <PatchOperation> patch = new List <PatchOperation>()
            {
                PatchOperation.Add("/new", "patched")
            };

            ItemRequestOptions itemRequestOptions = new ItemRequestOptions();

            Cosmos.PartitionKey partitionKey = new Cosmos.PartitionKey(testItem.pk);
            using (ResponseMessage streamResponse = await container.PatchItemStreamAsync(
                       partitionKey: partitionKey,
                       id: testItem.id,
                       patchOperations: patch))
            {
                mockedExecutor.Verify(c => c.AddAsync(It.IsAny <ItemBatchOperation>(), It.IsAny <ItemRequestOptions>(), It.IsAny <CancellationToken>()), Times.Once);
            }
        }
Exemplo n.º 3
0
        public async Task ItemBulkNoResponseTest()
        {
            ItemRequestOptions requestOptions = new ItemRequestOptions()
            {
                EnableContentResponseOnWrite = false
            };

            CosmosClient          bulkClient            = TestCommon.CreateCosmosClient((builder) => builder.WithBulkExecution(true));
            Container             bulkContainer         = bulkClient.GetContainer(this.database.Id, this.container.Id);
            ContainerInternal     bulkContainerInternal = (ContainerInternal)bulkContainer;
            string                pkId  = "TestBulkId";
            List <PatchOperation> patch = new List <PatchOperation>()
            {
                PatchOperation.Remove("/cost")
            };

            List <Task <ItemResponse <ToDoActivity> > > bulkOperations = new List <Task <ItemResponse <ToDoActivity> > >();
            List <ToDoActivity> items = new List <ToDoActivity>();

            for (int i = 0; i < 50; i++)
            {
                ToDoActivity item = ToDoActivity.CreateRandomToDoActivity(pk: pkId);
                items.Add(item);
                bulkOperations.Add(bulkContainer.CreateItemAsync <ToDoActivity>(item, requestOptions: requestOptions));
            }

            foreach (Task <ItemResponse <ToDoActivity> > result in bulkOperations)
            {
                ItemResponse <ToDoActivity> itemResponse = await result;
                this.ValidateItemNoContentResponse(itemResponse);
            }

            PatchItemRequestOptions patchRequestOptions = new PatchItemRequestOptions()
            {
                EnableContentResponseOnWrite = false
            };

            foreach (ToDoActivity item in items)
            {
                bulkOperations.Add(bulkContainerInternal.PatchItemAsync <ToDoActivity>(item.id, new PartitionKey(item.pk), patch, requestOptions: patchRequestOptions));
            }

            foreach (Task <ItemResponse <ToDoActivity> > result in bulkOperations)
            {
                ItemResponse <ToDoActivity> itemResponse = await result;
                this.ValidateItemNoContentResponse(itemResponse);
            }

            bulkOperations = new List <Task <ItemResponse <ToDoActivity> > >();
            foreach (ToDoActivity item in items)
            {
                bulkOperations.Add(bulkContainer.ReadItemAsync <ToDoActivity>(item.id, new PartitionKey(item.pk), requestOptions: requestOptions));
            }

            foreach (Task <ItemResponse <ToDoActivity> > result in bulkOperations)
            {
                ItemResponse <ToDoActivity> itemResponse = await result;
                this.ValidateItemResponse(itemResponse);
            }
        }
        private static void LoadSaveGamePatchesFor(ModContentPack mod)          //Taken from Verse.ModContentPack.LoadPatches()
        {
            List <LoadableXmlAsset> list = DirectXmlLoader.XmlAssetsInModFolder(mod, "SaveGamePatches/").ToList <LoadableXmlAsset> ();

            for (int i = 0; i < list.Count; i++)
            {
                XmlElement documentElement = list [i].xmlDoc.DocumentElement;
                if (documentElement.Name != "Patch")
                {
                    Log.Error(string.Format("Unexpected document element in patch XML; got {0}, expected 'Patch'", documentElement.Name));
                }
                else
                {
                    for (int j = 0; j < documentElement.ChildNodes.Count; j++)
                    {
                        XmlNode xmlNode = documentElement.ChildNodes [j];
                        if (xmlNode.NodeType == XmlNodeType.Element)
                        {
                            if (xmlNode.Name != "Operation")
                            {
                                Log.Error(string.Format("Unexpected element in patch XML; got {0}, expected 'Operation'", documentElement.ChildNodes [j].Name));
                            }
                            else
                            {
                                PatchOperation patchOperation = DirectXmlToObject.ObjectFromXml <PatchOperation> (xmlNode, false);
                                patchOperation.sourceFile = list [i].FullFilePath;
                                SaveGamePatches.patches.Add(patchOperation);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        public async Task StreamOperationsTest(ConnectionMode mode)
        {
            Container container = await this.GetContainer(mode);

            // Create an item
            var testItem = new { id = "MyTestItemId", partitionKeyPath = "MyTestPkValue", details = "it's working", status = "done" };
            await container
            .CreateItemStreamAsync(TestCommon.SerializerCore.ToStream(testItem),
                                   new Cosmos.PartitionKey(testItem.id));

            //Upsert an Item
            await container.UpsertItemStreamAsync(TestCommon.SerializerCore.ToStream(testItem), new Cosmos.PartitionKey(testItem.id));

            //Read an Item
            await container.ReadItemStreamAsync(testItem.id, new Cosmos.PartitionKey(testItem.id));

            //Replace an Item
            await container.ReplaceItemStreamAsync(TestCommon.SerializerCore.ToStream(testItem), testItem.id, new Cosmos.PartitionKey(testItem.id));

            // Patch an Item
            List <PatchOperation> patch = new List <PatchOperation>()
            {
                PatchOperation.Add("/new", "patched")
            };

            await((ContainerInternal)container).PatchItemStreamAsync(
                partitionKey: new Cosmos.PartitionKey(testItem.id),
                id: testItem.id,
                patchOperations: patch);

            //Delete an Item
            await container.DeleteItemStreamAsync(testItem.id, new Cosmos.PartitionKey(testItem.id));

            await this.WaitAndAssert(12);
        }
        private static void ValidateOperations <T>(PatchOperation patchOperation, PatchOperationType operationType, T value)
        {
            Assert.AreEqual(operationType, patchOperation.OperationType);
            Assert.AreEqual(path, patchOperation.Path);

            if (!operationType.Equals(PatchOperationType.Remove))
            {
                string           expected;
                CosmosSerializer cosmosSerializer = new CosmosJsonDotNetSerializer();
                using (Stream stream = cosmosSerializer.ToStream(value))
                {
                    using (StreamReader streamReader = new StreamReader(stream))
                    {
                        expected = streamReader.ReadToEnd();
                    }
                }

                Assert.IsTrue(patchOperation.TrySerializeValueParameter(new CustomSerializer(), out Stream valueParam));

                string actual;
                using (valueParam)
                {
                    using (StreamReader streamReader = new StreamReader(valueParam))
                    {
                        actual = streamReader.ReadToEnd();
                    }
                }

                Assert.AreEqual(expected, actual);
            }
        }
        public void CreateCopy()
        {
            PatchOperation patchOperation = PatchOperation.CreateCopy(new Range <int>(10, 15));

            Assert.AreEqual(PatchOperationType.Copy, patchOperation.Type);
            Assert.AreEqual(new Range <int>(10, 15), patchOperation.Copy);
        }
        public void CreateDeletion()
        {
            PatchOperation patchOperation = PatchOperation.CreateDeletion(new Range <int>(10, 15));

            Assert.AreEqual(PatchOperationType.Deletion, patchOperation.Type);
            Assert.AreEqual(new Range <int>(10, 15), patchOperation.Deletion);
        }
Exemplo n.º 9
0
        public async Task PointSuccessOperationsTest(ConnectionMode mode)
        {
            Container container = await this.GetContainer(mode);

            // Create an item
            ToDoActivity testItem = ToDoActivity.CreateRandomToDoActivity("MyTestPkValue");
            ItemResponse <ToDoActivity> createResponse = await container.CreateItemAsync <ToDoActivity>(testItem);

            ToDoActivity testItemCreated = createResponse.Resource;

            // Read an Item
            await container.ReadItemAsync <ToDoActivity>(testItem.id, new Cosmos.PartitionKey(testItem.id));

            // Upsert an Item
            await container.UpsertItemAsync <ToDoActivity>(testItem);

            // Replace an Item
            await container.ReplaceItemAsync <ToDoActivity>(testItemCreated, testItemCreated.id.ToString());

            // Patch an Item
            List <PatchOperation> patch = new List <PatchOperation>()
            {
                PatchOperation.Add("/new", "patched")
            };

            await((ContainerInternal)container).PatchItemAsync <ToDoActivity>(
                testItem.id,
                new Cosmos.PartitionKey(testItem.id),
                patch);

            // Delete an Item
            await container.DeleteItemAsync <ToDoActivity>(testItem.id, new Cosmos.PartitionKey(testItem.id));

            await this.WaitAndAssert(12);
        }
Exemplo n.º 10
0
        public PackageItemContainer(XmlElement element) : base(element)
        {
            Children   = new SetCollection();
            Operations = new OperationCollection();

            foreach (XmlElement e in element.ChildNodes)
            {
                switch (e.Name)
                {
                case "set":

                    Set set = new Set(e);
                    Children.Add(set);

                    break;

                case "patch":

                    PatchOperation patch = new PatchOperation(e);
                    Operations.Add(patch);
                    break;

                case "file":
                case "filetype":
                    break;
                }
            }
        }
Exemplo n.º 11
0
        public void ConstructPatchOperationTest()
        {
            PatchOperation operation = PatchOperation.CreateAddOperation(path, "string");

            PatchOperationTests.ValidateOperations(operation, PatchOperationType.Add, "string");

            DateTime current = DateTime.UtcNow;

            operation = PatchOperation.CreateAddOperation(path, current);
            PatchOperationTests.ValidateOperations(operation, PatchOperationType.Add, current);

            dynamic complexObject = new { a = "complex", b = 12.34, c = true };

            operation = PatchOperation.CreateAddOperation(path, complexObject);
            PatchOperationTests.ValidateOperations(operation, PatchOperationType.Add, complexObject);

            operation = PatchOperation.CreateRemoveOperation(path);
            PatchOperationTests.ValidateOperations(operation, PatchOperationType.Remove, "value not required");

            int[] arrayObject = { 1, 2, 3 };
            operation = PatchOperation.CreateReplaceOperation(path, arrayObject);
            PatchOperationTests.ValidateOperations(operation, PatchOperationType.Replace, arrayObject);

            Guid guid = new Guid();

            operation = PatchOperation.CreateSetOperation(path, guid);
            PatchOperationTests.ValidateOperations(operation, PatchOperationType.Set, guid);
        }
        public PatchRequest2 ComposeReferencePatch(
            string referenceAttributeName,
            string referencedObjectUniqueIdentifier,
            OperationName operationName)
        {
            Assert.IsFalse(string.IsNullOrWhiteSpace(referenceAttributeName));
            Assert.IsFalse(string.IsNullOrWhiteSpace(referencedObjectUniqueIdentifier));

            IPath path;

            Assert.IsTrue(Path.TryParse(referenceAttributeName, out path));
            OperationValue operationValue =
                new OperationValue()
            {
                Value = referencedObjectUniqueIdentifier
            };
            PatchOperation operation =
                new PatchOperation()
            {
                Name = operationName,
                Path = path
            };

            operation.AddValue(operationValue);

            PatchRequest2 result = new PatchRequest2();

            result.AddOperation(operation);
            return(result);
        }
        public void ValidatePatchOperationSerialization()
        {
            int toCount   = 0;
            int fromCount = 0;

            CosmosSerializerHelper serializerHelper = new CosmosSerializerHelper(
                null,
                (input) => fromCount++,
                (input) => toCount++);

            CosmosSerializerCore  serializerCore = new CosmosSerializerCore(serializerHelper);
            List <PatchOperation> patch          = new List <PatchOperation>()
            {
                PatchOperation.Remove("/removePath")
            };

            Assert.AreEqual(0, toCount);

            // custom serializer is not used since operation type is Remove, which doesnt have "value" param to serialize
            using (Stream stream = serializerCore.ToStream(patch)) { }
            Assert.AreEqual(0, toCount);

            patch.Add(PatchOperation.Add("/addPath", "addValue"));
            // custom serializer is used since there is Add operation type also
            using (Stream stream = serializerCore.ToStream(patch)) { }
            Assert.AreEqual(1, toCount);
        }
        public async Task BatchOperationDiagnostic(bool disableDiagnostics)
        {
            string                pkValue   = "DiagnosticTestPk";
            TransactionalBatch    batch     = this.Container.CreateTransactionalBatch(new PartitionKey(pkValue));
            BatchCore             batchCore = (BatchCore)batch;
            List <PatchOperation> patch     = new List <PatchOperation>()
            {
                PatchOperation.Remove("/cost")
            };

            List <ToDoActivity> createItems = new List <ToDoActivity>();

            for (int i = 0; i < 50; i++)
            {
                ToDoActivity item = ToDoActivity.CreateRandomToDoActivity(pk: pkValue);
                createItems.Add(item);
                batch.CreateItem <ToDoActivity>(item);
            }

            for (int i = 0; i < 20; i++)
            {
                batch.ReadItem(createItems[i].id);
                batchCore.PatchItem(createItems[i].id, patch);
            }

            TransactionalBatchRequestOptions requestOptions = disableDiagnostics ? RequestOptionDisableDiagnostic : null;
            TransactionalBatchResponse       response       = await batch.ExecuteAsync(requestOptions);

            Assert.IsNotNull(response);
            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                diagnostics: response.Diagnostics,
                disableDiagnostics: disableDiagnostics);
        }
        /// <inheritdoc />
        public override async Task <ResourceResponse> ExecuteAsync(PatchResourceRequest request)
        {
            try
            {
                var resource = await this.Repository.ReadResourceAsync(request.ResourceId);

                resource = this.PatchApplier.ApplyTo(resource, PatchOperation.Parse(request.Payload));
                resource = await this.Repository.UpdateResourceAsync(resource);

                return(new ResourceResponse {
                    Code = ResponseCode.Success, Resource = resource
                });
            }
            catch (ResourceNotFoundException exception)
            {
                return(new ResourceResponse {
                    Code = ResponseCode.ResourceNotFound, Exception = exception
                });
            }
            catch (Exception exception)
            {
                return(new ResourceResponse {
                    Code = ResponseCode.Failure, Exception = exception
                });
            }
        }
        public void Equals()
        {
            Assert.AreEqual(PatchOperation.CreateAddition(1, 10), PatchOperation.CreateAddition(1, 10));
            Assert.AreEqual(PatchOperation.CreateDeletion(1, 10), PatchOperation.CreateDeletion(1, 10));
            Assert.AreEqual(PatchOperation.CreateCopy(1, 10), PatchOperation.CreateCopy(1, 10));

            Assert.AreNotEqual(PatchOperation.CreateAddition(1, 10), PatchOperation.CreateDeletion(1, 10));
            Assert.AreNotEqual(PatchOperation.CreateAddition(1, 10), PatchOperation.CreateCopy(1, 10));
            Assert.AreNotEqual(PatchOperation.CreateAddition(1, 10), PatchOperation.CreateAddition(10, 1));

            Assert.AreNotEqual(PatchOperation.CreateDeletion(1, 10), PatchOperation.CreateAddition(1, 10));
            Assert.AreNotEqual(PatchOperation.CreateDeletion(1, 10), PatchOperation.CreateDeletion(10, 1));
            Assert.AreNotEqual(PatchOperation.CreateDeletion(1, 10), PatchOperation.CreateCopy(10, 1));

            Assert.AreNotEqual(PatchOperation.CreateCopy(1, 10), PatchOperation.CreateAddition(1, 10));
            Assert.AreNotEqual(PatchOperation.CreateCopy(1, 10), PatchOperation.CreateCopy(10, 1));
            Assert.AreNotEqual(PatchOperation.CreateCopy(1, 10), PatchOperation.CreateDeletion(10, 1));

            Assert.AreNotEqual(PatchOperation.CreateAddition(1, 1), null);
            Assert.AreNotEqual(PatchOperation.CreateAddition(1, 1), string.Empty);

            Assert.AreNotEqual(PatchOperation.CreateDeletion(1, 1), null);
            Assert.AreNotEqual(PatchOperation.CreateDeletion(1, 1), string.Empty);

            Assert.AreNotEqual(PatchOperation.CreateCopy(1, 1), null);
            Assert.AreNotEqual(PatchOperation.CreateCopy(1, 1), string.Empty);
        }
Exemplo n.º 17
0
        public void GetPatchOperations11()
        {
            DiffEngine <string> diffEngine =
                new DiffEngine <string>(
                    "The metrics for clarity are more-well understood. Do you have a game PLAN to become peerlessly synergetic across all platforms ? Think interactive".Split(' '),
                    //0    1       2    3     4      5      6           7  8   9   10 11   12  13   14      15        16         17   18   19       20 21     22
                    //0    1       2    3         4     5         6         7  8   9   10 11  12   13  14         15     16  17   18
                    "The metrics for obfuscation are more-well understood. Do you have a game plan to become cross-media ? Think interactive".Split(' '));

            PatchOperation[] expectedPatchOperations =
                new PatchOperation[] {
                PatchOperation.CreateCopy(0, 2),
                PatchOperation.CreateAddition(3, 3),
                PatchOperation.CreateDeletion(3, 3),
                PatchOperation.CreateCopy(4, 11),
                PatchOperation.CreateAddition(12, 12),
                PatchOperation.CreateDeletion(12, 12),
                PatchOperation.CreateCopy(13, 14),
                PatchOperation.CreateAddition(15, 15),
                PatchOperation.CreateDeletion(15, 19),
                PatchOperation.CreateCopy(20, 22)
            };

            AssertDifferences(diffEngine, expectedPatchOperations);
        }
Exemplo n.º 18
0
        public void CanOverwrite()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    session.Store(new Person
                    {
                        Name = "John Doe"
                    }, "people/1");

                    session.SaveChanges();
                }

                var reqEx = store.GetRequestExecutor();

                using (reqEx.ContextPool.AllocateOperationContext(out var context))
                {
                    PatchOperation operation = new PatchOperation(
                        id: "people/1",
                        changeVector: null,
                        patch: new PatchRequest
                    {
                        Script = @"this.NewField= 'new value';
                        console.log('foo')"
                    },
                        patchIfMissing: null);

                    var cmd = operation.GetCommand(store, store.Conventions, context, reqEx.Cache, true, false);
                    store.Commands().Execute(cmd);
                    Assert.Equal("foo", (cmd.Result.Debug["Info"] as BlittableJsonReaderArray)[0].ToString());
                }
            }
        }
        public async Task CompareRUs(IEnumerable <RGB> rgbList)
        {
            try
            {
                RGB rgb = rgbList.ElementAt(0);
                Console.Write("Execute ReplaceItemAsync to update a item [{0}]'s field [/R]... ", rgb.id);
                ItemResponse <RGB> responseReplace = await this.Container.ReplaceItemAsync(
                    partitionKey : new PartitionKey(rgb.x),
                    id : rgb.id,
                    item : rgb
                    );

                Console.Write("Complete! RU Charge for Replace a item [{0}] - {1} RU\n", responseReplace.Resource.id, responseReplace.RequestCharge);

                Console.Write("Execute PatchItemAsync to update a item [{0}]'s field [/R]... ", rgb.id);
                ItemResponse <RGB> responsePatch = await this.Container.PatchItemAsync <RGB>(
                    id : rgb.id,
                    partitionKey : new PartitionKey(rgb.x),
                    patchOperations : new[] { PatchOperation.Replace("/R", rgb.R) }
                    );

                Console.Write("Complete! RU Charge for Patch a item [{0}] - {1} RU\n", responsePatch.Resource.id, responsePatch.RequestCharge);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 20
0
        public void Then_The_Url_Is_Correctly_Constructed(Guid id, PatchOperation data)
        {
            var actual = new PatchCourseDemandRequest(id, data);

            actual.Data.Should().BeEquivalentTo(new List <PatchOperation> {
                data
            });
            actual.PatchUrl.Should().Be($"api/demand/{id}");
        }
Exemplo n.º 21
0
        public void DebugResultsWhenModifyingCounters()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    session.Store(new Car {
                        Model = "Golf"
                    }, "cars/1");
                    session.CountersFor("cars/1").Increment("Counter1", 100);
                    session.SaveChanges();
                }

                var reqEx = store.GetRequestExecutor();
                using (reqEx.ContextPool.AllocateOperationContext(out var context))
                {
                    PatchOperation operation = new PatchOperation(id: "cars/1", changeVector: null, patch: new PatchRequest {
                        Script = @"
                                    incrementCounter('cars/1', 'Counter1', 50);
                                    incrementCounter('cars/1', 'Counter2');
                                 "
                    }, patchIfMissing: null);

                    var cmd = operation.GetCommand(store, store.Conventions, context, reqEx.Cache, true, true);
                    store.Commands().Execute(cmd);

                    Assert.True(cmd.Result.Debug.TryGet("Actions", out BlittableJsonReaderObject actions), "<Actions> section not found");

                    // Counters Modifications Check
                    Assert.True(actions.TryGet("IncrementCounter", out BlittableJsonReaderArray incrementCounter), "<IncrementCounter> section not found");

                    (incrementCounter[0] as BlittableJsonReaderObject).TryGet("Name", out string name);
                    Assert.Equal("Counter1", name);
                    (incrementCounter[0] as BlittableJsonReaderObject).TryGet("OldValue", out int?oldValue);
                    Assert.Equal(100, oldValue);
                    (incrementCounter[0] as BlittableJsonReaderObject).TryGet("AddedValue", out int addedValue);
                    Assert.Equal(50, addedValue);
                    (incrementCounter[0] as BlittableJsonReaderObject).TryGet("NewValue", out int newValue);
                    Assert.Equal(150, newValue);
                    (incrementCounter[0] as BlittableJsonReaderObject).TryGet("Created", out bool created);
                    Assert.Equal(false, created);

                    (incrementCounter[1] as BlittableJsonReaderObject).TryGet("Name", out name);
                    Assert.Equal("Counter2", name);
                    (incrementCounter[1] as BlittableJsonReaderObject).TryGet("OldValue", out oldValue);
                    Assert.Equal(null, oldValue);
                    (incrementCounter[1] as BlittableJsonReaderObject).TryGet("AddedValue", out addedValue);
                    Assert.Equal(1, addedValue);
                    (incrementCounter[1] as BlittableJsonReaderObject).TryGet("NewValue", out newValue);
                    Assert.Equal(1, newValue);
                    (incrementCounter[1] as BlittableJsonReaderObject).TryGet("Created", out created);
                    Assert.Equal(true, created);
                }
            }
        }
Exemplo n.º 22
0
        private async Task Validate(
            ItemRequestOptions requestOptions,
            Action <ItemResponse <ToDoActivity> > ValidateWrite,
            Action <ItemResponse <ToDoActivity> > ValidateRead)
        {
            ToDoActivity item = ToDoActivity.CreateRandomToDoActivity();
            ItemResponse <ToDoActivity> itemResponse = await this.container.CreateItemAsync(item, requestOptions : requestOptions);

            Assert.AreEqual(HttpStatusCode.Created, itemResponse.StatusCode);
            ValidateWrite(itemResponse);

            itemResponse = await this.container.ReadItemAsync <ToDoActivity>(item.id, new PartitionKey(item.status), requestOptions : requestOptions);

            Assert.AreEqual(HttpStatusCode.OK, itemResponse.StatusCode);
            ValidateRead(itemResponse);

            item.cost    = 424242.42;
            itemResponse = await this.container.UpsertItemAsync <ToDoActivity>(item, requestOptions : requestOptions);

            Assert.AreEqual(HttpStatusCode.OK, itemResponse.StatusCode);
            ValidateWrite(itemResponse);

            item.cost    = 9000.42;
            itemResponse = await this.container.ReplaceItemAsync <ToDoActivity>(
                item,
                item.id,
                new PartitionKey(item.status),
                requestOptions : requestOptions);

            Assert.AreEqual(HttpStatusCode.OK, itemResponse.StatusCode);
            ValidateWrite(itemResponse);

            item.cost = 1000;
            List <PatchOperation> patch = new List <PatchOperation>()
            {
                PatchOperation.CreateReplaceOperation("/cost", item.cost)
            };

            itemResponse = await this.containerInternal.PatchItemAsync <ToDoActivity>(
                item.id,
                new PartitionKey(item.status),
                patchOperations : patch,
                requestOptions : requestOptions);

            Assert.AreEqual(HttpStatusCode.OK, itemResponse.StatusCode);
            ValidateWrite(itemResponse);

            itemResponse = await this.container.DeleteItemAsync <ToDoActivity>(
                item.id,
                new PartitionKey(item.status),
                requestOptions : requestOptions);

            Assert.AreEqual(HttpStatusCode.NoContent, itemResponse.StatusCode);
            this.ValidateItemNoContentResponse(itemResponse);
        }
Exemplo n.º 23
0
        public void TestJsonArrayCanBeParsed()
        {
            var result = PatchOperation.Parse(
                "[{ \"op\": \"test\", \"path\": \"/a/b/c\", \"value\": \"foo\" }, { \"op\": \"remove\", \"path\": \"/a/b/c\" }]");

            Assert.AreEqual(2, result.Count);

            Assert.AreEqual("test", result[0].Operation);
            Assert.AreEqual("/a/b/c", result[0].Path);
            Assert.AreEqual("foo", result[0].Value);
        }
Exemplo n.º 24
0
        // </ReplaceItemAsync>

        // <PatchItemAsync>
        private static async Task PatchItemAsync(SalesOrder order)
        {
            //******************************************************************************************************************
            // 1.7 - Patch a item
            //
            // Just update a property of an existing item and issue a Patch command
            //******************************************************************************************************************
            Console.WriteLine("\n1.6 - Patching a item using its Id");

            ItemResponse <SalesOrder> response = await container.PatchItemAsync <SalesOrder>(
                id : order.Id,
                partitionKey : new PartitionKey(order.AccountNumber),
                patchOperations : new[] { PatchOperation.Replace("/TotalDue", 0) });

            SalesOrder updatedSalesOrder = response.Resource;

            Console.WriteLine($"TotalDue of updated item: {updatedSalesOrder.TotalDue}");

            PatchItemRequestOptions patchItemRequestOptions = new PatchItemRequestOptions
            {
                FilterPredicate = "from c where (c.TotalDue = 0 OR NOT IS_DEFINED(c.TotalDue))"
            };

            response = await container.PatchItemAsync <SalesOrder>(
                id : order.Id,
                partitionKey : new PartitionKey(order.AccountNumber),
                patchOperations : new[] { PatchOperation.Replace("/ShippedDate", DateTime.UtcNow) },
                patchItemRequestOptions);

            updatedSalesOrder = response.Resource;
            Console.WriteLine($"\n1.6.2 - Shipped date of updated item: {updatedSalesOrder.ShippedDate}");

            IReadOnlyList <PatchOperation> patchOperations = new[] { PatchOperation.Replace("/ShippedDate", DateTime.UtcNow) };

            using (Stream stream = Program.ToStream <IReadOnlyList <PatchOperation> >(patchOperations))
            {
                using (ResponseMessage responseMessage = await container.PatchItemStreamAsync(
                           id: order.Id,
                           partitionKey: new PartitionKey(order.AccountNumber),
                           patchOperations: patchOperations))
                {
                    // Item stream operations do not throw exceptions for better performance
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        SalesOrder streamResponse = FromStream <SalesOrder>(responseMessage.Content);
                        Console.WriteLine($"\n1.6.3 - Item Patch via stream {streamResponse.Id}");
                    }
                    else
                    {
                        Console.WriteLine($"Patch item from stream failed. Status code: {responseMessage.StatusCode} Message: {responseMessage.ErrorMessage}");
                    }
                }
            }
        }
Exemplo n.º 25
0
 private bool ApplyPatches(XmlDocument xml)
 {
     foreach (PatchOperation operation in this.operations)
     {
         if (!operation.Apply(xml))
         {
             this.lastFailedOperation = operation;
             return(false);
         }
     }
     return(true);
 }
Exemplo n.º 26
0
        private static void PatchMembers(this Core2Group group, PatchOperation operation)
        {
            //path Members expects operation to only contain one item

            group.Members = PatchMembers(group.Members, operation);
            if (operation.Value.Count > 1)
            {
                List <Newtonsoft.Json.Linq.JToken> list = operation.Value.ToList();
                list.RemoveAt(0);
                operation.Value = list;
                group.PatchMembers(operation);
            }
        }
Exemplo n.º 27
0
        public void GetPatchOperations5()
        {
            DiffEngine <long> diffEngine = new DiffEngine <long>(
                new long[] { 1, 2, 3 }, new long[] { 2, 3 });

            PatchOperation[] expectedPatchOperations =
                new PatchOperation[] {
                PatchOperation.CreateDeletion(0, 0),
                PatchOperation.CreateCopy(1, 2)
            };

            AssertDifferences(diffEngine, expectedPatchOperations);
        }
Exemplo n.º 28
0
        private static Range <int> GetRange(PatchOperation difference, WordDataProvider dataProvider)
        {
            int start = dataProvider.Matches[difference.Range.Start].Index;
            int end   = 0;

            for (int match = difference.Range.Start; match <= difference.Range.End; ++match)
            {
                end = Math.Max(end,
                               dataProvider.Matches[match].Index + dataProvider.Matches[match].Length);
            }

            return(new Range <int>(start, end));
        }
Exemplo n.º 29
0
        public void ReplaceGivenPropertyWithRequiredAndJsonAttributesSetsCorrectPatchOperation()
        {
            //Arrange
            IPatchOperationBuilder <RequiredAndJsonItem> builder = new PatchOperationBuilder <RequiredAndJsonItem>();

            //Act
            builder.Replace(x => x.TestProperty, "Test Value");

            //Assert
            PatchOperation operation = builder.PatchOperations.First();

            Assert.Equal(PatchOperationType.Replace, operation.OperationType);
            Assert.Equal("/testProperty", operation.Path);
        }
Exemplo n.º 30
0
        public async Task ClientContentResponseTest()
        {
            ToDoActivity item = ToDoActivity.CreateRandomToDoActivity();
            ItemResponse <ToDoActivity> itemResponse = await this.containerWithFlag.CreateItemAsync(item);

            Assert.AreEqual(HttpStatusCode.Created, itemResponse.StatusCode);
            Assert.IsNotNull(itemResponse);
            Assert.IsNotNull(itemResponse.Resource);

            itemResponse = await this.containerWithFlag.ReadItemAsync <ToDoActivity>(item.id, new PartitionKey(item.pk));

            Assert.AreEqual(HttpStatusCode.OK, itemResponse.StatusCode);
            item.cost = 424242.42;

            itemResponse = await this.containerWithFlag.UpsertItemAsync <ToDoActivity>(item);

            Assert.AreEqual(HttpStatusCode.OK, itemResponse.StatusCode);
            Assert.IsNotNull(itemResponse.Resource);

            item.cost    = 9000.42;
            itemResponse = await this.containerWithFlag.ReplaceItemAsync <ToDoActivity>(
                item,
                item.id,
                new PartitionKey(item.pk));

            Assert.AreEqual(HttpStatusCode.OK, itemResponse.StatusCode);
            Assert.IsNotNull(itemResponse.Resource);

            ContainerInternal containerInternal = (ContainerInternal)this.containerWithFlag;

            item.cost = 1000;
            List <PatchOperation> patch = new List <PatchOperation>()
            {
                PatchOperation.Replace("/cost", item.cost)
            };

            itemResponse = await containerInternal.PatchItemAsync <ToDoActivity>(
                item.id,
                new PartitionKey(item.pk),
                patchOperations : patch);

            Assert.AreEqual(HttpStatusCode.OK, itemResponse.StatusCode);
            Assert.IsNotNull(itemResponse.Resource);

            ItemResponse <ToDoActivity> itemResponseWithoutFlag = await this.containerWithoutFlag.CreateItemAsync(item);

            Assert.AreEqual(HttpStatusCode.Created, itemResponseWithoutFlag.StatusCode);
            Assert.IsNotNull(itemResponseWithoutFlag);
            Assert.IsNull(itemResponseWithoutFlag.Resource);
        }
        public void TestLifecycleGroup()
        {
            Uri addressBase = new Uri(WebServiceUnitTest.AddressBase);

            IMonitor monitor = new ConsoleMonitor();

            IAmazonWebServicesIdentityAnchoringBehavior anchoringBehavior =
                new AnchoringByIdentifierBehavior();
            AmazonWebServicesProviderBase provider = new AmazonWebServicesProvider(WebServiceUnitTest.CredentialsProfileName, anchoringBehavior);
            Service webService = null;
            try
            {
                webService = new WebService(monitor, provider);
                webService.Start(addressBase);

                string identifierGroup;
                string identifierGroupExternal;
                string identifierMemberOne;
                string identifierMemberTwo;
                
                Uri resource;

                WebClient client = null;
                try
                {
                    IDictionary<string, object> json;
                    string characters;
                    byte[] bytes;
                    byte[] response;
                    string responseCharacters;
                    IReadOnlyDictionary<string, object> responseJson;
                    Core2EnterpriseUser user;
                    Member member;
                    IReadOnlyCollection<Member> members;

                    client = new WebClient();
                    
                    identifierMemberOne = Guid.NewGuid().ToString();
                    string identifierMemberOneExternal = Guid.NewGuid().ToString();
                    user =
                        new Core2EnterpriseUser()
                        {
                            Identifier = identifierMemberOne,
                            ExternalIdentifier = identifierMemberOneExternal
                        };

                    json = user.ToJson();
                    characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                    bytes = Encoding.UTF8.GetBytes(characters);
                    resource = new Uri(addressBase, WebServiceUnitTest.AddressRelativeUsers);
                    client.Headers.Clear();
                    client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                    response = client.UploadData(resource.AbsoluteUri, WebRequestMethods.Http.Post, bytes);
                    responseCharacters = Encoding.UTF8.GetString(response);
                    responseJson =
                        WebServiceUnitTest.Serializer.Value.Deserialize<Dictionary<string, object>>(responseCharacters);
                    user = new Core2EnterpriseUserJsonDeserializingFactory().Create(responseJson);
                    identifierMemberOne = user.Identifier;

                    try
                    {
                        member = 
                            new Member()
                            {
                                Value = identifierMemberOne
                            };
                        members =
                            new Member[]
                                {
                                    member
                                };

                        identifierGroup = Guid.NewGuid().ToString();
                        identifierGroupExternal = Guid.NewGuid().ToString();

                        WindowsAzureActiveDirectoryGroup group =
                            new WindowsAzureActiveDirectoryGroup()
                            {
                                Identifier = identifierGroup,
                                ExternalIdentifier = identifierGroupExternal,
                                Members = members
                            };

                        json = group.ToJson();
                        characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                        bytes = Encoding.UTF8.GetBytes(characters);
                        resource = new Uri(addressBase, WebServiceUnitTest.AddressRelativeGroups);
                        client.Headers.Clear();
                        client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                        response = client.UploadData(resource.AbsoluteUri, WebRequestMethods.Http.Post, bytes);
                        responseCharacters = Encoding.UTF8.GetString(response);
                        responseJson =
                            WebServiceUnitTest.Serializer.Value.Deserialize<Dictionary<string, object>>(responseCharacters);
                        group = new WindowsAzureActiveDirectoryGroupJsonDeserializingFactory().Create(responseJson);
                        Assert.IsNotNull(group);
                        Assert.IsNotNull(
                            group
                            .Schemas
                            .SingleOrDefault(
                                (string item) =>
                                    string.Equals(
                                        SchemaIdentifiers.WindowsAzureActiveDirectoryGroup,
                                        item,
                                        StringComparison.Ordinal)));
                        Assert.IsFalse(string.IsNullOrWhiteSpace(group.Identifier));

                        string identifierGroupAmazon = group.Identifier;

                        try
                        {
                            Assert.IsNotNull(group.Metadata);
                            Assert.IsFalse(string.IsNullOrWhiteSpace(group.Metadata.ResourceType));
                            Assert.IsFalse(string.Equals(identifierGroup, identifierGroupAmazon, StringComparison.OrdinalIgnoreCase));

                            string resourcePath = 
                                string.Format(
                                    CultureInfo.InvariantCulture, 
                                    WebServiceUnitTest.AddressRelativeGroupTemplate, 
                                    identifierGroupAmazon);
                            resource = new Uri(addressBase, resourcePath);

                            response = client.DownloadData(resource);
                            responseCharacters = Encoding.UTF8.GetString(response);
                            responseJson =
                                WebServiceUnitTest.Serializer.Value.Deserialize<Dictionary<string, object>>(responseCharacters);
                            group = new WindowsAzureActiveDirectoryGroupJsonDeserializingFactory().Create(responseJson);
                            Assert.IsNotNull(group);
                            Assert.IsNotNull(
                                group
                                .Schemas
                                .SingleOrDefault(
                                    (string item) =>
                                        string.Equals(
                                            SchemaIdentifiers.Core2Group,
                                            item,
                                            StringComparison.Ordinal)));
                            Assert.IsFalse(string.IsNullOrWhiteSpace(group.Identifier));
                            Assert.IsTrue(string.Equals(group.Identifier, identifierGroupAmazon, StringComparison.OrdinalIgnoreCase));

                            Assert.IsFalse(string.IsNullOrWhiteSpace(group.ExternalIdentifier));
                            Assert.IsTrue(string.Equals(group.ExternalIdentifier, identifierGroupExternal, StringComparison.OrdinalIgnoreCase));

                            identifierMemberTwo = Guid.NewGuid().ToString();
                            string identifierMemberTwoExternal = Guid.NewGuid().ToString();
                            user =
                                new Core2EnterpriseUser()
                                {
                                    Identifier = identifierMemberTwo,
                                    ExternalIdentifier = identifierMemberTwoExternal
                                };

                            json = user.ToJson();
                            characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                            bytes = Encoding.UTF8.GetBytes(characters);
                            resource = new Uri(addressBase, WebServiceUnitTest.AddressRelativeUsers);
                            client.Headers.Clear();
                            client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                            response = client.UploadData(resource.AbsoluteUri, WebRequestMethods.Http.Post, bytes);
                            responseCharacters = Encoding.UTF8.GetString(response);
                            responseJson =
                                WebServiceUnitTest.Serializer.Value.Deserialize<Dictionary<string, object>>(responseCharacters);
                            user = new Core2EnterpriseUserJsonDeserializingFactory().Create(responseJson);
                            identifierMemberTwo = user.Identifier;

                            try
                            {
                                IResourceIdentifier resourceIdentifier =
                                    new ResourceIdentifier()
                                    {
                                        Identifier = identifierGroupAmazon,
                                        SchemaIdentifier = SchemaIdentifiers.WindowsAzureActiveDirectoryGroup
                                    };

                                IPath path = Microsoft.SystemForCrossDomainIdentityManagement.Path.Create(AttributeNames.Members);

                                OperationValue operationValue;
                                PatchOperation operation;
                                IReadOnlyCollection<PatchOperation> operations;
                                PatchRequest2 patch;
                                                                
                                operationValue =
                                    new OperationValue()
                                    {
                                        Value = identifierMemberTwo
                                    };
                                operation =
                                    new PatchOperation()
                                    {
                                        Name = OperationName.Add,
                                        Path = path
                                    };
                                operations =
                                    new PatchOperation[] 
                                        { 
                                            operation 
                                        };
                                operation.AddValue(operationValue);                                
                                
                                patch = new PatchRequest2();
                                patch.AddOperation(operation);
                                json = patch.ToJson();
                                characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                                bytes = Encoding.UTF8.GetBytes(characters);
                                resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeGroup, identifierGroupAmazon);
                                resource = new Uri(addressBase, resourcePath);
                                client.Headers.Clear();
                                client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                                response = client.UploadData(resource.AbsoluteUri, WebServiceUnitTest.MethodPatch, bytes);

                                operationValue =
                                   new OperationValue()
                                   {
                                       Value = identifierMemberTwo
                                   };
                                operation =
                                    new PatchOperation()
                                    {
                                        Name = OperationName.Remove,
                                        Path = path
                                    };
                                operations =
                                    new PatchOperation[] 
                                        { 
                                            operation 
                                        };
                                operation.AddValue(operationValue);

                                patch = new PatchRequest2();
                                patch.AddOperation(operation);
                                json = patch.ToJson();
                                characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                                bytes = Encoding.UTF8.GetBytes(characters);
                                resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeGroup, identifierGroupAmazon);
                                resource = new Uri(addressBase, resourcePath);
                                client.Headers.Clear();
                                client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                                response = client.UploadData(resource.AbsoluteUri, WebServiceUnitTest.MethodPatch, bytes);

                                operationValue =
                                   new OperationValue()
                                   {
                                       Value = identifierMemberOne
                                   };
                                operation =
                                    new PatchOperation()
                                    {
                                        Name = OperationName.Remove,
                                        Path = path
                                    };
                                operations =
                                    new PatchOperation[] 
                                        { 
                                            operation 
                                        };
                                operation.AddValue(operationValue);

                                patch = new PatchRequest2();
                                patch.AddOperation(operation);
                                json = patch.ToJson();
                                characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                                bytes = Encoding.UTF8.GetBytes(characters);
                                resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeGroup, identifierGroupAmazon);
                                resource = new Uri(addressBase, resourcePath);
                                client.Headers.Clear();
                                client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                                response = client.UploadData(resource.AbsoluteUri, WebServiceUnitTest.MethodPatch, bytes);
                            }
                            finally
                            {
                                resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeUser, identifierMemberTwo);
                                resource = new Uri(addressBase, resourcePath);
                                bytes = new byte[0];
                                client.UploadData(resource, WebServiceUnitTest.MethodDelete, bytes);
                            }
                        }
                        finally
                        {
                            string resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeGroup, identifierGroupAmazon);
                            resource = new Uri(addressBase, resourcePath);
                            bytes = new byte[0];
                            client.UploadData(resource, WebServiceUnitTest.MethodDelete, bytes);
                        }
                    }
                    finally
                    {
                        string resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeUser, identifierMemberOne);
                        resource = new Uri(addressBase, resourcePath);
                        bytes = new byte[0];
                        client.UploadData(resource, WebServiceUnitTest.MethodDelete, bytes);
                    }
                }
                finally
                {
                    if (client != null)
                    {
                        client.Dispose();
                        client = null;
                    }
                }
            }
            finally
            {
                if (webService != null)
                {
                    webService.Dispose();
                    webService = null;
                }
            }
        }
        private async Task UpdateMembers(
            IResourceIdentifier resourceIdentifier,
            PatchOperation membershipOperation,
            string correlationIdentifier)
        {
            if (null == resourceIdentifier)
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameResourceIdentifier);
            }

            if (null == membershipOperation)
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameMembershipOperation);
            }

            if (string.IsNullOrWhiteSpace(correlationIdentifier))
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameCorrelationIdentifier);
            }

            if (string.IsNullOrWhiteSpace(resourceIdentifier.Identifier))
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidResourceIdentifier);
            }

            if (string.IsNullOrWhiteSpace(resourceIdentifier.SchemaIdentifier))
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidResourceIdentifier);
            }

            IAmazonIdentityManagementService proxy = null;
            try
            {
                proxy = AWSClientFactory.CreateAmazonIdentityManagementServiceClient(this.credentials);

                Group group = await this.RetrieveGroup(resourceIdentifier.Identifier, proxy);
                if (null == group)
                {
                    string warning =
                    string.Format(
                        CultureInfo.InvariantCulture,
                        AmazonProvisioningAgentResources.WarningEntryNotFoundTemplate,
                        typeof(Group).Name,
                        resourceIdentifier.Identifier);
                    ProvisioningAgentMonitor.Instance.Warn(warning, correlationIdentifier);
                    return;
                }

                switch (membershipOperation.Name)
                {
                    case OperationName.Add:
                        foreach (OperationValue value in membershipOperation.Value)
                        {
                            await this.AddMember(group.GroupName, value.Value, proxy, correlationIdentifier);
                        }
                        break;
                    case OperationName.Remove:
                        foreach (OperationValue value in membershipOperation.Value)
                        {
                            await this.RemoveMember(group.GroupName, value.Value, proxy, correlationIdentifier);
                        }
                        break;
                    default:
                        string unsupportedOperation = Enum.GetName(typeof(OperationName), membershipOperation.Name);
                        throw new NotSupportedException(unsupportedOperation);
                }
            }
            finally
            {
                if (proxy != null)
                {
                    proxy.Dispose();
                    proxy = null;
                }
            }
        }