public async Task<ActionResult> Edit(int id, Expense expense)
        {
            try
            {
                var client = ExpenseTrackerHttpClient.GetClient();


                // create a JSON Patch Document
                JsonPatchDocument<DTO.Expense> patchDoc = new JsonPatchDocument<DTO.Expense>();
                patchDoc.Replace(e => e.Amount, expense.Amount);
                patchDoc.Replace(e => e.Date, expense.Date);
                patchDoc.Replace(e => e.Description, expense.Description);

                // serialize and PATCH
                var serializedItemToUpdate = JsonConvert.SerializeObject(patchDoc);

                var response = await client.PatchAsync("api/expenses/" + id,
                    new StringContent(serializedItemToUpdate,
                    System.Text.Encoding.Unicode, "application/json"));

                if (response.IsSuccessStatusCode)
                {
                    return RedirectToAction("Details", "ExpenseGroups", new { id = expense.ExpenseGroupId });
                }
                else
                {
                    return Content("An error occurred");
                }

            }
            catch
            {
                return Content("An error occurred");
            }
        }
        public void SerializeAndReplaceNestedObjectTest()
        {
            var doc = new SimpleDTOWithNestedDTO()
            {
                SimpleDTO = new SimpleDTO()
                {
                    IntegerValue = 5,
                    IntegerList = new List<int>() { 1, 2, 3 }
                }
            };

            var newDTO = new SimpleDTO()
            {
                DoubleValue = 1
            };

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Replace("SimpleDTO", newDTO);

            // serialize & deserialize 
            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);

            deserialized.ApplyTo(doc);

            Assert.Equal(1, doc.SimpleDTO.DoubleValue);
            Assert.Equal(0, doc.SimpleDTO.IntegerValue);
            Assert.Equal(null, doc.SimpleDTO.IntegerList);
        }
示例#3
1
        public async static void ExampleDoc()
        {
            // Authenticate
            var identity = new CloudIdentity
            {
                APIKey = "{apikey}",
                Username = "******"
            };
            var authProvider = new CloudIdentityProvider(identity);
            var cdnService = new ContentDeliveryNetworkService(authProvider, "{region}");

            // List Flavors
            IEnumerable<Flavor> flavors = await cdnService.ListFlavorsAsync();

            // Get Flavor
            Flavor flavor = await cdnService.GetFlavorAsync("{flavorId}");

            // Create Service
            ServiceDefinition serviceDefinition = new ServiceDefinition("example_site", "{flavorId}",
                domains: new[] {new ServiceDomain("www.example.com")},
                origins: new[] {new ServiceOrigin("example.com")});
            string serviceId = await cdnService.CreateServiceAsync(serviceDefinition);
            await cdnService.WaitForServiceDeployedAsync(serviceId);

            // List Services
            IPage<Service> services = await cdnService.ListServicesAsync();

            // Get Service
            Service service = await cdnService.GetServiceAsync("{serviceId}");

            // Purge All Service Assets
            await cdnService.PurgeCachedAssetsAsync("{serviceId}");

            // Purge a Specific Service Asset
            await cdnService.PurgeCachedAssetAsync("{serviceId}", "{relativeUrlOfAsset}");

            // Update Service
            var patch = new JsonPatchDocument<ServiceDefinition>();
            patch.Replace(svc => svc.Name, "newServiceName");
            await cdnService.UpdateServiceAsync("{serviceId}", patch);
            await cdnService.WaitForServiceDeployedAsync("{serviceId}");

            // Delete Service
            await cdnService.DeleteServiceAsync("{serviceId}");
            await cdnService.WaitForServiceDeletedAsync("{serviceId}");
        }
        private async Task SaveExpense()
        {
            // partial update

            var client = ExpenseTrackerHttpClient.GetClient();

            // create a patch document, containing the (possible) changes to the
            // expense DTO
 
            JsonPatchDocument<DTO.Expense> patchDoc = new JsonPatchDocument<DTO.Expense>();
            patchDoc.Replace(e => e.Description, Expense.Description);

            // serialize & PATCH
            var serializedItemToUpdate = JsonConvert.SerializeObject(patchDoc);


            var response = client.PatchAsync("api/expenses/" + Expense.Id,
                new StringContent(serializedItemToUpdate,
                System.Text.Encoding.Unicode, "application/json")).Result;

            if (response.IsSuccessStatusCode)
            {
                // return to the expense list
                App.RootFrame.Navigate(typeof(ExpensesView), true);

            }
            else
            {
                // error: handle, log, ...
            }
            
        }
        public void AddToListInListInvalidPositionTooLarge()
        {
            var doc = new SimpleDTOWithNestedDTO()
            {
                ListOfSimpleDTO = new List<SimpleDTO>()
                {
                     new SimpleDTO()
                     {
                        IntegerList = new List<int>() { 1, 2, 3 }
                     }
                }
            };
            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Add("ListOfSimpleDTO/20/IntegerList/0", 4);

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);

            var exception = Assert.Throws<JsonPatchException>(() =>
            {
                deserialized.ApplyTo(doc);
            });
            Assert.Equal(
                "The property at path '/ListOfSimpleDTO/20/IntegerList/0' could not be added.",
                exception.Message);
        }
        public void Remove_InvalidPath_ThrowsJsonPatchParseException()
        {
            //Arrange
            var patchDocument = new JsonPatchDocument<SimpleEntity>();

            //Act
            patchDocument.Remove("FooMissing");
        }
示例#7
0
        public async Task CreateAServiceOnAkamai_UsingDefaults()
        {
            Trace.WriteLine("Looking for a CDN flavor provided by Akamai...");
            var flavors = await _cdnService.ListFlavorsAsync();
            var flavor = flavors.FirstOrDefault(x => x.Providers.Any(p => string.Equals(p.Name, "Akamai", StringComparison.OrdinalIgnoreCase)));
            Assert.NotNull(flavor);
            var akamaiFlavor = flavor.Id;
            Trace.WriteLine(string.Format("Found the {0} flavor", akamaiFlavor));

            Trace.WriteLine("Creating a CDN service using defaults for anything I can omit...");
            var domains = new[] {new ServiceDomain("mirror.example.com")};
            var origins = new[] {new ServiceOrigin("example.com")};
            var serviceDefinition = new ServiceDefinition("ci-test", akamaiFlavor, domains, origins);
            var serviceId = await _cdnService.CreateServiceAsync(serviceDefinition);
            Trace.WriteLine(string.Format("Service was created: {0}", serviceId));

            try
            {
                Trace.WriteLine("Waiting for the service to be deployed...");
                var service = await _cdnService.WaitForServiceDeployedAsync(serviceId, progress: new Progress<bool>(x => Trace.WriteLine("...")));

                Trace.WriteLine("Verifying service matches the requested definition...");
                Assert.Equal("ci-test", service.Name);
                Assert.Equal(serviceDefinition.FlavorId, service.FlavorId);

                Assert.Equal(serviceDefinition.Origins.Count, service.Origins.Count());
                Assert.Equal(serviceDefinition.Origins.First().Origin, service.Origins.First().Origin);

                Assert.Equal(serviceDefinition.Domains.Count, service.Domains.Count());
                Assert.Equal(serviceDefinition.Domains.First().Domain, service.Domains.First().Domain);

                Trace.WriteLine("Updating the service...");
                var patch = new JsonPatchDocument<ServiceDefinition>();
                patch.Replace(x => x.Name, "ci-test2");
                var intranetOnly = new ServiceRestriction("intranet", new[] {new ServiceRestrictionRule("intranet", "intranet.example.com")});
                patch.Add(x => x.Restrictions, intranetOnly, 0);
                await _cdnService.UpdateServiceAsync(serviceId, patch);

                Trace.WriteLine("Waiting for the service changes to be deployed...");
                service = await _cdnService.WaitForServiceDeployedAsync(serviceId, progress: new Progress<bool>(x => Trace.WriteLine("...")));

                Trace.WriteLine("Verifying service matches updated definition...");
                Assert.Equal("ci-test2", service.Name);
                Assert.Equal(JsonConvert.SerializeObject(intranetOnly), JsonConvert.SerializeObject(service.Restrictions.First()));

                Trace.WriteLine("Purging all assets on service");
                await _cdnService.PurgeCachedAssetsAsync(serviceId);
            }
            finally
            {
                Trace.WriteLine("Cleaning up any test data...");

                Trace.WriteLine("Removing the service...");
                _cdnService.DeleteService(serviceId);
                _cdnService.WaitForServiceDeleted(serviceId);
                Trace.WriteLine("The service was cleaned up sucessfully.");
            }
        }
 public void WHEN_Patch1_is_applied_THEN_sum_change_to_correct_value()
 {
     var basket = JsonConvert.DeserializeObject<StockMarketOrders>(TestData.ORIGINAL_DATA);
     var patch = JsonConvert.DeserializeObject<List<Operation<StockMarketOrders>>>(TestData.PATCH_1);
     JsonPatchDocument<StockMarketOrders> doc = new JsonPatchDocument<StockMarketOrders>(patch);
     doc.ApplyTo(basket);
     var sum = basket.Select(x => x.Price).Sum();
     var expectedSum = 718 - 60 + 95;
     //on patch one only one value changed from 60 to 95
     Check.That(sum).IsEqualTo(expectedSum);
 }
示例#9
0
 public void InvalidPathWithDotShouldThrowException()
 {
     JsonPatchDocument patchDoc = new JsonPatchDocument();
     var exception = Assert.Throws<JsonPatchException>(() =>
     {
         patchDoc.Add("NewInt.Test", 1);
     });
     Assert.Equal(
        "The provided string 'NewInt.Test' is an invalid path.",
         exception.Message);
 }
 public void WHEN_Patch2_is_applied_with_multiples_changes_THEN_sum_change_to_correct_value()
 {
     var basket = JsonConvert.DeserializeObject<StockMarketOrders>(TestData.ORIGINAL_DATA);
     var patch = JsonConvert.DeserializeObject<List<Operation<StockMarketOrders>>>(TestData.PATCH_2);
     JsonPatchDocument<StockMarketOrders> doc = new JsonPatchDocument<StockMarketOrders>(patch);
     doc.ApplyTo(basket);
     var sum = basket.Select(x => x.Price).Sum();
     //expected = original sum + sum(- item source price + item new price)
     var expectedSum = 718 + (-78 + 0) + (-77 + 13) + (-22 + 27);
     Check.That(sum).IsEqualTo(expectedSum);//=581
 }
 public void WHEN_Two_patches_are_applied_THEN_sum_change_to_correct_value()
 {
     var basket = JsonConvert.DeserializeObject<StockMarketOrders>(TestData.ORIGINAL_DATA);
     var patch1 = JsonConvert.DeserializeObject<List<Operation<StockMarketOrders>>>(TestData.PATCH_1);
     var patch2 = JsonConvert.DeserializeObject<List<Operation<StockMarketOrders>>>(TestData.PATCH_2);
     JsonPatchDocument<StockMarketOrders> documentPatcher1 = new JsonPatchDocument<StockMarketOrders>(patch1);
     JsonPatchDocument<StockMarketOrders> documentPatcher2 = new JsonPatchDocument<StockMarketOrders>(patch2);
     documentPatcher1.ApplyTo(basket);
     documentPatcher2.ApplyTo(basket);
     var sum = basket.Select(x => x.Price).Sum();
     Check.That(sum).IsEqualTo(616);
 }
        public void Replace_ValidPath_OperationAdded()
        {
            //Arrange
            var patchDocument = new JsonPatchDocument<SimpleEntity>();

            //Act
            patchDocument.Replace("Foo", "bar");

            //Assert
            Assert.AreEqual(1, patchDocument.Operations.Count);
            Assert.AreEqual(JsonPatchOperationType.replace, patchDocument.Operations.Single().Operation);
        }
示例#13
0
        public void ReplaceAtEndOfList()
        {
            dynamic doc = new ExpandoObject();
            doc.IntegerList = new List<int>() { 1, 2, 3 };

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Replace("IntegerList/-", 5);

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);
            deserialized.ApplyTo(doc);

            Assert.Equal(new List<int>() { 1, 2, 5 }, doc.IntegerList);
        }
示例#14
0
        public void CopyFromListToEndOfList()
        {
            dynamic doc = new ExpandoObject();
            doc.IntegerList = new List<int>() { 1, 2, 3 };

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Copy("IntegerList/0", "IntegerList/-");

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);
            deserialized.ApplyTo(doc);

            Assert.Equal(new List<int>() { 1, 2, 3, 1 }, doc.IntegerList);
        }
示例#15
0
        public void ReplaceFullListFromEnumerable()
        {
            dynamic doc = new ExpandoObject();
            doc.IntegerList = new List<int>() { 1, 2, 3 };

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Replace("IntegerList", new List<int>() { 4, 5, 6 });

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);

            deserialized.ApplyTo(doc);
            Assert.Equal(new List<int>() { 4, 5, 6 }, doc.IntegerList);
        }
示例#16
0
        public void AddToList()
        {
            var doc = new SimpleDTO()
            {
                IntegerList = new List<int>() { 1, 2, 3 }
            };

            // create patch
            JsonPatchDocument<SimpleDTO> patchDoc = new JsonPatchDocument<SimpleDTO>();
            patchDoc.Add<int>(o => o.IntegerList, 4, 0);

            patchDoc.ApplyTo(doc);

            Assert.Equal(new List<int>() { 4, 1, 2, 3 }, doc.IntegerList);
        }
示例#17
0
        public void Copy()
        {
            dynamic doc = new ExpandoObject();

            doc.StringProperty = "A";
            doc.AnotherStringProperty = "B";

            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Copy("StringProperty", "AnotherStringProperty");

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);
            deserialized.ApplyTo(doc);

            Assert.Equal("A", doc.AnotherStringProperty);
        }
        public void MoveFromListToEndOfList()
        {
            var doc = new SimpleDTO()
            {
                IntegerList = new List<int>() { 1, 2, 3 }
            };

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Move("IntegerList/0", "IntegerList/-");

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);
            deserialized.ApplyTo(doc);

            Assert.Equal(new List<int>() { 2, 3, 1 }, doc.IntegerList);
        }
示例#19
0
        public void AddNewProperty()
        {
            dynamic obj = new ExpandoObject();
            obj.Test = 1;

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Add("NewInt", 1);

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);

            deserialized.ApplyTo(obj);

            Assert.Equal(1, obj.NewInt);
            Assert.Equal(1, obj.Test);
        }
示例#20
0
        public void MoveFomListToNonList()
        {
            dynamic doc = new ExpandoObject();
            doc.IntegerList = new List<int>() { 1, 2, 3 };

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Move("IntegerList/0", "IntegerValue");

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);

            deserialized.ApplyTo(doc);

            Assert.Equal(new List<int>() { 2, 3 }, doc.IntegerList);
            Assert.Equal(1, doc.IntegerValue);
        }
        public void ReplacePropertyInNestedObject()
        {
            var doc = new SimpleDTOWithNestedDTO()
            {
                IntegerValue = 1

            };

            // create patch
            JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>();
            patchDoc.Replace<string>(o => o.NestedDTO.StringProperty, "B");

            patchDoc.ApplyTo(doc);

            Assert.Equal("B", doc.NestedDTO.StringProperty);

        }
示例#22
0
        public void NestedRemoveFromEndOfList()
        {
            dynamic doc = new ExpandoObject();
            doc.SimpleDTO = new SimpleDTO()
            {
                IntegerList = new List<int>() { 1, 2, 3 }
            };

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Remove("SimpleDTO/IntegerList/-");

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);

            deserialized.ApplyTo(doc);
            Assert.Equal(new List<int>() { 1, 2 }, doc.SimpleDTO.IntegerList);
        }
        public void Copy()
        {
            var doc = new SimpleDTO()
            {
                StringProperty = "A",
                AnotherStringProperty = "B"
            };

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Copy("StringProperty", "AnotherStringProperty");

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);
            deserialized.ApplyTo(doc);

            Assert.Equal("A", doc.AnotherStringProperty);
        }
        public void ReplaceGuidTestExpandoObject()
        {
            dynamic doc = new ExpandoObject();
            doc.GuidValue = Guid.NewGuid();

            var newGuid = Guid.NewGuid();
            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Replace("GuidValue", newGuid);

            // serialize & deserialize 
            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserizalized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);

            deserizalized.ApplyTo(doc);

            Assert.Equal(newGuid, doc.GuidValue);
        }
示例#25
0
        public void NonGenericPatchDocToGenericMustSerialize()
        {
            var doc = new SimpleDTO()
            {
                StringProperty = "A",
                AnotherStringProperty = "B"
            };

            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Copy("StringProperty", "AnotherStringProperty");

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument<SimpleDTO>>(serialized);

            deserialized.ApplyTo(doc);

            Assert.Equal("A", doc.AnotherStringProperty);
        }
示例#26
0
        public void NestedRemove()
        {
            dynamic doc = new ExpandoObject();
            doc.SimpleDTO = new SimpleDTO()
            {
                StringProperty = "A"
            };

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Remove("SimpleDTO/StringProperty");

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);

            deserialized.ApplyTo(doc);
            Assert.Equal(null, doc.SimpleDTO.StringProperty);
        }
示例#27
0
        public void AddResultsShouldReplace()
        {
            var doc = new SimpleDTO()
            {
                StringProperty = "A"
            };

            // create patch
            JsonPatchDocument<SimpleDTO> patchDoc = new JsonPatchDocument<SimpleDTO>();
            patchDoc.Add<string>(o => o.StringProperty, "B");

            patchDoc.ApplyTo(doc);

            var s = new Operations.Operation();

            Assert.Equal("B", doc.StringProperty);
          
        }
        public void CopyFromListToNonList()
        {
            var doc = new SimpleDTO()
            {
                IntegerList = new List<int>() { 1, 2, 3 }
            };

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Copy("IntegerList/0", "IntegerValue");

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);

            deserialized.ApplyTo(doc);

            Assert.Equal(1, doc.IntegerValue);
        }
示例#29
0
        public void AddResultsShouldReplace()
        {
            // Arrange
            var doc = new SimpleDTO()
            {
                StringProperty = "A"
            };

            // create patch
            var patchDoc = new JsonPatchDocument<SimpleDTO>();
            patchDoc.Add<string>(o => o.StringProperty, "B");

            // Act
            patchDoc.ApplyTo(doc);

            // Assert
            Assert.Equal("B", doc.StringProperty);
        }
        public void ReplaceInList()
        {
            var doc = new SimpleDTO()
            {
                IntegerList = new List<int>() { 1, 2, 3 }
            };

            // create patch
            JsonPatchDocument patchDoc = new JsonPatchDocument();
            patchDoc.Replace("IntegerList/0", 5);

            var serialized = JsonConvert.SerializeObject(patchDoc);
            var deserialized = JsonConvert.DeserializeObject<JsonPatchDocument>(serialized);

            deserialized.ApplyTo(doc);

            Assert.Equal(new List<int>() { 5, 2, 3 }, doc.IntegerList);
        }
示例#31
0
 public async Task <IActionResult> UpdateCurrentUser([FromBody] JsonPatchDocument <UserPatchViewModel> patch)
 {
     return(await UpdateUser(Utilities.GetUserId(this.User), patch));
 }
示例#32
0
        public string QueryAndUpdateWorkItems()
        {
            string project = _configuration.Project;

            // create a query to get your list of work items needed
            Wiql wiql = new Wiql()
            {
                Query = "Select [State], [Title] " +
                        "From WorkItems " +
                        "Where [Work Item Type] = 'Bug' " +
                        "And [System.TeamProject] = '" + project + "' " +
                        "And [System.State] = 'New' " +
                        "Order By [State] Asc, [Changed Date] Desc"
            };


            // create a patchDocument that is used to update the work items
            JsonPatchDocument patchDocument = new JsonPatchDocument();

            // change the backlog priority
            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/Microsoft.VSTS.Common.BacklogPriority",
                Value     = "2",
                From      = _configuration.Identity
            }
                );

            // move the state to active
            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.State",
                Value     = "Active",
                From      = _configuration.Identity
            }
                );

            // add some comments
            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.History",
                Value     = "comment from client lib sample code",
                From      = _configuration.Identity
            }
                );

            VssConnection connection = new VssConnection(_uri, _credentials);
            WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>();

            // execute the query
            WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;

            // check to make sure we have some results
            if (workItemQueryResult == null || workItemQueryResult.WorkItems.Count() == 0)
            {
                throw new NullReferenceException("Wiql '" + wiql.Query + "' did not find any results");
            }

            // loop thru the work item results and update each work item
            foreach (WorkItemReference workItemReference in workItemQueryResult.WorkItems)
            {
                WorkItem result = workItemTrackingHttpClient.UpdateWorkItemAsync(patchDocument, workItemReference.Id).Result;
            }

            wiql          = null;
            patchDocument = null;

            return("success");
        }
示例#33
0
        public string CreateBugByPassingRules()
        {
            string project = _configuration.Project;

            JsonPatchDocument patchDocument = new JsonPatchDocument();

            // add fields to your patch document
            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.Title",
                Value     = "Imported bug from my other system (client lib)"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/Microsoft.VSTS.TCM.ReproSteps",
                Value     = "Our authorization logic needs to allow for users with Microsoft accounts (formerly Live Ids) - http:// msdn.microsoft.com/en-us/library/live/hh826547.aspx"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.CreatedBy",
                Value     = "Some User"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.ChangedBy",
                Value     = "Some User"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.CreatedDate",
                Value     = "4/15/2016"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.History",
                Value     = "Data imported from source"
            }
                );

            VssConnection connection = new VssConnection(_uri, _credentials);
            WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>();

            // create the bug
            WorkItem result = workItemTrackingHttpClient.CreateWorkItemAsync(patchDocument, project, "Bug", null, true).Result;

            patchDocument = null;

            return("success");
        }
示例#34
0
 public override async Task <IActionResult> PartiallyUpdate(int id, JsonPatchDocument <ZdravstvenaKnjizicaUpsertDto> patchDocument)
 {
     return(await base.PartiallyUpdate(id, patchDocument));
 }
        public async Task <IActionResult> PatchCategoriesTreeNode(Guid id, Guid nodeId, [FromBody] JsonPatchDocument <UpdateCategoryTreeRequest> request, int version)
        {
            //TODO: Validate input parapeters e.g. title
            var treeView = await _categoryTreeCollection.Find(new BsonDocument("_id", id)).FirstOrDefaultAsync();

            if (treeView == null)
            {
                return(NotFound());
            }

            var tree = await _session.Get <CategoryTree>(id);

            if (!tree.Nodes.ContainsTree(nodeId))
            {
                return(NotFound());
            }

            var operations = new UpdateCategoryTreeRequest();

            request.ApplyTo(operations);

            if (operations.Nodes.Any())
            {
                operations.Nodes.InitNodeIds();

                await Bus.Publish <UpdateCategoryTree>(new
                {
                    Id              = id,
                    ParentId        = nodeId,
                    UserId          = UserId,
                    Nodes           = operations.Nodes,
                    ExpectedVersion = version
                });
            }

            if (operations.IsDeleted)
            {
                await Bus.Publish <DeleteCategoryTreeNode>(new
                {
                    Id     = id,
                    NodeId = nodeId,
                    UserId,
                    ExpectedVersion = version
                });
            }

            return(Accepted());
        }
示例#36
0
        private async Task <ApiProductModelIllustrationRequestModel> PatchModel(int id, JsonPatchDocument <ApiProductModelIllustrationRequestModel> patch)
        {
            var record = await this.ProductModelIllustrationService.Get(id);

            if (record == null)
            {
                return(null);
            }
            else
            {
                ApiProductModelIllustrationRequestModel request = this.ProductModelIllustrationModelMapper.MapResponseToRequest(record);
                patch.ApplyTo(request);
                return(request);
            }
        }
示例#37
0
        private async Task MigrateWorkItemRelationsAsync(MigrationContext context, IEnumerable <WorkItemRelation> relations, WorkItem targetItem, CancellationToken cancellationToken)
        {
            var doc = new JsonPatchDocument();

            foreach (var relation in relations)
            {
                var isChild   = relation.IsChild();
                var isParent  = !isChild && relation.IsParent();
                var isRelated = !isChild && !isParent && relation.IsRelated();

                //Not a relation we care about
                if (!isChild && !isParent && !isRelated)
                {
                    continue;
                }

                //Get the related item information
                var relatedId = relation.GetRelatedId();
                if (relatedId <= 0)
                {
                    continue;
                }

                var related = context.GetMigratedWorkItem(relatedId);

                if (isChild)
                {
                    //If the child has been migrated then add a child link to the related item
                    //else if the target isn't closed (or the override setting is set) then add the related item to migration list
                    if (related != null)
                    {
                        if (related.TargetId != 0)
                        {
                            Logger.Debug($"Adding Child link to {related.TargetId}");
                            doc.AddLink(WorkItemRelations.Child, related.TargetUrl);
                        }
                        else
                        {
                            Logger.Warning($"Skipping Child link to {related.SourceId} because it failed to migrate");
                        }
                    }
                    else if (!targetItem.IsClosed() || Settings.IncludeChildLinksOnClosed)
                    {
                        Logger.Debug($"Adding Child link {relatedId} to migration list");
                        AddToMigrationQueue(context.MigrationQueue, new MigratedWorkItem()
                        {
                            SourceId = relatedId
                        });
                    }
                    ;
                }
                else if (isParent)
                {
                    //If the parent has already been migrated then add a parent link to the related item
                    if (related != null)
                    {
                        if (related.TargetId != 0)
                        {
                            Logger.Debug($"Adding Parent link to {related.TargetId}");
                            doc.AddLink(WorkItemRelations.Parent, related.TargetUrl);
                        }
                        else
                        {
                            Logger.Warning($"Skipping Parent link to {related.SourceId} because it failed to migrate");
                        }
                    }
                    else if (!targetItem.IsClosed() || Settings.IncludeParentLinksOnClosed)
                    {
                        Logger.Debug($"Adding Parent link {relatedId} to migration list");
                        AddToMigrationQueue(context.MigrationQueue, new MigratedWorkItem()
                        {
                            SourceId = relatedId
                        });
                    }
                    ;
                }
                else if (isRelated)
                {
                    //If the related item has already been migrated then add a related link to it
                    //else if the target is not closed (or the override setting is set) then add the related item to the migration list
                    if (related != null)
                    {
                        if (related.TargetId != 0)
                        {
                            Logger.Debug($"Adding Related link to {related.TargetId}");
                            doc.AddLink(WorkItemRelations.Related, related.TargetUrl);
                        }
                        else
                        {
                            Logger.Warning($"Skipping Related link to {related.SourceId} because it failed to migrate");
                        }
                    }
                    else if (!targetItem.IsClosed() || Settings.IncludeRelatedLinksOnClosed)
                    {
                        Logger.Debug($"Adding Related link {relatedId} to migration list");
                        AddToMigrationQueue(context.MigrationQueue, new MigratedWorkItem()
                        {
                            SourceId = relatedId
                        });
                    }
                    ;
                }
                ;  //else ignore

                cancellationToken.ThrowIfCancellationRequested();
            }
            ;

            //If we have made any changes then update the target
            if (doc.Any())
            {
                await context.TargetService.UpdateWorkItemUnrestrictedAsync(targetItem, doc, cancellationToken).ConfigureAwait(false);
            }
        }
        public async Task Relationships_Lifecycle()
        {
            // arrange

            DigitalTwinsClient client = GetClient();

            var floorContainsRoomRelationshipId    = "FloorToRoomRelationship";
            var floorCooledByHvacRelationshipId    = "FloorToHvacRelationship";
            var hvacCoolsFloorRelationshipId       = "HvacToFloorRelationship";
            var roomContainedInFloorRelationshipId = "RoomToFloorRelationship";

            string floorModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.FloorModelIdPrefix).ConfigureAwait(false);

            string roomModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.RoomModelIdPrefix).ConfigureAwait(false);

            string hvacModelId = await GetUniqueTwinIdAsync(client, TestAssetDefaults.HvacModelIdPrefix).ConfigureAwait(false);

            string floorTwinId = await GetUniqueTwinIdAsync(client, TestAssetDefaults.FloorTwinIdPrefix).ConfigureAwait(false);

            string roomTwinId = await GetUniqueTwinIdAsync(client, TestAssetDefaults.RoomTwinIdPrefix).ConfigureAwait(false);

            string hvacTwinId = await GetUniqueTwinIdAsync(client, TestAssetDefaults.HvacTwinIdPrefix).ConfigureAwait(false);

            try
            {
                // create floor, room and hvac model
                string floorModel = TestAssetsHelper.GetFloorModelPayload(floorModelId, roomModelId, hvacModelId);
                string roomModel  = TestAssetsHelper.GetRoomModelPayload(roomModelId, floorModelId);
                string hvacModel  = TestAssetsHelper.GetHvacModelPayload(hvacModelId, floorModelId);
                await client.CreateModelsAsync(new List <string> {
                    floorModel, roomModel, hvacModel
                }).ConfigureAwait(false);

                // create floor twin
                BasicDigitalTwin floorTwin = TestAssetsHelper.GetFloorTwinPayload(floorModelId);
                await client.CreateDigitalTwinAsync <BasicDigitalTwin>(floorTwinId, floorTwin).ConfigureAwait(false);

                // Create room twin
                BasicDigitalTwin roomTwin = TestAssetsHelper.GetRoomTwinPayload(roomModelId);
                await client.CreateDigitalTwinAsync <BasicDigitalTwin>(roomTwinId, roomTwin).ConfigureAwait(false);

                // create hvac twin
                BasicDigitalTwin hvacTwin = TestAssetsHelper.GetHvacTwinPayload(hvacModelId);
                await client.CreateDigitalTwinAsync <BasicDigitalTwin>(hvacTwinId, hvacTwin).ConfigureAwait(false);

                BasicRelationship floorContainsRoomPayload                = TestAssetsHelper.GetRelationshipWithPropertyPayload(roomTwinId, ContainsRelationship, "isAccessRestricted", true);
                BasicRelationship floorTwinCoolsRelationshipPayload       = TestAssetsHelper.GetRelationshipPayload(floorTwinId, CoolsRelationship);
                BasicRelationship floorTwinContainedInRelationshipPayload = TestAssetsHelper.GetRelationshipPayload(floorTwinId, ContainedInRelationship);
                BasicRelationship floorCooledByHvacPayload                = TestAssetsHelper.GetRelationshipPayload(hvacTwinId, CooledByRelationship);
                JsonPatchDocument floorContainsRoomUpdatePayload          = new JsonPatchDocument();
                floorContainsRoomUpdatePayload.AppendReplace("/isAccessRestricted", false);

                // CREATE relationships

                // create Relationship from Floor -> Room
                await client
                .CreateRelationshipAsync <BasicRelationship>(
                    floorTwinId,
                    floorContainsRoomRelationshipId,
                    floorContainsRoomPayload)
                .ConfigureAwait(false);

                // create Relationship from Floor -> Hvac
                await client
                .CreateRelationshipAsync <BasicRelationship>(
                    floorTwinId,
                    floorCooledByHvacRelationshipId,
                    floorCooledByHvacPayload)
                .ConfigureAwait(false);

                // create Relationship from Hvac -> Floor
                await client
                .CreateRelationshipAsync <BasicRelationship>(
                    hvacTwinId,
                    hvacCoolsFloorRelationshipId,
                    floorTwinCoolsRelationshipPayload)
                .ConfigureAwait(false);

                // create Relationship from Room -> Floor
                await client
                .CreateRelationshipAsync <BasicRelationship>(
                    roomTwinId,
                    roomContainedInFloorRelationshipId,
                    floorTwinContainedInRelationshipPayload)
                .ConfigureAwait(false);

                // UPDATE relationships

                // create Relationship from Floor -> Room
                await client
                .UpdateRelationshipAsync(
                    floorTwinId,
                    floorContainsRoomRelationshipId,
                    floorContainsRoomUpdatePayload)
                .ConfigureAwait(false);

                // GET relationship
                Response <BasicRelationship> containsRelationshipId = await client
                                                                      .GetRelationshipAsync <BasicRelationship>(
                    floorTwinId,
                    floorContainsRoomRelationshipId)
                                                                      .ConfigureAwait(false);

                // LIST incoming relationships
                AsyncPageable <IncomingRelationship> incomingRelationships = client.GetIncomingRelationshipsAsync(floorTwinId);

                int numberOfIncomingRelationshipsToFloor = 0;
                await foreach (IncomingRelationship relationship in incomingRelationships)
                {
                    ++numberOfIncomingRelationshipsToFloor;
                }
                numberOfIncomingRelationshipsToFloor.Should().Be(2, "floor has incoming relationships from room and hvac");

                // LIST relationships
                AsyncPageable <string> floorRelationships = client.GetRelationshipsAsync(floorTwinId);

                int numberOfFloorRelationships = 0;
                await foreach (var relationship in floorRelationships)
                {
                    ++numberOfFloorRelationships;
                }
                numberOfFloorRelationships.Should().Be(2, "floor has an relationship to room and hvac");

                // LIST relationships by name
                AsyncPageable <string> roomTwinRelationships = client
                                                               .GetRelationshipsAsync(
                    roomTwinId,
                    ContainedInRelationship);
                containsRelationshipId.Value.Id.Should().Be(floorContainsRoomRelationshipId);

                int numberOfRelationships = 0;
                await foreach (var relationship in roomTwinRelationships)
                {
                    ++numberOfRelationships;
                }
                numberOfRelationships.Should().Be(1, "room has only one containedIn relationship to floor");

                await client
                .DeleteRelationshipAsync(
                    floorTwinId,
                    floorContainsRoomRelationshipId)
                .ConfigureAwait(false);

                await client
                .DeleteRelationshipAsync(
                    roomTwinId,
                    roomContainedInFloorRelationshipId)
                .ConfigureAwait(false);

                await client
                .DeleteRelationshipAsync(
                    floorTwinId,
                    floorCooledByHvacRelationshipId)
                .ConfigureAwait(false);

                await client
                .DeleteRelationshipAsync(
                    hvacTwinId,
                    hvacCoolsFloorRelationshipId)
                .ConfigureAwait(false);

                Func <Task> act = async() =>
                {
                    await client
                    .GetRelationshipAsync <BasicRelationship>(
                        floorTwinId,
                        floorContainsRoomRelationshipId)
                    .ConfigureAwait(false);
                };
                act.Should().Throw <RequestFailedException>()
                .And.Status.Should().Be((int)HttpStatusCode.NotFound);

                act = async() =>
                {
                    await client
                    .GetRelationshipAsync <BasicRelationship>(
                        roomTwinId,
                        roomContainedInFloorRelationshipId)
                    .ConfigureAwait(false);
                };
                act.Should().Throw <RequestFailedException>().
                And.Status.Should().Be((int)HttpStatusCode.NotFound);

                act = async() =>
                {
                    await client
                    .GetRelationshipAsync <BasicRelationship>(
                        floorTwinId,
                        floorCooledByHvacRelationshipId)
                    .ConfigureAwait(false);
                };
                act.Should().Throw <RequestFailedException>().
                And.Status.Should().Be((int)HttpStatusCode.NotFound);

                act = async() =>
                {
                    await client
                    .GetRelationshipAsync <BasicRelationship>(
                        hvacTwinId,
                        hvacCoolsFloorRelationshipId)
                    .ConfigureAwait(false);
                };
                act.Should().Throw <RequestFailedException>()
                .And.Status.Should().Be((int)HttpStatusCode.NotFound);
            }
            finally
            {
                // clean up
                try
                {
                    await Task
                    .WhenAll(
                        client.DeleteDigitalTwinAsync(floorTwinId),
                        client.DeleteDigitalTwinAsync(roomTwinId),
                        client.DeleteDigitalTwinAsync(hvacTwinId),
                        client.DeleteModelAsync(hvacModelId),
                        client.DeleteModelAsync(floorModelId),
                        client.DeleteModelAsync(roomModelId))
                    .ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Assert.Fail($"Test clean up failed: {ex.Message}");
                }
            }
        }
示例#39
0
 public Task <CustomerDto> UpdateCustomerPartiallyAsync(int id, JsonPatchDocument <CustomerDto> CustomerPatch)
 {
     throw new NotImplementedException();
 }
示例#40
0
 public async Task <ActionResult> Patch(int id, [FromBody] JsonPatchDocument <Vehicle> patchDoc)
 {
     return(await Patch <Vehicle, VehicleDTO>(id, patchDoc));
 }
 public AccountPatchCommand(string id, JsonPatchDocument <AccountPatchCommand> patchDoc)
 {
     Id            = id;
     this.patchDoc = patchDoc;
 }
示例#42
0
 public async Task <IActionResult> Patch(string id, [FromBody] JsonPatchDocument <EmailLog> request)
 {
     return(await base.PatchEntity(id, request));
 }
示例#43
0
 public IActionResult UpdateUserPartially(Guid userId, [FromBody] JsonPatchDocument <UserRegistrationInfo> user)
 {
     return(Ok());
 }
示例#44
0
        public ActionResult <SuccessResponse> Patch(int id, JsonPatchDocument <CustomerRequest> request)
        {
            var successResponse = _customerService.Patch(id, request);

            return(Ok(successResponse));
        }
示例#45
0
        public override async Task ExecuteAsync(PstClientPacket pstClientPacket, ClientSession clientSession)
        {
            var isCopy = pstClientPacket.Type == 2;
            var mail   = await _mailHttpClient.GetGiftAsync(pstClientPacket.Id, clientSession.Character.VisualId, isCopy).ConfigureAwait(false);

            switch (pstClientPacket.ActionType)
            {
            case 3:
                if (mail == null)
                {
                    return;
                }

                var patch = new JsonPatchDocument <MailDto>();
                patch.Replace(link => link.IsOpened, true);
                await _mailHttpClient.ViewGiftAsync(mail.MailDto.MailId, patch).ConfigureAwait(false);

                await clientSession.SendPacketAsync(mail.GeneratePostMessage(pstClientPacket.Type)).ConfigureAwait(false);

                break;

            case 2:
                if (mail == null)
                {
                    return;
                }

                await _mailHttpClient.DeleteGiftAsync(pstClientPacket.Id, clientSession.Character.VisualId, isCopy).ConfigureAwait(false);

                await clientSession.SendPacketAsync(
                    clientSession.Character.GenerateSay(
                        GameLanguage.Instance.GetMessageFromKey(LanguageKey.MAIL_DELETED,
                                                                clientSession.Account.Language),
                        SayColorType.Purple)).ConfigureAwait(false);

                break;

            case 1:
                if (string.IsNullOrEmpty(pstClientPacket.Text) || string.IsNullOrEmpty(pstClientPacket.Title))
                {
                    return;
                }

                var dest = await _characterDao.FirstOrDefaultAsync(s => s.Name == pstClientPacket.ReceiverName).ConfigureAwait(false);

                if (dest != null)
                {
                    await _mailHttpClient.SendMessageAsync(clientSession.Character, dest.CharacterId, pstClientPacket.Title,
                                                           pstClientPacket.Text).ConfigureAwait(false);

                    await clientSession.SendPacketAsync(clientSession.Character.GenerateSay(
                                                            GameLanguage.Instance.GetMessageFromKey(
                                                                LanguageKey.MAILED,
                                                                clientSession.Account.Language), SayColorType.Yellow)).ConfigureAwait(false);
                }
                else
                {
                    await clientSession.SendPacketAsync(
                        clientSession.Character.GenerateSay(
                            GameLanguage.Instance.GetMessageFromKey(LanguageKey.USER_NOT_FOUND,
                                                                    clientSession.Account.Language),
                            SayColorType.Yellow)).ConfigureAwait(false);
                }

                break;

            default:
                return;
            }
        }
 public new ActionResult Patch(int id, JsonPatchDocument <InsertScenarioDto> document)
 {
     return(base.Patch(id, document));
 }
示例#47
0
        private async Task <JsonPatchDocument> CreatePatchDocumentAsync(MigrationContext context, WorkItemUpdate update, CancellationToken cancellationToken)
        {
            var doc = new JsonPatchDocument();

            if (update.Fields == null)
            {
                update.Fields = new Dictionary <string, WorkItemFieldUpdate>(StringComparer.OrdinalIgnoreCase);
            }

            var fields = update.Fields;

            //Ensure that the ChangedBy/Changed Date fields are being set so the history is maintained
            fields.EnsureFieldSet(WorkItemFields.ChangedBy, update.RevisedBy.Name);
            fields.EnsureFieldSet(WorkItemFields.ChangedDate, update.RevisedDate);

            //Copy the fields
            foreach (var field in fields)
            {
                cancellationToken.ThrowIfCancellationRequested();

                context.FieldHandlers.TryGetValue(field.Key, out var handlers);
                if (handlers != null || Settings.IncludeAllFields)
                {
                    var newField = new WorkItemFieldValue()
                    {
                        Name = field.Key, Value = field.Value.NewValue
                    };

                    if (handlers != null)
                    {
                        foreach (var handler in handlers)
                        {
                            newField = await handler.HandleAsync(doc, newField, cancellationToken).ConfigureAwait(false);

                            if (newField == null)
                            {
                                break;
                            }
                        }
                        ;
                    }
                    ;

                    if (newField != null)
                    {
                        //The final check before we add the item is to ensure that the field actually exists in the target system
                        var allowedFields = await context.GetTargetFieldsAsync(cancellationToken).ConfigureAwait(false);

                        if (!allowedFields.Contains(newField.Name, StringComparer.OrdinalIgnoreCase))
                        {
                            Logger.Warning($"{newField.Name} was not found in target, skipping");
                        }
                        else
                        {
                            var name  = (newField.Name != field.Key) ? $"{newField.Name} (renamed from {field.Key})" : newField.Name;
                            var value = newField.Value?.ToString() ?? "";
                            if (value.Length > 75)
                            {
                                value = value.Left(75) + "...";
                            }

                            Logger.Debug($"{name} = {value}");

                            //Add or update it
                            if (field.Value.OldValue != null)
                            {
                                doc.UpdateField(newField.Name, newField.Value);
                            }
                            else
                            {
                                doc.AddField(newField.Name, newField.Value);
                            }
                        };
                    }
                    else
                    {
                        Logger.Debug($"{field.Key} is marked as ignore");
                    }
                }
                else
                {
                    Logger.Debug($"{field.Key} has no handlers, skipping");
                }
            }
            ;

            return(doc);
        }
示例#48
0
        public async Task <IActionResult> PartiallyUpdateBookAsync(Guid authorId, Guid bookId, JsonPatchDocument <BookForUpdateDto> patchDocument)
        {
            var book = await RepositoryWrapper.Book.GetBookAsync(authorId, bookId);

            if (book == null)
            {
                return(NotFound());
            }

            var entityHash = HashFactory.GetHash(book);

            if (Request.Headers.TryGetValue(HeaderNames.IfMatch, out var requestETag) &&
                requestETag != entityHash)
            {
                return(StatusCode(StatusCodes.Status412PreconditionFailed));
            }

            var bookUpdateDto = Mapper.Map <BookForUpdateDto>(book);

            patchDocument.ApplyTo(bookUpdateDto, ModelState);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Mapper.Map(bookUpdateDto, book, typeof(BookForUpdateDto), typeof(Book));

            RepositoryWrapper.Book.Update(book);
            if (!await RepositoryWrapper.Book.SaveAsync())
            {
                throw new Exception("更新资源Book失败");
            }

            var entityNewHash = HashFactory.GetHash(book);

            Response.Headers[HeaderNames.ETag] = entityNewHash;

            return(NoContent());
        }
示例#49
0
 public async Task <IActionResult> Patch(string id, [FromBody] JsonPatchDocument <ConfigurationValue> request)
 {
     return(await base.PatchEntity(id, request));
 }
示例#50
0
 public Input(string id, JsonPatchDocument <ImageAsset> patch)
 {
     Id    = !string.IsNullOrEmpty(id) ? id : throw new ArgumentNullException(nameof(id));
     Patch = patch ?? throw new ArgumentNullException(nameof(patch));
 }
示例#51
0
        public async Task <ActionResult <ManipulationResult <User> > > PatchUserAsync(int id,
                                                                                      [FromBody] JsonPatchDocument <User> userPatch)
        {
            _logger.Info("Startet updating a User");

            if (userPatch is null)
            {
                return(BadRequest("Patch body is empty"));
            }

            var userIdClaimed = HttpContext.User.Identity.GetUserIdClaim();

            if (userIdClaimed is null)
            {
                _logger.Info("No userId has been found in the claims");
                return(BadRequest("Incorrect JWT. No userId Claim found."));
            }

            // create empty user ..
            var patchedUser = new User();

            // .. and apply patch on it
            userPatch.ApplyTo(patchedUser);

            if (!TryValidateModel(patchedUser))
            {
                _logger.Info("Patch syntax invalid");
                return(BadRequest("Patch syntax invalid."));
            }

            var patchResult = await _userService.UpdateUserAsync(userIdClaimed.Value, id, patchedUser);

            if (patchResult is null)
            {
                _logger.Info("Tried to update non updateable attributes or userId is invalid.");
                return(BadRequest("Tried to update non updateable attributesor userId is invalid."));
            }

            _logger.Info("User updated with ErrorCode {0}", patchResult.ErrorCode);

            return(Ok(patchResult));
        }
示例#52
0
        public async Task <ActionResult> PartiallyUpdateAlbumForBand(Guid bandId, Guid albumId, [FromBody] JsonPatchDocument <AlbumForUpdatingDto> patchDocument)
        {
            if (!await _bandAlbumRepository.BandExists(bandId))
            {
                return(NotFound());
            }

            var albumFromRepo = await _bandAlbumRepository.GetAlbum(bandId, albumId);

            if (albumFromRepo == null)
            {
                var albumDto = new AlbumForUpdatingDto();
                patchDocument.ApplyTo(albumDto, ModelState); // Aplly to Dto so we can use the restriction set in Dto

                var albumToAdd = _mapper.Map <Album>(albumDto);

                albumToAdd.Id = albumId;
                _bandAlbumRepository.AddAlbum(bandId, albumToAdd);

                await _bandAlbumRepository.Save();

                var upsertingAlbumToReturn = _mapper.Map <AlbumDto>(albumToAdd);

                return(CreatedAtRoute(
                           "GetAlbumForBand",
                           new { bandId = bandId, albumId = upsertingAlbumToReturn.Id },
                           upsertingAlbumToReturn
                           ));
            }

            /*
             * The Strategy doesn't override the current from repo directly.
             * 1. Get the CurrentData
             * 2. Transform CurrentData to Dto
             * 3. Overriding the Dto (Since the Dto has updating restriction)
             * 4. Using the Dto to override the CurrentData in the DB
             * 5. Save the Changes
             */

            var albumToPatch = _mapper.Map <AlbumForUpdatingDto>(albumFromRepo); // Firstly, transform the one in DB to the Dto

            patchDocument.ApplyTo(albumToPatch, ModelState);                     // Then we can apply Changes to current Dto

            if (!TryValidateModel(albumToPatch))
            {
                return(ValidationProblem(ModelState));
            }


            _mapper.Map(albumToPatch, albumFromRepo); // Using the updatedDto to override the current from repo
            _bandAlbumRepository.UpdateAlbum(albumFromRepo);
            await _bandAlbumRepository.Save();

            //return NoContent();

            var albumToReturn = _mapper.Map <AlbumDto>(albumFromRepo);

            return(CreatedAtRoute(
                       "GetAlbumForBand",
                       new { bandId = bandId, albumId = albumToReturn.Id },
                       albumToReturn
                       ));
        }
示例#53
0
 public Task<IActionResult> Patch(int carId, [FromBody] JsonPatchDocument<SaveCar> patch) =>
     this.patchCarCommand.Value.ExecuteAsync(carId, patch);
示例#54
0
 public abstract Task <WorkItemFieldValue> HandleAsync(JsonPatchDocument document, WorkItemFieldValue field, CancellationToken cancellationToken);
        private WorkItem ReplayRevisions(List <RevisionItem> revisionsToMigrate, WorkItem sourceWorkItem, WorkItem targetWorkItem, Project destProject, WorkItemStoreContext sourceStore,
                                         int current,
                                         WorkItemStoreContext targetStore)
        {
            try
            {
                foreach (var revision in revisionsToMigrate)
                {
                    var currentRevisionWorkItem = sourceStore.GetRevision(sourceWorkItem, revision.Number);
                    TraceWriteLine(currentRevisionWorkItem, $" Processing Revision[{revision.Number}");
                    // Decide on WIT
                    string destType = currentRevisionWorkItem.Type.Name;
                    if (me.WorkItemTypeDefinitions.ContainsKey(destType))
                    {
                        destType =
                            me.WorkItemTypeDefinitions[destType].Map(currentRevisionWorkItem);
                    }
                    //If work item hasn't been created yet, create a shell
                    if (targetWorkItem == null)
                    {
                        targetWorkItem = CreateWorkItem_Shell(destProject, currentRevisionWorkItem, destType);
                    }
                    //If the work item already exists and its type has changed, update its type. Done this way because there doesn't appear to be a way to do this through the store.
                    else if (targetWorkItem.Type.Name != destType)
                    {
                        Debug.WriteLine($"Work Item type change! '{targetWorkItem.Title}': From {targetWorkItem.Type.Name} to {destType}");
                        var typePatch = new JsonPatchOperation()
                        {
                            Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Add,
                            Path      = "/fields/System.WorkItemType",
                            Value     = destType
                        };
                        var datePatch = new JsonPatchOperation()
                        {
                            Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Add,
                            Path      = "/fields/System.ChangedDate",
                            Value     = currentRevisionWorkItem.Revisions[revision.Index].Fields["System.ChangedDate"].Value
                        };

                        var patchDoc = new JsonPatchDocument();
                        patchDoc.Add(typePatch);
                        patchDoc.Add(datePatch);
                        _witClient.UpdateWorkItemAsync(patchDoc, targetWorkItem.Id, bypassRules: true).Wait();
                    }

                    PopulateWorkItem(currentRevisionWorkItem, targetWorkItem, destType);
                    me.ApplyFieldMappings(currentRevisionWorkItem, targetWorkItem);

                    targetWorkItem.Fields["System.ChangedBy"].Value =
                        currentRevisionWorkItem.Revisions[revision.Index].Fields["System.ChangedBy"].Value;

                    targetWorkItem.Fields["System.History"].Value =
                        currentRevisionWorkItem.Revisions[revision.Index].Fields["System.History"].Value;
                    //Debug.WriteLine("Discussion:" + currentRevisionWorkItem.Revisions[revision.Index].Fields["System.History"].Value);


                    var fails = targetWorkItem.Validate();

                    foreach (Field f in fails)
                    {
                        TraceWriteLine(currentRevisionWorkItem,
                                       $"{current} - Invalid: {currentRevisionWorkItem.Id}-{currentRevisionWorkItem.Type.Name}-{f.ReferenceName}-{sourceWorkItem.Title} Value: {f.Value}");
                    }

                    targetWorkItem.Save();
                    TraceWriteLine(currentRevisionWorkItem,
                                   $" Saved TargetWorkItem {targetWorkItem.Id}. Replayed revision {revision.Number} of {currentRevisionWorkItem.Revisions.Count}");
                }

                if (targetWorkItem != null)
                {
                    ProcessWorkItemAttachments(sourceWorkItem, targetWorkItem, false);
                    ProcessWorkItemLinks(sourceStore, targetStore, sourceWorkItem, targetWorkItem, false);
                    string reflectedUri = sourceStore.CreateReflectedWorkItemId(sourceWorkItem);
                    if (targetWorkItem.Fields.Contains(me.Target.Config.ReflectedWorkItemIDFieldName))
                    {
                        targetWorkItem.Fields[me.Target.Config.ReflectedWorkItemIDFieldName].Value = reflectedUri;
                    }
                    var history = new StringBuilder();
                    history.Append(
                        $"This work item was migrated from a different project or organization. You can find the old version at <a href=\"{reflectedUri}\">{reflectedUri}</a>.");
                    targetWorkItem.History = history.ToString();
                    SaveWorkItem(targetWorkItem);

                    attachmentOMatic.CleanUpAfterSave(targetWorkItem);
                    TraceWriteLine(sourceWorkItem, $"...Saved as {targetWorkItem.Id}");

                    if (_config.UpdateSourceReflectedId && sourceWorkItem.Fields.Contains(me.Source.Config.ReflectedWorkItemIDFieldName))
                    {
                        sourceWorkItem.Fields[me.Source.Config.ReflectedWorkItemIDFieldName].Value =
                            targetStore.CreateReflectedWorkItemId(targetWorkItem);
                        SaveWorkItem(sourceWorkItem);
                        TraceWriteLine(sourceWorkItem, $"...and Source Updated {sourceWorkItem.Id}");
                    }
                }
            }
            catch (Exception ex)
            {
                TraceWriteLine(sourceWorkItem, "...FAILED to Save");

                if (targetWorkItem != null)
                {
                    foreach (Field f in targetWorkItem.Fields)
                    {
                        TraceWriteLine(sourceWorkItem, $"{f.ReferenceName} ({f.Name}) | {f.Value}");
                    }
                }
                TraceWriteLine(sourceWorkItem, ex.ToString());
            }
            return(targetWorkItem);
        }
示例#56
0
        public virtual void PatchWeapon(JsonPatchDocument <Weapon> jsonPatch)
        {
            jsonPatch.ApplyTo(this);

            Validate(this, new WeaponValidator());
        }
示例#57
0
        public async Task DigitalTwins_Lifecycle()
        {
            DigitalTwinsClient client = GetClient();

            string roomTwinId = await GetUniqueTwinIdAsync(client, TestAssetDefaults.RoomTwinIdPrefix).ConfigureAwait(false);

            string floorModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.FloorModelIdPrefix).ConfigureAwait(false);

            string roomModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.RoomModelIdPrefix).ConfigureAwait(false);

            try
            {
                // arrange

                // create room model
                string roomModel = TestAssetsHelper.GetRoomModelPayload(roomModelId, floorModelId);
                await client.CreateModelsAsync(new List <string> {
                    roomModel
                }).ConfigureAwait(false);

                // act

                // create room twin
                BasicDigitalTwin roomTwin = TestAssetsHelper.GetRoomTwinPayload(roomModelId);
                await client.CreateDigitalTwinAsync <BasicDigitalTwin>(roomTwinId, roomTwin).ConfigureAwait(false);

                // get twin
                await client.GetDigitalTwinAsync <BasicDigitalTwin>(roomTwinId).ConfigureAwait(false);

                // update twin
                JsonPatchDocument updateTwinPatchDocument = new JsonPatchDocument();
                updateTwinPatchDocument.AppendAdd("/Humidity", 30);
                updateTwinPatchDocument.AppendReplace("/Temperature", 70);
                updateTwinPatchDocument.AppendRemove("/EmployeeId");

                var requestOptions = new UpdateDigitalTwinOptions
                {
                    IfMatch = "*"
                };

                await client.UpdateDigitalTwinAsync(roomTwinId, updateTwinPatchDocument, requestOptions).ConfigureAwait(false);

                // delete a twin
                await client.DeleteDigitalTwinAsync(roomTwinId).ConfigureAwait(false);

                // assert
                Func <Task> act = async() =>
                {
                    await client.GetDigitalTwinAsync <BasicDigitalTwin>(roomTwinId).ConfigureAwait(false);
                };

                act.Should().Throw <RequestFailedException>()
                .And.Status.Should().Be((int)HttpStatusCode.NotFound);
            }
            finally
            {
                // cleanup
                try
                {
                    if (!string.IsNullOrWhiteSpace(roomModelId))
                    {
                        await client.DeleteModelAsync(roomModelId).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    Assert.Fail($"Test clean up failed: {ex.Message}");
                }
            }
        }
示例#58
0
        public async Task <IActionResult> PatchUser(int id, [FromBody] JsonPatchDocument <User> patchDoc)
        {
            patchDoc.ApplyTo(await _userService.PatchUser(id), ModelState);

            return(Ok(await _userService.GetUserById(id)));
        }
示例#59
0
        public async Task <ActionResult> PartiallyUpdateRekommendation(Guid rekommendationId, JsonPatchDocument <RekommendationForUpdateDto> patchDocument)
        {
            var rekommendationFromRepo = await _repository.GetRekommendationAsync(rekommendationId);

            if (rekommendationFromRepo == null)
            {
                return(NotFound());
            }

            var rekommendationToPatch = rekommendationFromRepo.ToUpdateDto();

            patchDocument.ApplyTo(rekommendationToPatch, ModelState);

            if (!TryValidateModel(rekommendationToPatch))
            {
                return(ValidationProblem(ModelState));
            }

            //var oldGrade = rekommendationFromRepo.Grade;
            //var oldStatus = rekommendationFromRepo.Status;

            // Need to keep repoInstance for Entity Framework
            ApplyUpdateToEntity(rekommendationFromRepo, rekommendationToPatch);

            //bool isRekommenderToBeUpdated = false;

            //if ((rekommendationFromRepo.Grade != oldGrade && rekommendationFromRepo.Grade != -1) || (rekommendationFromRepo.Status != oldStatus && rekommendationFromRepo.Status != RekommendationStatus.EmailToBeVerified))
            //{
            //    isRekommenderToBeUpdated = true;
            //}

            // Action without any effect
            _repository.UpdateRekommendation(rekommendationFromRepo);

            //if (isRekommenderToBeUpdated)
            //{
            //    _repository.RecomputeXpAndRekoAvgFromRekommender(rekommendationFromRepo.RekommenderId);
            //}

            await _repository.SaveChangesAsync();

            return(NoContent());
        }
示例#60
0
        public async Task <IActionResult> PartiuallyUpdateHallByIdAsync(
            [FromRoute, SwaggerParameter(Description = "Id of hall to update", Required = true)] Guid hallId,
            [FromBody, SwaggerParameter(Description = "Jsonpatch operation document to update", Required = true)] JsonPatchDocument <HallToUpdateDto> patchDoc,
            [FromHeader(Name = "Accept"), SwaggerParameter(Description = "media type to request betwen json or json+hateoas")] string mediaType)
        {
            if (patchDoc == null)
            {
                return(BadRequest());
            }

            var hallFromDb = await _hallRepository.GetHallAsync(hallId);

            //  upserting if movie does not already exist
            if (hallFromDb == null)
            {
                var hallToCreate = new HallToUpdateDto();
                patchDoc.ApplyTo(hallToCreate, ModelState);

                if (!ModelState.IsValid)
                {
                    new ProccessingEntityObjectResultErrors(ModelState);
                }

                var hallToAddToDb = Mapper.Map <Hall>(hallToCreate);
                hallToAddToDb.Id = hallId;
                _hallRepository.AddHall(hallToAddToDb);

                if (!await _hallRepository.SaveChangesAsync())
                {
                    _logger.LogError($"Upserting hall: {hallId} failed on save");
                }

                var hallToReturn = Mapper.Map <HallDto>(hallToAddToDb);

                if (mediaType == "application/vnd.biob.json+hateoas")
                {
                    var links = CreateLinksForHall(hallToReturn.Id);

                    var linkedHall = hallToReturn.ShapeData(null) as IDictionary <string, object>;

                    linkedHall.Add("links", links);

                    return(CreatedAtRoute("GetHall", new { hallId = hallToReturn.Id }, linkedHall));
                }

                return(CreatedAtRoute("GetHall", new { hallId = hallToReturn.Id }, hallToReturn));
            }

            var hallToPatch = Mapper.Map <HallToUpdateDto>(hallFromDb);

            patchDoc.ApplyTo(hallToPatch, ModelState);

            if (!ModelState.IsValid)
            {
                new ProccessingEntityObjectResultErrors(ModelState);
            }

            Mapper.Map(hallToPatch, hallFromDb);
            _hallRepository.UpdateHall(hallFromDb);

            if (!await _hallRepository.SaveChangesAsync())
            {
                _logger.LogError($"Partially updating hall: {hallId} failed on save");
            }

            return(NoContent());
        }