Example #1
0
 private static void AddOperation(JsonMergePatchDocument jsonMergePatchDocument, string pathPrefix,
                                  JObject patchObject, JsonMergePatchOptions options)
 {
     foreach (var jProperty in patchObject)
     {
         var path = pathPrefix + jProperty.Key;
         if (jProperty.Value is JValue jValue)
         {
             if (options.EnableDelete && jValue.Value == null)
             {
                 jsonMergePatchDocument.AddOperation_Remove(path);
             }
             else
             {
                 jsonMergePatchDocument.AddOperation_Replace(path, jValue.Value);
             }
         }
         else if (jProperty.Value is JArray jArray)
         {
             jsonMergePatchDocument.AddOperation_Replace(path, jArray);
         }
         else if (jProperty.Value is JObject jObject)
         {
             jsonMergePatchDocument.AddOperation_Add(path);
             AddOperation(jsonMergePatchDocument, path + "/", jObject, options);
         }
     }
 }
Example #2
0
        public async Task <IActionResult> JsonMergePatch([FromRoute] string petName,
                                                         [FromBody] JsonMergePatchDocument <PetEntity> patch)
        {
            try
            {
                var pet = _manager.ReadOne(petName).Result;
                patch.ApplyTo(pet, ModelState);

                if (!ModelState.IsValid)
                {
                    return(_invalidResponseFactory.Response(StatusCodes.Status412PreconditionFailed, "JsonPatchDocument", "Argumentos no válidos"));
                }

                await _manager.Update(pet);

                return(Ok(pet));
            }
            catch (NotFoundException ex)
            {
                return(_invalidResponseFactory.Response(NotFound(ex.Message)));
            }
            catch (System.Exception e)
            {
                return(_invalidResponseFactory.Response(StatusCode(StatusCodes.Status409Conflict, e.Message)));
            }
        }
Example #3
0
        public void PatchDictionnaryAddKeyWithSlash()
        {
            var patchString = @"{ ""SubModels"": {""te/st"": {} } }";
            JsonMergePatchDocument <TestModelBase> patch = PatchBuilder.Build <TestModelBase>(patchString);
            TestModelBase patchedModel = patch.ApplyTo(GetTestModel());

            Assert.Equal("te/st", patchedModel.SubModels.First().Key);
        }
        public void Empty_PatchDocument_IsValid()
        {
            var patchDocument     = new JsonMergePatchDocument <ValidationClass>(EmptyPatchDocument.ToString());
            var validationContext = new ValidationContext(patchDocument);
            var validationErrors  = patchDocument.Validate(validationContext).ToList();

            Console.Write(JsonConvert.SerializeObject(validationErrors));
            Assert.IsTrue(validationErrors.All(p => p == null), "No Error Result");
        }
        public void Inherited_Classes_Allow_Additional_Properties()
        {
            var patchDocument     = new JsonMergePatchDocument <InheritedClass>(InheritedClassPatchDocumentWithAdditionalProperties.ToString());
            var validationContext = new ValidationContext(patchDocument);
            var validationErrors  = patchDocument.Validate(validationContext).ToList();

            Console.Write(JsonConvert.SerializeObject(validationErrors));
            Assert.IsTrue(validationErrors.All(p => p == null), "No Error Result");
        }
        public void Inherited_RequiredProperties_Are_Not_Enforced()
        {
            var patchDocument     = new JsonMergePatchDocument <InheritedClass>(InheritedClassPatchDocument.ToString());
            var validationContext = new ValidationContext(patchDocument);
            var validationErrors  = patchDocument.Validate(validationContext).ToList();

            Console.Write(JsonConvert.SerializeObject(validationErrors));
            Assert.IsTrue(validationErrors.All(p => p == null), "No Error Result");
        }
        public void Validate_Reports_IllegealStringEnum_Values()
        {
            var patchDocument     = new JsonMergePatchDocument <ValidationClass>(InValidStringEnumPatchDocument.ToString());
            var validationContext = new ValidationContext(patchDocument);
            var validationErrors  = patchDocument.Validate(validationContext).ToList();

            Console.Write(JsonConvert.SerializeObject(validationErrors));
            Assert.AreEqual(validationErrors.Count(p => p != null), 1, "One Error");
        }
        public T PatchWithModelValidation(int id, [FromBody] JsonMergePatchDocument <T> patch)
        {
            if (!ModelState.IsValid)
            {
                throw new ArgumentException("Model is invalid");
            }

            return(Patch(id, patch));
        }
        public void Validate_Returns_Error_If_MaximumStringLength_Is_Ignored()
        {
            var patchDocument     = new JsonMergePatchDocument <ValidationClass>(InvalidMaxLengthPatchDocument.ToString());
            var validationContext = new ValidationContext(patchDocument);
            var validationErrors  = patchDocument.Validate(validationContext).ToList();

            Console.Write(JsonConvert.SerializeObject(validationErrors));
            Assert.AreEqual(2, validationErrors.Count);
        }
        public void Validate_Accepts_StringEnum_Values()
        {
            var patchDocument     = new JsonMergePatchDocument <ValidationClass>(ValidStringEnumPatchDocument.ToString());
            var validationContext = new ValidationContext(patchDocument);
            var validationErrors  = patchDocument.Validate(validationContext).ToList();

            Console.Write(JsonConvert.SerializeObject(validationErrors));
            Assert.IsTrue(validationErrors.All(p => p == null), "No Error Result");
        }
        public void Required_Properties_In_Components_Are_Ignored()
        {
            var patchDocument     = new JsonMergePatchDocument <ValidationClass>(ComponentPatchDocument.ToString());
            var validationContext = new ValidationContext(patchDocument);
            var validationErrors  = patchDocument.Validate(validationContext).ToList();

            Console.Write(JsonConvert.SerializeObject(validationErrors));
            Assert.IsTrue(validationErrors.All(p => p == null), "No Error Result");
        }
        public T Patch(int id, [FromBody] JsonMergePatchDocument <T> patch)
        {
            var model = _repository[id];

            patch.ApplyTo(model);
            _repository[id] = model;
            model.Id        = id;
            return(model);
        }
        public async Task <IActionResult> PatchStudent(int id, [FromBody] JsonMergePatchDocument <StudentModel> patchDocument)
        {
            if (patchDocument == null)
            {
                return(BadRequest());
            }

            //send {"lastName": "ssss",  "firstMidName": "bbbbbb", } from post man
            //Todo: test with postman not wokring for
            //[ { "op": "add", "path": "/lastName", "value": "some name"} ]

            await Task.CompletedTask;

            var existingModel = await StudentService.GetAsync(id);

            patchDocument.ApplyTo(existingModel);
            var updatedStudent = await StudentService.UpdateAsync(existingModel);

            return(Ok(updatedStudent));

            #region patch code not in us

            //var existingModel = await this.CampusQueries.GetCampusById(uid);

            //if (existingModel == null)
            //{
            //    return this.NotFound();
            //}

            //patchDocument.ApplyTo(existingModel);
            //TryValidateModel(existingModel);

            //if (!ModelState.IsValid)
            //{
            //    return this.BadRequest(ModelState);
            //}

            //var entity = Map(existingModel);

            //    var model = await Commands.Update(entity);
            //    var selfurl = Url.Link(nameof(GetStudentById), new { uid = model.id });
            //    model.Links = new[] { Link.Self(selfurl) };
            //    return Ok(model);


            //return this.BadRequest(new MessageValuesModel() { Values = entity.Messages });
            //var existingModel = new StudentModel()
            //{
            //    ID = 1,
            //    FirstMidName = "some name",
            //    LastName = "last name 1"
            //};
            #endregion
        }
Example #14
0
        public virtual async Task <IActionResult> PatchAsync([FromRoute] long id, JsonMergePatchDocument <Person> patch)
        {
            if (!Valid(patch, out var error))
            {
                return(error);
            }

            var @object = await _repository.GetAsync(id);

            if (@object?.Data == null)
            {
                return(NotFound());
            }

            patch.ApplyTo(@object.Data);
            return(await SaveAsync(@object.Data));
        }
Example #15
0
        public int PartialUpdate([FromRoute] string id, [FromBody] JsonMergePatchDocument <Company> patch)
        {
            Guid docId = new Guid(id);

            var ops = new List <string>();

            patch.Operations.ForEach(op =>
            {
                ops.Add(op.path.TrimStart('/'));
            });

            var data = new Company();

            patch.ApplyTo(data);

            return(_companyDbService.PartialUpdate(docId, data, ops));
        }
Example #16
0
 private static void AddOperation(JsonMergePatchDocument jsonMergePatchDocument, string pathPrefix, JObject jObject)
 {
     foreach (var jProperty in jObject)
     {
         if (jProperty.Value is JValue)
         {
             jsonMergePatchDocument.AddOperation(OperationType.Replace, pathPrefix + jProperty.Key, ((JValue)jProperty.Value).Value);
         }
         else if (jProperty.Value is JArray)
         {
             jsonMergePatchDocument.AddOperation(OperationType.Replace, pathPrefix + jProperty.Key, ((JArray)jProperty.Value));
         }
         else if (jProperty.Value is JObject)
         {
             AddOperation(jsonMergePatchDocument, pathPrefix + jProperty.Key + "/", (jProperty.Value as JObject));
         }
     }
 }
Example #17
0
        public int PartialUpdate([FromRoute] string id, [FromBody] JsonMergePatchDocument <Target> patch)
        {
            Guid docId = new Guid(id);

            var ops = new List <string>();

            patch.Operations.ForEach(op =>
            {
                ops.Add(op.path.TrimStart('/'));
            });

            var data = new Target();

            patch.ApplyTo(data);

            var query = new TargetQuery();

            return(query.PartialUpdate(docId, data, ops));
        }
        public ActionResult <VerificationKey> Patch(int id, [FromBody] JsonMergePatchDocument <VerificationKeyPatch> patch)
        {
            if (patch is null)
            {
                return(BadRequest(ModelState));
            }

            var key = _context.VerificationKeys.Find(id);

            if (key is null)
            {
                return(NotFound());
            }

            patch.ApplyTo(key);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.SaveChanges();

            return(key);
        }
 public PatchTaskQueryBuilder(JsonMergePatchDocument <PatchTaskViewModel> patchDocument, int taskId)
 {
     _patchDocument = patchDocument;
     _taskId        = taskId;
 }