public IHttpActionResult Patch([FromODataUri] string key, Delta <CODE_PROVANDCITYEntity> patch) { CODE_PROVANDCITYService service = new CODE_PROVANDCITYService(); object id; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } else if (patch.GetChangedPropertyNames().Contains("ITEM_CODE") && patch.TryGetPropertyValue("ITEM_CODE", out id) && (string)id != key) { return(BadRequest("The key from the url must match the key of the entity in the body")); } try { var query = service.GetEntity(key); patch.Patch(query); service.UpdateEntity(query); return(Updated(query)); } catch (Exception) { return(NotFound()); } }
// PATCH tables/ExpenseItem/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task <ExpenseItem> PatchExpenseItem(string id, Delta <ExpenseItem> patch) { var userSid = this.GetCurrentUserSid(); var userAccounts = _context.AccountUsers .Where(accountUser => accountUser.UserId == userSid) .Select(accountUser => accountUser.AccountId); var query = _context.ExpenseItems.Where(expenseItem => userAccounts.Contains(expenseItem.AccountId) && expenseItem.Id == id); if (!query.Any()) { throw new HttpResponseException(HttpStatusCode.NotFound); } var changedProperties = patch.GetChangedPropertyNames().ToList(); var filteredDelta = new Delta <ExpenseItem>(); if (changedProperties.Contains(nameof(ExpenseItem.Amount), StringComparer.OrdinalIgnoreCase)) { filteredDelta.TrySetPropertyValue(nameof(ExpenseItem.Amount), patch.GetEntity().Amount); } if (changedProperties.Contains(nameof(ExpenseItem.Date), StringComparer.OrdinalIgnoreCase)) { filteredDelta.TrySetPropertyValue(nameof(ExpenseItem.Date), patch.GetEntity().Date); } if (changedProperties.Contains(nameof(ExpenseItem.Description), StringComparer.OrdinalIgnoreCase)) { filteredDelta.TrySetPropertyValue(nameof(ExpenseItem.Description), patch.GetEntity().Description); } return(UpdateAsync(id, filteredDelta)); }
public virtual async Task <IHttpActionResult> PatchAsync(string id, Delta <TUpdateModel> changes) { TModel original = await GetModelAsync(id, false); if (original == null) { return(NotFound()); } // if there are no changes in the delta, then ignore the request if (changes == null || !changes.GetChangedPropertyNames().Any()) { return(await OkModelAsync(original)); } var permission = await CanUpdateAsync(original, changes); if (!permission.Allowed) { return(Permission(permission)); } try { await UpdateModelAsync(original, changes); await AfterPatchAsync(original); } catch (ValidationException ex) { return(BadRequest(ex.Errors.ToErrorMessage())); } return(await OkModelAsync(original)); }
public virtual IHttpActionResult Patch(string id, Delta <TUpdateModel> changes) { // if there are no changes in the delta, then ignore the request if (changes == null || !changes.GetChangedPropertyNames().Any()) { return(Ok()); } TModel original = GetModel(id, false); if (original == null) { return(NotFound()); } var permission = CanUpdate(original, changes); if (!permission.Allowed) { return(Permission(permission)); } try { UpdateModel(original, changes); } catch (ValidationException ex) { return(BadRequest(ex.Errors.ToErrorMessage())); } return(Ok()); }
public void Read_PatchMode() { // Arrange string content = Resources.SupplierPatch; var readContext = new ODataDeserializerContext { Path = new ODataPath(new EntitySetSegment(_edmModel.EntityContainer.FindEntitySet("Suppliers"))), Model = _edmModel, ResourceType = typeof(Delta <Supplier>) }; ODataResourceDeserializer deserializer = new ODataResourceDeserializer(_deserializerProvider); // Act Delta <Supplier> supplier = deserializer.Read(GetODataMessageReader(GetODataMessage(content), _edmModel), typeof(Delta <Supplier>), readContext) as Delta <Supplier>; // Assert Assert.NotNull(supplier); Assert.Equal(supplier.GetChangedPropertyNames(), new string[] { "ID", "Name", "Address" }); Assert.Equal((supplier as dynamic).Name, "Supplier Name"); Assert.Equal("Supplier City", (supplier as dynamic).Address.City); Assert.Equal("123456", (supplier as dynamic).Address.ZipCode); }
public override IHttpActionResult Patch(int key, Delta <ItSystem> delta) { var itSystem = Repository.GetByKey(key); if (itSystem == null) { return(NotFound()); } var changedPropertyNames = delta.GetChangedPropertyNames().ToHashSet(); if (AttemptToChangeUuid(delta, itSystem, changedPropertyNames)) { return(BadRequest("Cannot change Uuid")); } var disabledBefore = itSystem.Disabled; var result = base.Patch(key, delta); if (disabledBefore != itSystem.Disabled) { DomainEvents.Raise(new EnabledStatusChanged <ItSystem>(itSystem, disabledBefore, itSystem.Disabled)); } return(result); }
public override IHttpActionResult Patch(int key, Delta <Advice> delta) { try { var existingAdvice = Repository.GetByKey(key); var deltaAdvice = delta.GetInstance(); if (existingAdvice == null) { return(NotFound()); } if (existingAdvice.Type != deltaAdvice.Type) { return(BadRequest("Cannot change advice type")); } if (!existingAdvice.IsActive) { throw new ArgumentException( "Cannot update inactive advice "); } if (existingAdvice.AdviceType == AdviceType.Immediate) { throw new ArgumentException("Editing is not allowed for immediate advice"); } if (existingAdvice.AdviceType == AdviceType.Repeat) { var changedPropertyNames = delta.GetChangedPropertyNames().ToList(); if (changedPropertyNames.All(IsRecurringEditableProperty)) { throw new ArgumentException("For recurring advices editing is only allowed for name, subject and stop date"); } if (changedPropertyNames.Contains("StopDate") && deltaAdvice.StopDate != null) { if (deltaAdvice.StopDate.Value.Date < deltaAdvice.AlarmDate.GetValueOrDefault().Date || deltaAdvice.StopDate.Value.Date < _operationClock.Now.Date) { throw new ArgumentException("For recurring advices only future stop dates after the set alarm date is allowed"); } } } var response = base.Patch(key, delta); if (response is UpdatedODataResult <Advice> ) { var updatedAdvice = Repository.GetByKey(key); //Re-load _adviceService.UpdateSchedule(updatedAdvice); } return(response); } catch (Exception e) { Logger.ErrorException("Failed to update advice", e); return(StatusCode(HttpStatusCode.InternalServerError)); } }
public virtual async Task <IHttpActionResult> Patch([FromODataUri] TKey key, Delta <TEntity> patch, ODataQueryOptions <TEntity> options) { Validate(patch.GetInstance()); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!String.IsNullOrWhiteSpace(this.AllowedSelectProperties)) { var updateableProperties = AllowedSelectProperties.Split(',').Select(x => x.Trim()); /***************************************************************** * Example that prevents patch when invalid fields are presented * * Comment this block to passively allow the operation and skip * * over the invalid fields * * ***************************************************************/ if (patch.GetChangedPropertyNames().Any(x => updateableProperties.Contains(x, StringComparer.OrdinalIgnoreCase))) { return(BadRequest("Can only Patch the following fields: " + this.AllowedSelectProperties)); } /***************************************************************** * Passive example, re-create the delta and skip invalid fields * * ***************************************************************/ var delta = new Delta <TEntity>(); foreach (var field in updateableProperties) { if (delta.TryGetPropertyValue(field, out object value)) { delta.TrySetPropertyValue(field, value); } } patch = delta; } var itemQuery = GetEntitySet().Where(FindByKey(key)); var item = itemQuery.FirstOrDefault(); if (item == null) { return(NotFound()); } patch.Patch(item); try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ItemExists(key)) { return(NotFound()); } else { throw; } } return(Updated(item)); }
public IHttpActionResult Patch([FromODataUri] int key, Delta <Punch> patch) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var currentUser = CurrentUser(); // Ensure that user is authorized. if (!currentUser.CanModifyPunches) { return(StatusCode(HttpStatusCode.Forbidden)); } var punch = db.Punches .Include("User") .Where(p => p.User.OrganizationId == currentUser.OrganizationId) .Where(p => p.Id == key) .FirstOrDefault(); // Record the object before any changes are made. var before = JsonConvert.SerializeObject(punch); if (punch == null) { return(NotFound()); } // Cannot modify locked punches. if (punch.CommitId.HasValue) { return(BadRequest()); } // Do not allow modifying some properties. if (patch.GetChangedPropertyNames().Contains("OrganizationId")) { return(BadRequest("Cannont modify OrganizationId")); } // Peform the update patch.Patch(punch); // Ensure InAt is at bottom of hour and OutAt is at top of the hour punch.InAt = new DateTime(punch.InAt.Year, punch.InAt.Month, punch.InAt.Day, punch.InAt.Hour, punch.InAt.Minute, 0, 0); if (punch.OutAt.HasValue) { punch.OutAt = new DateTime(punch.OutAt.Value.Year, punch.OutAt.Value.Month, punch.OutAt.Value.Day, punch.OutAt.Value.Hour, punch.OutAt.Value.Minute, 0, 0); } db.SaveChanges(); // Record the activity. AuditPunch(punch.Id, before, JsonConvert.SerializeObject(punch), currentUser, "UPDATE"); return(Updated(punch)); }
public void ReadFromStreamAsync_ForComplexType_WithNestedComplexType() { // Arrange const string content = "{\"value\":{" + "\"City\":\"UpdatedCity\"," + "\"Location\": {" + "\"Latitude\": 30.6," + "\"Longitude\": 101.313" + "}," + "\"SubLocation\": {" + // dynamic property "\"@odata.type\":\"#System.Web.OData.Formatter.Deserialization.Location\"," + "\"Latitude\": 15.5," + "\"Longitude\": 130.88" + "}" + "}}"; ODataComplexTypeDeserializer deserializer = new ODataComplexTypeDeserializer(new DefaultODataDeserializerProvider()); ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.ComplexType <Region>(); IEdmModel model = builder.GetEdmModel(); ODataDeserializerContext readContext = new ODataDeserializerContext { Model = model, ResourceType = typeof(Delta <Region>) }; // Act object value = deserializer.Read(GetODataMessageReader(GetODataMessage(content), model), typeof(Delta <Region>), readContext); // Assert Delta <Region> region = Assert.IsType <Delta <Region> >(value); Assert.NotNull(region); Assert.Equal(new[] { "City", "Location" }, region.GetChangedPropertyNames()); Assert.Empty(region.GetUnchangedPropertyNames()); object propertyValue; Assert.True(region.TryGetPropertyValue("City", out propertyValue)); string cityValue = Assert.IsType <string>(propertyValue); Assert.Equal("UpdatedCity", cityValue); Assert.True(region.TryGetPropertyValue("Location", out propertyValue)); Location locationValue = Assert.IsType <Location>(propertyValue); Assert.Equal(30.6, locationValue.Latitude); Assert.Equal(101.313, locationValue.Longitude); // dynamic property Assert.True(region.TryGetPropertyValue("SubLocation", out propertyValue)); locationValue = Assert.IsType <Location>(propertyValue); Assert.Equal(15.5, locationValue.Latitude); Assert.Equal(130.88, locationValue.Longitude); }
// PATCH: odata/Tasks(5) public IActionResult Patch([FromODataUri] int key, Delta <Brizbee.Core.Models.Task> patch) { var currentUser = CurrentUser(); var task = _context.Tasks .Include(t => t.Job.Customer) .Where(t => t.Id == key) .FirstOrDefault(); // Ensure that object was found. if (task == null) { return(NotFound()); } // Ensure that user is authorized. if (!currentUser.CanModifyTasks || task.Job.Customer.OrganizationId != currentUser.OrganizationId) { return(Forbid()); } // Do not allow modifying some properties. if (patch.GetChangedPropertyNames().Contains("JobId") || patch.GetChangedPropertyNames().Contains("CreatedAt") || patch.GetChangedPropertyNames().Contains("Id")) { return(BadRequest("Cannot modify the JobId, CreatedAt, or Id.")); } // Peform the update. patch.Patch(task); // Validate the model. ModelState.ClearValidationState(nameof(task)); if (!TryValidateModel(task, nameof(task))) { return(BadRequest()); } _context.SaveChanges(); return(NoContent()); }
// PATCH: odata/Jobs(5) public IActionResult Patch([FromODataUri] int key, Delta <Job> patch) { var currentUser = CurrentUser(); var job = _context.Jobs .Include(j => j.Customer) .Where(j => j.Customer.OrganizationId == currentUser.OrganizationId) .Where(j => j.Id == key) .FirstOrDefault(); // Ensure that object was found. if (job == null) { return(NotFound()); } // Ensure that user is authorized. if (!currentUser.CanModifyProjects || currentUser.OrganizationId != job.Customer.OrganizationId) { return(Forbid()); } // Do not allow modifying some properties. if (patch.GetChangedPropertyNames().Contains("CustomerId") || patch.GetChangedPropertyNames().Contains("Id") || patch.GetChangedPropertyNames().Contains("CreatedAt")) { return(BadRequest("Not authorized to modify the CustomerId, CreatedAt, or Id.")); } // Peform the update patch.Patch(job); // Validate the model. ModelState.ClearValidationState(nameof(job)); if (!TryValidateModel(job, nameof(job))) { return(BadRequest()); } _context.SaveChanges(); return(NoContent()); }
/// <summary> /// Get this list of non-editable changes in a <see cref="Delta{T}"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="delta"></param> /// <returns></returns> public static IList <string> NonEditableChanges <T>(this Delta <T> delta) where T : class { var nec = new List <string>(); var excluded = typeof(T).NonEditableProperties(); nec.AddRange(delta.GetChangedPropertyNames().Where(x => excluded.Contains(x))); return(nec); }
public IActionResult PatchToQuery(int key, Delta <HuntingQueryResults> delta) { var changedPropertyNames = delta.GetChangedPropertyNames(); HuntingQueryResults original = new HuntingQueryResults(); delta.Patch(original); return(Ok(key)); }
// PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959 public async Task <UserProfileDTO> PatchUserProfile(string id, Delta <UserProfileDTO> patch) { UserProfile currentUserProfile = this.context.UserProfiles.Include("InterestedIn") .First(j => (j.Id == id)); UserProfileDTO updatedUserProfileEntity = patch.GetEntity(); ICollection <TechnologyDTO> updatedTechnologies; bool reqeustContainsRelatedEntities = patch.GetChangedPropertyNames().Contains("InterestedIn"); if (reqeustContainsRelatedEntities) { //If request contains Items get the updated list from the patch Mapper.Map <UserProfileDTO, UserProfile>(updatedUserProfileEntity, currentUserProfile); updatedTechnologies = updatedUserProfileEntity.InterestedIn; } else { //If request doest not have Items, then retain the original association UserProfileDTO userProfileDTOUpdated = Mapper.Map <UserProfile, UserProfileDTO> (currentUserProfile); patch.Patch(userProfileDTOUpdated); Mapper.Map <UserProfileDTO, UserProfile>(userProfileDTOUpdated, currentUserProfile); updatedTechnologies = userProfileDTOUpdated.InterestedIn; } if (updatedTechnologies != null) { //Update related Items currentUserProfile.InterestedIn = new List <Technology>(); foreach (var currentTechnologyDTO in updatedTechnologies) { //Look up existing entry in database Technology existingItem = this.context.Technologies .FirstOrDefault(j => (j.Id.ToString() == currentTechnologyDTO.Id.ToString())); if (existingItem != null) { //Convert client type to database type // Mapper.Map<TechnologyDTO, Technology>(currentTechnologyDTO, // existingItem); currentUserProfile.InterestedIn.Add(existingItem); } } } await this.context.SaveChangesAsync(); //Convert to client type before returning the result var result = Mapper.Map <UserProfile, UserProfileDTO>(currentUserProfile); return(result); }
public void CanChangeDerivedClassProperties() { // Arrange dynamic delta = new Delta <Base>(typeof(Derived)); // Act delta.DerivedInt = 10; // Assert Assert.Equal(delta.GetChangedPropertyNames(), new[] { "DerivedInt" }); }
// PUT: odata/LocationCollections(5) public IHttpActionResult Put([FromODataUri] int key, Delta <LocationCollection> patch) { string LogMsg = this.ControllerContext.RouteData.Values["controller"].ToString() + "Controller." + this.ControllerContext.RouteData.Values["action"].ToString() + " :: "; LocationCollection locationcollection = null; try { Validate(patch.GetChangedPropertyNames()); if (!ModelState.IsValid) { NLogWriter.LogMessage(LogType.Error, LogMsg + "Invalid ModelState"); throw new Exception("Invalid modelstate"); } locationcollection = data.LocationCollectionRepository.GetByID(key); if (locationcollection == null) { NLogWriter.LogMessage(LogType.Error, LogMsg + "Unable to find Locationcollection by Key = '" + Convert.ToString(key) + "'"); throw new Exception("Unable to find locationcollection by key"); } patch.Put(locationcollection); try { data.Save(); } catch (DbUpdateConcurrencyException ex) { if (!LocationCollectionExists(key)) { NLogWriter.LogMessage(LogType.Error, LogMsg + "DbUpdateConcurrencyException putting locationcollection by ID '" + Convert.ToString(key) + "' - Not Found :: " + ex.ToString()); throw new Exception("DbUpdateConcurrencyException putting locationcollection by ID = '" + Convert.ToString(key) + "' - Not Found :: " + ex.ToString()); } else { throw; } } } catch (Exception ex) { NLogWriter.LogMessage(LogType.Error, LogMsg + "Exception updating locationcollection :: " + ex.ToString()); HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("Exception updating locationcollection :: " + ex.ToString()), ReasonPhrase = "Unable to udpate locationcollection" }; throw new HttpResponseException(resp); } return(Updated(locationcollection)); }
// PATCH tables/Domain/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task <Domain> PatchDomain(string id, Delta <DomainRequest> patch) { try { // patch Mappers does not work for Patch.Itws a limitation. ValidationUtilities.ValidateEditDomainRequest(patch.GetEntity(), patch.GetChangedPropertyNames().ToList()); string currentUserEmail = HttpUtilities.GetUserNameFromToken(this.Request); Delta <Domain> deltaDest = new Delta <Domain>(); //Domain dbObject = context.Domains.FirstOrDefault(a => a.Id == id); //Mapper.Initialize(cfg => cfg.CreateMap<DomainRequest, Domain>() // .ForMember(i => i.ModifiedBy, j => j.UseValue(currentUserEmail)) // .ForMember(i => i.UpdatedAt, j => j.UseValue(DateTimeOffset.UtcNow)) //); //var domainMap = Mapper.Map<DomainRequest, Domain>(patch.GetEntity(), dbObject); //deltaDest.Put(domainMap); //patch. foreach (var item in patch.GetChangedPropertyNames()) { object result; patch.TryGetPropertyValue(item, out result); bool bResult; if (bool.TryParse(result.ToString(), out bResult)) { deltaDest.TrySetPropertyValue(item, bResult); } else { deltaDest.TrySetPropertyValue(item, result); } } deltaDest.TrySetPropertyValue("ModifiedBy", currentUserEmail); deltaDest.TrySetPropertyValue("UpdatedAt", DateTimeOffset.UtcNow); return(UpdateAsync(id, deltaDest)); } catch (HttpResponseException ex) { LGSELogger.Error(ex); throw ex; } }
// PATCH tables/SummaryItem/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task <SummaryItem> PatchSummaryItem(string id, Delta <SummaryItem> patch) { SummaryItem oldSummaryItem = ValidateKey(id); // Only do the following if the summary value is being updated if (patch.GetChangedPropertyNames().Contains("Summary")) { string newSummaryCipher = patch.GetEntity().AddSummary(oldSummaryItem); patch.TrySetPropertyValue("Summary", newSummaryCipher); } return(UpdateAsync(id, patch)); }
public async Task <IHttpActionResult> Patch([FromODataUri] int elementFieldId, Delta <UserElementField> patch) { var userElementField = await MainUnitOfWork.AllLive.SingleOrDefaultAsync(item => item.ElementFieldId == elementFieldId); if (userElementField == null) { return(NotFound()); } var patchEntity = patch.GetEntity(); if (patchEntity.RowVersion == null) { throw new InvalidOperationException("RowVersion property of the entity cannot be null"); } if (!userElementField.RowVersion.SequenceEqual(patchEntity.RowVersion)) { return(Conflict()); } patch.Patch(userElementField); try { await MainUnitOfWork.UpdateAsync(userElementField); } catch (DbUpdateException) { if (patch.GetChangedPropertyNames().Any(item => item == "ElementFieldId")) { object elementFieldIdObject = null; patch.TryGetPropertyValue("ElementFieldId", out elementFieldIdObject); if (elementFieldIdObject != null && await MainUnitOfWork.All.AnyAsync(item => item.ElementFieldId == (int)elementFieldIdObject)) { return(new UniqueKeyConflictResult(Request, "ElementFieldId", elementFieldIdObject.ToString())); } else { throw; } } else { throw; } } return(Ok(userElementField)); }
public virtual async Task <IHttpActionResult> Patch([FromODataUri] string providerKey, Delta <UserLogin> patch) { var userLogin = await MainUnitOfWork.AllLive.SingleOrDefaultAsync(item => item.ProviderKey == providerKey); if (userLogin == null) { return(NotFound()); } var patchEntity = patch.GetEntity(); if (patchEntity.RowVersion == null) { throw new InvalidOperationException("RowVersion property of the entity cannot be null"); } if (!userLogin.RowVersion.SequenceEqual(patchEntity.RowVersion)) { return(Conflict()); } patch.Patch(userLogin); try { await MainUnitOfWork.UpdateAsync(userLogin); } catch (DbUpdateException) { if (patch.GetChangedPropertyNames().Any(item => item == "ProviderKey")) { object providerKeyObject = null; patch.TryGetPropertyValue("ProviderKey", out providerKeyObject); if (providerKeyObject != null && await MainUnitOfWork.All.AnyAsync(item => item.ProviderKey == (string)providerKeyObject)) { return(new UniqueKeyConflictResult(Request, "ProviderKey", providerKeyObject.ToString())); } else { throw; } } else { throw; } } return(Ok(userLogin)); }
public async Task <Result <TKey> > PatchAsync <TModel, TEntity, TKey>(Delta <TModel> delta, CancellationToken cancellationToken = default) where TModel : class, IObject <TKey> where TEntity : class, IObject <TKey> { var idName = nameof(IObject <TKey> .Id); if (delta.GetChangedPropertyNames().Contains(idName)) { if (delta.TryGetPropertyValue(idName, out var value)) { if (value is TKey id) { var entity = await this.repository.FindOneAsync <TEntity, TKey>(id, cancellationToken); if (entity != null) { var model = this.Mapper.Map <TEntity, TModel>(entity); delta.Patch(model); entity = this.Mapper.Map(model, entity); await this.repository.CommitAsync(cancellationToken); return(Result <TKey> .Success(id)); } else { var error = $"The entity of type {typeof(TEntity).Name} with key {id} does not exits and can not be patched"; this.Logger.LogDebug(error); return(Result <TKey> .Fail(error)); } } else { var error = $"The type of {value.GetType()} does not match the key type {typeof(TKey).Name} fot the entity type {typeof(TEntity).Name} and can not be patched"; this.Logger.LogDebug(error); return(Result <TKey> .Fail(error)); } } else { var error = $"The delta of entity of type {typeof(TEntity).Name} does not have a key ({idName}) and can not be patched"; this.Logger.LogDebug(error); return(Result <TKey> .Fail(error)); } } else { var error = $"The delta of entity of type {typeof(TEntity).Name} does not have a key property provided ({idName}) and can not be patched"; this.Logger.LogDebug(error); return(Result <TKey> .Fail(error)); } }
public virtual async Task <IHttpActionResult> Patch([FromODataUri] int key, Delta <ResourcePool> patch) { var resourcePool = await MainUnitOfWork.AllLive.SingleOrDefaultAsync(item => item.Id == key); if (resourcePool == null) { return(NotFound()); } var patchEntity = patch.GetEntity(); if (patchEntity.RowVersion == null) { throw new InvalidOperationException("RowVersion property of the entity cannot be null"); } if (!resourcePool.RowVersion.SequenceEqual(patchEntity.RowVersion)) { return(Conflict()); } patch.Patch(resourcePool); try { await MainUnitOfWork.UpdateAsync(resourcePool); } catch (DbUpdateException) { if (patch.GetChangedPropertyNames().Any(item => item == "Id")) { object keyObject = null; patch.TryGetPropertyValue("Id", out keyObject); if (keyObject != null && await MainUnitOfWork.All.AnyAsync(item => item.Id == (int)keyObject)) { return(new UniqueKeyConflictResult(Request, "Id", keyObject.ToString())); } else { throw; } } else { throw; } } return(Ok(resourcePool)); }
protected virtual async Task <PermissionResult> CanUpdateAsync(TModel original, Delta <TUpdateModel> changes) { if (original is IOwnedByOrganization orgModel && !CanAccessOrganization(orgModel.OrganizationId)) { return(PermissionResult.DenyWithMessage("Invalid organization id specified.")); } if (changes.GetChangedPropertyNames().Contains("OrganizationId")) { return(PermissionResult.DenyWithMessage("OrganizationId cannot be modified.")); } return(PermissionResult.Allow); }
public IHttpActionResult PatchToLocation(int key, Delta <Address> patch) { Assert.Equal(new[] { "Street", "City" }, patch.GetChangedPropertyNames()); // Verify the origin address Address address = new Address(); patch.Patch(address); Assert.Equal("UpdatedStreet", address.Street); Assert.Equal("UpdatedCity", address.City); return(Ok()); }
protected override Employee PatchEntity(int key, Delta <Employee> patch) { var employeeToPatch = GetEntityByKey(key); patch.Patch(employeeToPatch); db.Entry(employeeToPatch).State = EntityState.Modified; db.SaveChanges(); var changedProperty = patch.GetChangedPropertyNames().ToList()[0]; object changedPropertyValue; patch.TryGetPropertyValue(changedProperty, out changedPropertyValue); Hub.Clients.All.updateEmployee(employeeToPatch.Id, changedProperty, changedPropertyValue); return(employeeToPatch); }
/// <summary> /// Exclude changes from a <see cref="Delta{T}"/> based on a list of property names /// </summary> /// <typeparam name="T"></typeparam> /// <param name="delta"></param> /// <param name="excluded"></param> /// <returns></returns> public static Delta <T> Exclude <T>(this Delta <T> delta, IList <string> excluded) where T : class { var changed = new Delta <T>(); foreach (var prop in delta.GetChangedPropertyNames().Where(x => !excluded.Contains(x))) { object value; if (delta.TryGetPropertyValue(prop, out value)) { changed.TrySetPropertyValue(prop, value); } } return(changed); }
protected virtual PermissionResult CanUpdate(TModel original, Delta <TUpdateModel> changes) { var orgModel = original as IOwnedByOrganization; if (orgModel != null && !IsInOrganization(orgModel.OrganizationId)) { return(PermissionResult.DenyWithMessage("Invalid organization id specified.")); } if (changes.GetChangedPropertyNames().Contains("OrganizationId")) { return(PermissionResult.DenyWithMessage("OrganizationId cannot be modified.")); } return(PermissionResult.Allow); }
protected override Product PatchEntity(int key, Delta <Product> patch) { Delta <V2VM.Product> v2Patch = new Delta <V2VM.Product>(); foreach (string name in patch.GetChangedPropertyNames()) { object value; if (patch.TryGetPropertyValue(name, out value)) { v2Patch.TrySetPropertyValue(name, value); } } var v2Product = _controller.PatchEntityImpl((long)key, v2Patch); return(Mapper.Map <Product>(v2Product)); }
public void Read_PatchMode() { IEdmEntityType supplierEntityType = EdmTestHelpers.GetModel().FindType("ODataDemo.Supplier") as IEdmEntityType; _readContext.IsPatchMode = true; ODataEntityDeserializer deserializer = new ODataEntityDeserializer(_supplierEdmType, _deserializerProvider); Delta <Supplier> supplier = deserializer.Read(GetODataMessageReader(GetODataMessage(BaselineResource.SuppliersPatchData), _edmModel), _readContext) as Delta <Supplier>; Assert.NotNull(supplier); Assert.Equal(supplier.GetChangedPropertyNames(), new string[] { "Name", "Address" }); Assert.Equal((supplier as dynamic).Name, "Supplier Name"); Assert.Equal("Supplier City", (supplier as dynamic).Address.City); Assert.Equal("123456", (supplier as dynamic).Address.ZipCode); }