コード例 #1
0
        public async Task <IHttpActionResult> Put([FromODataUri] int key, Delta <Customer> patch)
        {
            Validate(patch.GetInstance());

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

            var customer = await _db.Customers.FindAsync(key);

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

            patch.Put(customer);

            try {
                await _db.SaveChangesAsync();
            } catch (DbUpdateConcurrencyException) {
                if (!CustomerExists(key))
                {
                    return(NotFound());
                }
                throw;
            }

            return(Updated(customer));
        }
コード例 #2
0
        public void CanGetChangedNestedPropertyNames()
        {
            dynamic deltaCustomer  = new Delta <CustomerEntity>();
            IDelta  ideltaCustomer = deltaCustomer as IDelta;

            AddressEntity Address = new AddressEntity();

            Address.ID            = 42;
            Address.StreetAddress = "23213 NE 15th Ct";
            Address.City          = "Sammamish";
            Address.State         = "WA";
            Address.ZipCode       = 98074;

            // modify in the way we expect the formatter too.
            ideltaCustomer.TrySetPropertyValue("Address", Address);
            Assert.Single(ideltaCustomer.GetChangedPropertyNames());
            Assert.Equal("Address", ideltaCustomer.GetChangedPropertyNames().Single());
            Assert.Equal(3, ideltaCustomer.GetUnchangedPropertyNames().Count());

            // read the property back
            Assert.True(ideltaCustomer.TryGetPropertyValue("Address", out object address));
            Assert.Equal(Address, address);

            // read the instance
            CustomerEntity instance = deltaCustomer.GetInstance();

            Assert.Equal(Address, instance.Address);
        }
コード例 #3
0
        // PUT: odata/People(5)
        public IActionResult Put([FromODataUri] int key, Delta <Person> patch)
        {
            if (!TryValidateModel(patch.GetInstance()))
            {
                return(BadRequest(ModelState));
            }

            var entity = db.People.Find(key);

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

            patch.Put(entity);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!Exists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(entity));
        }
コード例 #4
0
    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));
    }
コード例 #5
0
        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));
            }
        }
コード例 #6
0
        public override Task <TestCustomerDto> PartialUpdate(Guid key, Delta <TestCustomerDto> modifiedDtoDelta, CancellationToken cancellationToken)
        {
            TestCustomerDto dto = modifiedDtoDelta.GetInstance();

            dto.Name += "#";

            return(base.PartialUpdate(key, modifiedDtoDelta, cancellationToken));
        }
コード例 #7
0
        public virtual async Task <SingleResult <TestComplexDto> > PartialUpdate(int key, Delta <TestComplexDto> modelDelta,
                                                                                 CancellationToken cancellationToken)
        {
            TestComplexDto model = modelDelta.GetInstance();

            model.ComplexObj.Name += "?";

            return(SingleResult(model));
        }
コード例 #8
0
        public virtual async Task <TestComplexDto> PartialUpdate([FromODataUri] int key, Delta <TestComplexDto> modelDelta,
                                                                 CancellationToken cancellationToken)
        {
            TestComplexDto model = modelDelta.GetInstance();

            model.ComplexObj.Name += "?";

            return(model);
        }
コード例 #9
0
        public virtual async Task <SingleResult <ChildEntity> > PartialUpdate(long key, Delta <ChildEntity> modelDelta, CancellationToken cancellationToken)
        {
            var model = modelDelta.GetInstance();

            model.Name += "?";

            model = await TestRepository.UpdateAsync(model, cancellationToken);

            return(SingleResult(model));
        }
コード例 #10
0
        public IActionResult Patch([FromODataUri] int key, [FromBody] Delta<User> request)
        {
            UpdateByIdResponse response =
                new UserObjectService().UpdateById(new UpdateByIdRequest()
                {
                    Id = key,
                    User = request.GetInstance()
                }); 

            return Ok(response);
        }
コード例 #11
0
        public IActionResult Patch([FromODataUri] int key, [FromBody] Delta <Ac4yPersistentChild> request)
        {
            UpdateByIdResponse response =
                new Ac4yPersistentChildEFService().UpdateById(new UpdateByIdRequest()
            {
                Id = key,
                Ac4yPersistentChild = request.GetInstance()
            });

            return(Ok(response));
        }
コード例 #12
0
        public virtual async Task <SingleResult <ChildEntity> > PartialUpdate(long key, Delta <ChildEntity> modifiedDtoDelta, CancellationToken cancellationToken)
        {
            var e = modifiedDtoDelta.GetInstance();

            if (e.Name == "Error")
            {
                throw new DomainLogicException("TestErrorMessage");
            }

            e.Name += "?";

            return(SingleResult(e));
        }
コード例 #13
0
        public async Task <IHttpActionResult> Patch([FromODataUri] int key, Delta <Exercise> delta)
        {
            Validate(delta.GetInstance());

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

            // TODO: Get the entity here.

            // delta.Patch(exercise);

            // TODO: Save the patched entity.

            // return Updated(exercise);
            return(StatusCode(HttpStatusCode.NotImplemented));
        }
コード例 #14
0
        public override async Task <IHttpActionResult> PatchEntity([FromODataUri] int key, Delta <tbDeviceToken> patch)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var deviceToken = _db.tbDeviceTokens.Find(key);

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

            Validate(patch.GetInstance());
            patch.Patch(deviceToken);
            await _db.SaveChangesAsync();

            return(Ok());
        }
コード例 #15
0
 public override IHttpActionResult Patch(int key, Delta <Organization> delta)
 {
     try
     {
         var organization = delta.GetInstance();
         if (organization.TypeId > 0)
         {
             var typeKey = (OrganizationTypeKeys)organization.TypeId;
             if (!_organizationService.CanChangeOrganizationType(organization, typeKey))
             {
                 return(Forbidden());
             }
         }
     }
     catch (SecurityException e)
     {
         return(Forbidden());
     }
     return(base.Patch(key, delta));
 }
コード例 #16
0
        public async Task <IActionResult> PatchAsync(int todoListId, int id, [FromBody] Delta <UpdateToDoItemModel> model, CancellationToken cancellationToken = default)
        {
            if (id != model.GetInstance()?.Id)
            {
                return(this.BadRequest("ToDoItem ID are different in the route and the model"));
            }

            var exists = await this.service.AnyAsync(new ToDoItemByIdSpecification(todoListId, id), cancellationToken);

            if (!exists)
            {
                return(this.NotFound());
            }

            await this.service.PatchAsync <UpdateToDoItemModel, ToDoItem, int>(model, cancellationToken);

            var result = await this.service.FindOneAsync <ToDoItemModel, ToDoItem, int>(id, cancellationToken);

            return(this.Ok(result));
        }
コード例 #17
0
        public virtual IHttpActionResult Patch([FromODataUri] TKey key, Delta <TEntity> delta)
        {
            Validate(delta.GetInstance());

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

            var dbEntity = Db.Set <TEntity>().Find(key);

            var entity = AutoMapperHelper <TEntity, TEntity> .Mapper.Map <TEntity>(dbEntity);

            delta.Patch(entity);
            entity.Id = key;
            //entity.UpdatedTime = DateTime.Now;
            //entity.UpdatedBy = User.Identity.Name;

            dbEntity = AutoMapperHelper <TEntity, TEntity> .Mapper.Map <TEntity>(entity);

            if (Db.Entry(dbEntity).State == EntityState.Modified)
            {
                Db.SaveChanges();
            }
            else if (Db.Entry(dbEntity).State == EntityState.Detached)
            {
                try
                {
                    Db.Set <TEntity>().Attach(dbEntity);
                    Db.Entry(dbEntity).State = EntityState.Modified;
                }
                catch (InvalidOperationException)
                {
                    TEntity old = Db.Set <TEntity>().Find(key);
                    Db.Entry(old).CurrentValues.SetValues(dbEntity);
                }
                Db.SaveChanges();
            }

            return(Updated(entity));
        }
コード例 #18
0
        private async Task <IActionResult> Update(int id, Delta <Category> patch)
#endif
        {
            var category = await FindAsync(id);

            if (category == null)
            {
                return(NotFound());
            }
#if NETCORE10
            _db.Entry(patch as object).State = EntityState.Modified;
#else
            if (!TryValidateModel(patch.GetInstance()))
            {
                return(BadRequest(ModelState));
            }
            patch.Patch(category);
#endif
            try
            {
                await _db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CategoryExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
#if NETCORE10
            return(NoContent());
#else
            return(Updated(category));
#endif
        }
コード例 #19
0
        public VacationReport Edit(Delta <VacationReport> delta)
        {
            var newReport = delta.GetInstance();
            var report    = _reportRepo.AsQueryable().First(x => x.Id == newReport.Id);

            newReport.Person     = report.Person;
            newReport.ApprovedBy = report.ApprovedBy;
            PrepareReport(newReport);
            var shouldNotify = report.Status == ReportStatus.Accepted;

            if (report.ProcessedDateTimestamp != 0)
            {
                DeleteReport(report);
            }
            delta.Patch(report);
            _reportRepo.Save();
            if (shouldNotify)
            {
                SendMailIfUserEditedAprovedReport(newReport, "redigeret");
            }
            return(newReport);
        }
コード例 #20
0
        public override async Task <IHttpActionResult> PatchEntity([FromODataUri] int key, Delta <tbRequestInstance> patch)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var requestInstance = _db.tbRequestInstances.Find(key);

            if (requestInstance == null)
            {
                return(NotFound());
            }
            Validate(patch.GetInstance());

            patch.Patch(requestInstance);
            await _db.SaveChangesAsync();

            SendNotification(key);

            return(Ok());
        }
コード例 #21
0
        public async Task <IHttpActionResult> Patch(int key, Delta <Risposta> patch)
        {
            Validate(patch.GetInstance());
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var risposta = await _db.Risposte.FindAsync(key);

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

            patch.Patch(risposta);
            _db.Entry(risposta).State = EntityState.Modified;

            await _db.SaveChangesAsync();

            return(Updated(risposta));
        }
コード例 #22
0
        public async Task <IHttpActionResult> Patch(Guid key, Delta <Blog> patch)
        {
            Validate(patch.GetInstance());

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

            var blog = await _db.Blogs.FindAsync(key);

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

            patch.Patch(blog);
            _db.Entry(blog).State = EntityState.Modified;

            await _db.SaveChangesAsync();

            return(Updated(blog));
        }
コード例 #23
0
        // PUT: odata/Products(5)
        public IActionResult Put([FromODataUri] int key, [FromBody] Delta <Products> delta)
        {
            TryValidateModel(delta.GetInstance());

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

            // TODO: Get the entity here.
            var item = _context.Products.Find(key);

            if (item == null)
            {
                return(NotFound());
            }
            delta.Put(item);

            // TODO: Save the patched entity.
            try
            {
                _context.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductsExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(Updated(item));
            //return StatusCode(HttpStatusCode.NotImplemented);
        }
コード例 #24
0
        // PUT: odata/ResellerSales(5)
        public IHttpActionResult Put([FromODataUri] string keySalesOrderNumber, [FromODataUri] byte keySalesOrderLineNumber, Delta <FactResellerSale> patch)
        {
            Validate(patch.GetInstance());

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

            FactResellerSale factResellerSale = db.FactResellerSales.Find(keySalesOrderNumber, keySalesOrderLineNumber);

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

            patch.Put(factResellerSale);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FactResellerSaleExists(keySalesOrderNumber, keySalesOrderLineNumber))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(factResellerSale));
        }
コード例 #25
0
        // PUT: odata/TaskStatus(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta <TaskStatus> patch)
        {
            Validate(patch.GetInstance());

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

            TaskStatus taskStatus = db.TaskStatus.Find(key);

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

            patch.Put(taskStatus);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TaskStatusExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(taskStatus));
        }
コード例 #26
0
        // PUT: odata/LearningTypes(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta <LearningType> patch)
        {
            Validate(patch.GetInstance());

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

            LearningType learningType = db.LearningTypes.Find(key);

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

            patch.Put(learningType);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LearningTypeExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(learningType));
        }
コード例 #27
0
        // PUT: odata/StateProvinces(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta <StateProvince> patch)
        {
            Validate(patch.GetInstance());

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

            StateProvince stateProvince = _db.StateProvinces.Find(key);

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

            patch.Put(stateProvince);

            try
            {
                _db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StateProvinceExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(stateProvince));
        }
コード例 #28
0
        // PUT: odata/ProductSubcategories(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta <DimProductSubcategory> patch)
        {
            Validate(patch.GetInstance());

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

            DimProductSubcategory dimProductSubcategory = db.DimProductSubcategories.Find(key);

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

            patch.Put(dimProductSubcategory);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DimProductSubcategoryExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(dimProductSubcategory));
        }
コード例 #29
0
        public IHttpActionResult Patch([FromODataUri] int key, Delta <PhoneNumberType> patch)
        {
            Validate(patch.GetInstance());

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

            PhoneNumberType phoneNumberType = _db.PhoneNumberTypes.Find(key);

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

            patch.Patch(phoneNumberType);

            try
            {
                _db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PhoneNumberTypeExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(phoneNumberType));
        }
コード例 #30
0
        // PUT: odata/ApplicationUsers(5)
        public IHttpActionResult Put([FromODataUri] string key, Delta <ApplicationUser> patch)
        {
            Validate(patch.GetInstance());

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

            ApplicationUser applicationUser = db.Users.Find(key);

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

            patch.Put(applicationUser);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ApplicationUserExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(applicationUser));
        }