Ejemplo n.º 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));
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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));
        }
    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));
    }
Ejemplo n.º 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));
            }
        }
        public override Task <TestCustomerDto> PartialUpdate(Guid key, Delta <TestCustomerDto> modifiedDtoDelta, CancellationToken cancellationToken)
        {
            TestCustomerDto dto = modifiedDtoDelta.GetInstance();

            dto.Name += "#";

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

            model.ComplexObj.Name += "?";

            return(SingleResult(model));
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 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));
        }
        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());
        }
Ejemplo n.º 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));
 }
Ejemplo n.º 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));
        }
Ejemplo n.º 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));
        }
        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
        }
        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);
        }
        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());
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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));
        }
        // 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));
        }
Ejemplo n.º 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));
        }
        // 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));
        }
        // 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));
        }
        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));
        }
        // 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));
        }