public Task <ResponseBase> Handle(HttpInformation context, InfoCommand command)
        {
            SapphireDbContext db = GetContext(command.ContextName);

            KeyValuePair <Type, string> property = db.GetType().GetDbSetType(command.CollectionName);

            if (property.Key != null)
            {
                // if (!property.Key.CanQuery(context, serviceProvider))
                // {
                //     return Task.FromResult(
                //         command.CreateExceptionResponse<InfoResponse>(
                //             "Not allowed to query information for collection"));
                // }

                InfoResponse infoResponse = new InfoResponse
                {
                    PrimaryKeys = property.Key.GetPrimaryKeyNames(db),
                    ReferenceId = command.ReferenceId
                };

                return(Task.FromResult <ResponseBase>(infoResponse));
            }

            return(Task.FromResult(command.CreateExceptionResponse <InfoResponse>("No set for collection was found.")));
        }
Beispiel #2
0
        private ResponseBase SetPropertiesAndValidate(SapphireDbContext db, KeyValuePair <Type, string> property, object newValue, HttpInformation context,
                                                      CreateCommand command)
        {
            object newEntityObject = property.Key.SetFields(newValue, db);

            if (!ValidationHelper.ValidateModel(newEntityObject, serviceProvider, out Dictionary <string, List <string> > validationResults))
            {
                return(new CreateResponse()
                {
                    NewObject = newEntityObject,
                    ReferenceId = command.ReferenceId,
                    ValidationResults = validationResults
                });
            }

            property.Key.ExecuteHookMethods <CreateEventAttribute>(v => v.Before, newEntityObject, context, serviceProvider);

            db.Add(newEntityObject);

            property.Key.ExecuteHookMethods <CreateEventAttribute>(v => v.BeforeSave, newEntityObject, context, serviceProvider);

            db.SaveChanges();

            property.Key.ExecuteHookMethods <CreateEventAttribute>(v => v.After, newEntityObject, context, serviceProvider);

            return(new CreateResponse()
            {
                NewObject = newEntityObject,
                ReferenceId = command.ReferenceId
            });
        }
Beispiel #3
0
        private UpdateResponse ApplyChangesToDb(UpdateRangeCommand command, KeyValuePair <Type, string> property, object dbValue,
                                                JObject originalValue,
                                                JObject updatedProperties, SapphireDbContext db, HttpInformation context)
        {
            int insteadOfExecuteCount = property.Key.ExecuteHookMethods <UpdateEventAttribute>(
                ModelStoreEventAttributeBase.EventType.InsteadOf,
                dbValue, null, context, serviceProvider);

            if (insteadOfExecuteCount > 0)
            {
                return(new UpdateResponse());
            }

            property.Key.ExecuteHookMethods <UpdateEventAttribute>(ModelStoreEventAttributeBase.EventType.Before,
                                                                   dbValue, updatedProperties, context, serviceProvider);

            List <Tuple <string, string> > mergeErrors = null;

            DateTimeOffset?modifiedOn = originalValue.GetTimestamp();

            if (dbValue is SapphireOfflineEntity dbValueOfflineEntity &&
                property.Key.JsonContainsData(db, originalValue) &&
                modifiedOn.HasValue &&
                !dbValueOfflineEntity.ModifiedOn.EqualWithTolerance(modifiedOn.Value, db.Database.ProviderName))
            {
                if (property.Key.GetModelAttributesInfo().DisableAutoMergeAttribute == null)
                {
                    mergeErrors = property.Key.MergeFields(dbValueOfflineEntity, originalValue,
                                                           updatedProperties, context, serviceProvider);
                }
                else
                {
                    throw new UpdateRejectedException(command.ContextName, command.CollectionName, originalValue, updatedProperties);
                }
            }
        private ResponseBase SaveChangesToDb(KeyValuePair <Type, string> property, object value, object updateValue,
                                             SapphireDbContext db, HttpInformation context, UpdateCommand command)
        {
            property.Key.ExecuteHookMethods <UpdateEventAttribute>(v => v.Before, value, context, serviceProvider);

            property.Key.UpdateFields(value, updateValue, db, context, serviceProvider);

            if (!ValidationHelper.ValidateModel(value, serviceProvider, out Dictionary <string, List <string> > validationResults))
            {
                return(new UpdateResponse()
                {
                    UpdatedObject = value,
                    ReferenceId = command.ReferenceId,
                    ValidationResults = validationResults
                });
            }

            db.Update(value);

            property.Key.ExecuteHookMethods <UpdateEventAttribute>(v => v.BeforeSave, value, context, serviceProvider);

            db.SaveChanges();

            property.Key.ExecuteHookMethods <UpdateEventAttribute>(v => v.After, value, context, serviceProvider);

            return(new UpdateResponse()
            {
                UpdatedObject = value,
                ReferenceId = command.ReferenceId
            });
        }
Beispiel #5
0
        public Task <ResponseBase> Handle(HttpInformation context, SubscribeCommand command,
                                          ExecutionContext executionContext)
        {
            if (databaseOptions.DisableIncludePrefilter && command.Prefilters.Any(p => p is IncludePrefilter))
            {
                throw new IncludeNotAllowedException(command.ContextName, command.CollectionName);
            }

            if (databaseOptions.DisableSelectPrefilter && command.Prefilters.Any(p => p is SelectPrefilter))
            {
                throw new SelectNotAllowedException(command.ContextName, command.CollectionName);
            }

            SapphireDbContext           db       = GetContext(command.ContextName);
            KeyValuePair <Type, string> property = CollectionHelper.GetCollectionType(db, command);

            if (property.Key.GetModelAttributesInfo().DisableQueryAttribute != null)
            {
                throw new OperationDisabledException("Query", command.ContextName, command.CollectionName);
            }

            command.Prefilters.ForEach(prefilter => prefilter.Initialize(property.Key));
            ResponseBase response = CollectionHelper.GetCollection(db, command, property, command.Prefilters, context, serviceProvider);

            subscriptionManager.AddSubscription(command.ContextName, command.CollectionName, command.Prefilters, Connection, command.ReferenceId);

            return(Task.FromResult(response));
        }
Beispiel #6
0
        private ResponseBase CreateObjects(CreateRangeCommand command, KeyValuePair <Type, string> property,
                                           HttpInformation context, SapphireDbContext db)
        {
            object[] newValues = command.Values.Values <JObject>().Select(newValue => newValue.ToObject(property.Key))
                                 .ToArray();

            CreateRangeResponse response = new CreateRangeResponse
            {
                ReferenceId = command.ReferenceId,
                Results     = newValues.Select(value =>
                {
                    if (!property.Key.CanCreate(context, value, serviceProvider))
                    {
                        throw new UnauthorizedException("The user is not authorized for this action");
                    }

                    return(SetPropertiesAndValidate <CreateEventAttribute>(db, property, value, context,
                                                                           serviceProvider));
                }).ToList()
            };

            db.SaveChanges();

            foreach (object value in newValues)
            {
                property.Key.ExecuteHookMethods <CreateEventAttribute>(ModelStoreEventAttributeBase.EventType.After,
                                                                       value, context, serviceProvider);
            }

            return(response);
        }
Beispiel #7
0
        public static CreateResponse SetPropertiesAndValidate <TEventAttribute>(SapphireDbContext db,
                                                                                KeyValuePair <Type, string> property, object newValue,
                                                                                HttpInformation context, IServiceProvider serviceProvider)
            where TEventAttribute : ModelStoreEventAttributeBase
        {
            object newEntityObject = property.Key.SetFields(newValue);

            if (!ValidationHelper.ValidateModel(newEntityObject, serviceProvider,
                                                out Dictionary <string, List <string> > validationResults))
            {
                return(new CreateResponse()
                {
                    Value = newEntityObject,
                    ValidationResults = validationResults
                });
            }

            property.Key.ExecuteHookMethods <TEventAttribute>(ModelStoreEventAttributeBase.EventType.Before,
                                                              newEntityObject, context, serviceProvider);

            db.Add(newEntityObject);

            property.Key.ExecuteHookMethods <TEventAttribute>(ModelStoreEventAttributeBase.EventType.BeforeSave,
                                                              newEntityObject, context, serviceProvider);

            return(new CreateResponse()
            {
                Value = newEntityObject,
            });
        }
Beispiel #8
0
        private UpdateResponse ApplyChangesToDb(KeyValuePair <Type, string> property, object dbValue,
                                                JObject originalValue,
                                                JObject updatedProperties, SapphireDbContext db, HttpInformation context)
        {
            property.Key.ExecuteHookMethods <UpdateEventAttribute>(ModelStoreEventAttributeBase.EventType.Before,
                                                                   dbValue, context, serviceProvider);

            List <Tuple <string, string> > mergeErrors = null;

            DateTime?modifiedOn = originalValue.GetTimestamp();

            if (dbValue is SapphireOfflineEntity dbValueOfflineEntity &&
                property.Key.JsonContainsData(db, originalValue) &&
                modifiedOn.HasValue &&
                !dbValueOfflineEntity.ModifiedOn.EqualWithTolerance(modifiedOn.Value, db.Database.ProviderName))
            {
                if (property.Key.GetModelAttributesInfo().DisableAutoMergeAttribute == null)
                {
                    mergeErrors = property.Key.MergeFields(dbValueOfflineEntity, originalValue,
                                                           updatedProperties, context, serviceProvider);
                }
                else
                {
                    return(new UpdateResponse()
                    {
                        Value = originalValue,
                        UpdatedProperties = updatedProperties,
                        Error = new SapphireDbError(
                            new OperationRejectedException("Update rejected. The object state has changed"))
                    });
                }
            }
Beispiel #9
0
 public static object[] GetPrimaryKeyValuesFromJson(this Type type, SapphireDbContext db, JObject jsonObject)
 {
     return(type.GetPrimaryKeys(db)
            .Select(p =>
                    jsonObject.GetValue(p.PropertyInfo.Name.ToCamelCase())
                    .ToObject(p.PropertyInfo.PropertyType))
            .ToArray());
 }
Beispiel #10
0
        public static ResponseBase GetCollection(SapphireDbContext db, QueryCommand command,
                                                 HttpInformation information, IServiceProvider serviceProvider)
        {
            SapphireDatabaseOptions sapphireDatabaseOptions = serviceProvider.GetService <SapphireDatabaseOptions>();

            if (sapphireDatabaseOptions.DisableIncludePrefilter && command.Prefilters.Any(p => p is IncludePrefilter))
            {
                throw new IncludeNotAllowedException(command.CollectionName);
            }

            Type dbContextType = db.GetType();
            KeyValuePair <Type, string> property = dbContextType.GetDbSetType(command.CollectionName);

            if (property.Key == null)
            {
                throw new CollectionNotFoundException(command.CollectionName);
            }

            if (!property.Key.CanQuery(information, serviceProvider))
            {
                throw new UnauthorizedException("Not allowed to query values from collection");
            }

            IQueryable <object> collectionValues = db.GetCollectionValues(property, command.Prefilters);

            QueryResponse queryResponse = new QueryResponse()
            {
                ReferenceId = command.ReferenceId,
            };

            IAfterQueryPrefilter afterQueryPrefilter =
                command.Prefilters.OfType <IAfterQueryPrefilter>().FirstOrDefault();

            if (afterQueryPrefilter != null)
            {
                afterQueryPrefilter.Initialize(property.Key);
                queryResponse.Result = afterQueryPrefilter.Execute(collectionValues);
            }
            else
            {
                IEnumerable <object> values = collectionValues.AsEnumerable();

                ModelAttributesInfo modelAttributesInfo = property.Key.GetModelAttributesInfo();

                if (modelAttributesInfo.QueryEntryAuthAttributes.Any())
                {
                    values = values.Where(value => property.Key.CanQueryEntry(information, serviceProvider, value));
                }

                values = values.Select(v => v.GetAuthenticatedQueryModel(information, serviceProvider));

                queryResponse.Result = values.ToList();
            }

            return(queryResponse);
        }
Beispiel #11
0
 public string GetJobNumberByHomeRID(int homeRID)
 {
     using (var _db = new SapphireDbContext())
     {
         return(_db.Jobs
                .Where(j => j.HomeRID.Equals(homeRID))
                .Select(j => j.JobID.Substring(0, 12))
                .FirstOrDefault());
     }
 }
Beispiel #12
0
 public int GetHomeRIDByJobNumber(string jobNumber)
 {
     using (var _db = new SapphireDbContext())
     {
         return(_db.Jobs
                .Where(j => j.JobID.Substring(0, 12).Equals(jobNumber))
                .Select(h => h.HomeRID)
                .FirstOrDefault());
     }
 }
        public static IQueryable <object> GetCollectionValues(this SapphireDbContext db,
                                                              KeyValuePair <Type, string> property, List <IPrefilterBase> prefilters)
        {
            IQueryable <object> collectionSet = db.GetValues(property);

            foreach (IPrefilter prefilter in prefilters.OfType <IPrefilter>())
            {
                collectionSet = prefilter.Execute(collectionSet);
            }

            return(collectionSet);
        }
Beispiel #14
0
 public List <Workflow> GetSapphireWorkflow(int homeRID = 0)
 {
     using (var _db = new SapphireDbContext())
     {
         return(_db.Workflows
                .Where(w => w.RefObjType == "Home" &&
                       w.Name == "Home Estimate Status Approved" &&
                       ((!(homeRID.Equals(0)) && w.RefObjRID.Equals(homeRID)) ||
                        (homeRID.Equals(0)))
                       ).ToList());
     }
 }
        public static KeyValuePair <Type, string> GetCollectionType(SapphireDbContext db, IQueryCommand command)
        {
            Type dbContextType = db.GetType();
            KeyValuePair <Type, string> property = dbContextType.GetDbSetType(command.CollectionName);

            if (property.Key == null)
            {
                throw new CollectionNotFoundException(command.ContextName, command.CollectionName);
            }

            return(property);
        }
        public static IQueryable <object> GetCollectionValues(this SapphireDbContext db, IServiceProvider serviceProvider, HttpInformation information, KeyValuePair <Type, string> property, List <IPrefilterBase> prefilters)
        {
            IQueryable <object> collectionSet = db.GetValues(property, serviceProvider, information);

            foreach (IPrefilter prefilter in prefilters.OfType <IPrefilter>())
            {
                prefilter.Initialize(property.Key);
                collectionSet = prefilter.Execute(collectionSet);
            }

            return(collectionSet);
        }
Beispiel #17
0
        public async Task <ResponseBase> Handle(HttpInformation context, UpdateRangeCommand command,
                                                ExecutionContext executionContext)
        {
            SapphireDbContext           db       = GetContext(command.ContextName);
            KeyValuePair <Type, string> property = db.GetType().GetDbSetType(command.CollectionName);

            if (property.Key != null)
            {
                return(await InitializeUpdate(command, property, context, db));
            }

            throw new CollectionNotFoundException(command.CollectionName);
        }
Beispiel #18
0
        public Task <ResponseBase> Handle(HttpInformation context, CreateRangeCommand command,
                                          ExecutionContext executionContext)
        {
            SapphireDbContext           db       = GetContext(command.ContextName);
            KeyValuePair <Type, string> property = db.GetType().GetDbSetType(command.CollectionName);

            if (property.Key != null)
            {
                return(Task.FromResult(CreateObjects(command, property, context, db)));
            }

            throw new CollectionNotFoundException(command.CollectionName);
        }
        public Task <ResponseBase> Handle(HttpInformation context, QueryQueryCommand queryCommand,
                                          ExecutionContext executionContext)
        {
            SapphireDbContext           db       = GetContext(queryCommand.ContextName);
            KeyValuePair <Type, string> property = CollectionHelper.GetCollectionType(db, queryCommand);

            List <IPrefilterBase> prefilters =
                CollectionHelper.GetQueryPrefilters(property, queryCommand, Connection.Information, serviceProvider);

            ResponseBase response = CollectionHelper.GetCollection(db, queryCommand, property, prefilters, context, serviceProvider);

            return(Task.FromResult(response));
        }
Beispiel #20
0
        public static bool JsonContainsData(this Type type, SapphireDbContext db, JObject jsonObject)
        {
            bool isOfflineEntity = typeof(SapphireOfflineEntity).IsAssignableFrom(type);

            string[] defaultPropertyList = type.GetPrimaryKeys(db)
                                           .Select(p => p.PropertyInfo.Name.ToCamelCase())
                                           .Concat(isOfflineEntity ? new [] { "modifiedOn" } : new string[] {})
                                           .ToArray();

            List <JProperty> jsonObjectProperties = jsonObject.Properties().ToList();

            return(defaultPropertyList.All(p => jsonObjectProperties.Any(jp => jp.Name == p)) &&
                   jsonObjectProperties.Count > defaultPropertyList.Length);
        }
Beispiel #21
0
        public static ResponseBase GetCollection(SapphireDbContext db, QueryCommand command,
                                                 HttpInformation information, IServiceProvider serviceProvider)
        {
            Type dbContextType = db.GetType();
            KeyValuePair <Type, string> property = dbContextType.GetDbSetType(command.CollectionName);

            if (property.Key != null)
            {
                if (!property.Key.CanQuery(information, serviceProvider))
                {
                    return(command.CreateExceptionResponse <QueryResponse>(
                               "Not allowed to query values from collection"));
                }

                IQueryable <object> collectionValues = db.GetCollectionValues(serviceProvider, information, property, command.Prefilters);

                QueryResponse queryResponse = new QueryResponse()
                {
                    ReferenceId = command.ReferenceId,
                };

                IAfterQueryPrefilter afterQueryPrefilter = command.Prefilters.OfType <IAfterQueryPrefilter>().FirstOrDefault();

                if (afterQueryPrefilter != null)
                {
                    afterQueryPrefilter.Initialize(property.Key);
                    queryResponse.Result = afterQueryPrefilter.Execute(collectionValues);
                }
                else
                {
                    IEnumerable <object> values = collectionValues.AsEnumerable();

                    AuthModelInfo authModelInfo = property.Key.GetAuthModelInfos();

                    if (authModelInfo.QueryEntryAuthAttributes.Any())
                    {
                        values = values.Where(value => property.Key.CanQueryEntry(information, serviceProvider, value));
                    }

                    values = values.Select(v => v.GetAuthenticatedQueryModel(information, serviceProvider));

                    queryResponse.Result = values.ToList();
                }

                return(queryResponse);
            }

            return(command.CreateExceptionResponse <QueryResponse>("No set for collection was found."));
        }
        private UpdateResponse ApplyChangesToDb(KeyValuePair <Type, string> property, object dbValue, object updateValue,
                                                object previousValue, SapphireDbContext db, HttpInformation context)
        {
            property.Key.ExecuteHookMethods <UpdateEventAttribute>(ModelStoreEventAttributeBase.EventType.Before, dbValue, context, serviceProvider);

            List <string> mergeErrors = null;

            if (dbValue is SapphireOfflineEntity dbValueOfflineEntity &&
                updateValue is SapphireOfflineEntity updateOfflineEntity &&
                previousValue != null && previousValue is SapphireOfflineEntity previousValueOfflineEntity &&
                dbValueOfflineEntity.ModifiedOn.RoundToMilliseconds() !=
                updateOfflineEntity.ModifiedOn.RoundToMilliseconds())
            {
                mergeErrors = property.Key.MergeFields(dbValueOfflineEntity, updateOfflineEntity,
                                                       previousValueOfflineEntity, context, serviceProvider);
            }
        public Task <ResponseBase> Handle(HttpInformation context, DeleteCommand command)
        {
            SapphireDbContext           db       = GetContext(command.ContextName);
            KeyValuePair <Type, string> property = db.GetType().GetDbSetType(command.CollectionName);

            if (property.Key != null)
            {
                try
                {
                    object[] primaryKeys = property.Key.GetPrimaryKeyValues(db, command.PrimaryKeys);
                    object   value       = db.Find(property.Key, primaryKeys);

                    if (!property.Key.CanRemove(context, value, serviceProvider))
                    {
                        return(Task.FromResult(command.CreateExceptionResponse <DeleteResponse>(
                                                   "The user is not authorized for this action.")));
                    }

                    if (value != null)
                    {
                        property.Key.ExecuteHookMethods <RemoveEventAttribute>(ModelStoreEventAttributeBase.EventType.Before, value, context, serviceProvider);

                        db.Remove(value);

                        property.Key.ExecuteHookMethods <RemoveEventAttribute>(ModelStoreEventAttributeBase.EventType.BeforeSave, value, context, serviceProvider);

                        db.SaveChanges();

                        property.Key.ExecuteHookMethods <RemoveEventAttribute>(ModelStoreEventAttributeBase.EventType.After, value, context, serviceProvider);

                        return(Task.FromResult <ResponseBase>(new DeleteResponse()
                        {
                            ReferenceId = command.ReferenceId
                        }));
                    }

                    return(Task.FromResult(command.CreateExceptionResponse <DeleteResponse>("The value was not found.")));
                }
                catch (Exception ex)
                {
                    return(Task.FromResult(command.CreateExceptionResponse <DeleteResponse>(ex)));
                }
            }

            return(Task.FromResult(command.CreateExceptionResponse <DeleteResponse>("No set for collection was found.")));
        }
        public async Task <ResponseBase> Handle(HttpInformation context, InvokeCommand command, ExecutionContext executionContext)
        {
            SapphireDbContext           db       = GetContext(command.ContextName);
            KeyValuePair <Type, string> property = db.GetType().GetDbSetType(command.CollectionName);

            if (property.Key == null)
            {
                throw new CollectionNotFoundException(command.ContextName, command.CollectionName);
            }

            object[] primaryKeys = property.Key.GetPrimaryKeyValues(db, command.PrimaryKeys);
            object   value       = db.Find(property.Key, primaryKeys);

            if (value == null)
            {
                throw new ValueNotFoundException(command.ContextName, command.CollectionName, primaryKeys);
            }

            MethodInfo methodInfo = ReflectionMethodHelper.GetMethodInfo(property.Key, command.Action);

            if (methodInfo == null)
            {
                throw new MethodNotFoundException(property.Key.Name, command.Action);
            }

            if (methodInfo.GetCustomAttribute <InvokableAttribute>() == null)
            {
                throw new NotInvokableException(command.ContextName, command.CollectionName, command.Action);
            }

            object result = methodInfo.Invoke(value, methodInfo.CreateParameters(context, serviceProvider, command.Parameters, db));

            if (result != null)
            {
                result = await ActionHelper.HandleAsyncResult(result);
            }

            logger.LogInformation("Executed {CollectionName}.{ActionName}. ExecutionId: {ExecutionId}", property.Value, methodInfo.Name, executionContext.Id);

            return(new InvokeResponse()
            {
                ReferenceId = command.ReferenceId,
                Result = result
            });
        }
Beispiel #25
0
        public async Task <ResponseBase> Handle(HttpInformation context, UpdateRangeCommand command,
                                                ExecutionContext executionContext)
        {
            SapphireDbContext           db       = GetContext(command.ContextName);
            KeyValuePair <Type, string> property = db.GetType().GetDbSetType(command.CollectionName);

            if (property.Key == null)
            {
                throw new CollectionNotFoundException(command.ContextName, command.CollectionName);
            }

            if (property.Key.GetModelAttributesInfo().DisableUpdateAttribute != null)
            {
                throw new OperationDisabledException("Update", command.ContextName, command.CollectionName);
            }

            return(await InitializeUpdate(command, property, context, db));
        }
        public Task <ResponseBase> Handle(HttpInformation context, UpdateCommand command)
        {
            SapphireDbContext           db       = GetContext(command.ContextName);
            KeyValuePair <Type, string> property = db.GetType().GetDbSetType(command.CollectionName);

            if (property.Key != null)
            {
                try
                {
                    return(Task.FromResult(InitializeUpdate(command, property, context, db)));
                }
                catch (Exception ex)
                {
                    return(Task.FromResult(command.CreateExceptionResponse <UpdateResponse>(ex)));
                }
            }

            return(Task.FromResult(command.CreateExceptionResponse <UpdateResponse>("No set for collection was found.")));
        }
Beispiel #27
0
        public async Task <ResponseBase> Handle(HttpInformation context, UpdateRangeCommand command)
        {
            SapphireDbContext           db       = GetContext(command.ContextName);
            KeyValuePair <Type, string> property = db.GetType().GetDbSetType(command.CollectionName);

            if (property.Key != null)
            {
                try
                {
                    return(await InitializeUpdate(command, property, context, db));
                }
                catch (Exception ex)
                {
                    return(command.CreateExceptionResponse <UpdateRangeResponse>(ex));
                }
            }

            return(command.CreateExceptionResponse <UpdateRangeResponse>(new CollectionNotFoundException()));
        }
        private ResponseBase InitializeUpdate(UpdateCommand command, KeyValuePair <Type, string> property,
                                              HttpInformation context, SapphireDbContext db)
        {
            object updateValue = command.UpdateValue.ToObject(property.Key);

            if (!property.Key.CanUpdate(context, updateValue, serviceProvider))
            {
                return(command.CreateExceptionResponse <UpdateResponse>("The user is not authorized for this action."));
            }

            object[] primaryKeys = property.Key.GetPrimaryKeyValues(db, updateValue);
            object   value       = db.Find(property.Key, primaryKeys);

            if (value != null)
            {
                db.Entry(value).State = EntityState.Detached;
                return(SaveChangesToDb(property, value, updateValue, db, context, command));
            }

            return(command.CreateExceptionResponse <UpdateResponse>("No value to update was found"));
        }
        public static ResponseBase GetCollection(SapphireDbContext db, IQueryCommand command, KeyValuePair <Type, string> property, List <IPrefilterBase> prefilters,
                                                 HttpInformation information, IServiceProvider serviceProvider)
        {
            if (!property.Key.CanQuery(information, serviceProvider))
            {
                throw new UnauthorizedException("Not allowed to query values from collection");
            }

            IQueryable <object> collectionValues = db.GetCollectionValues(property, prefilters);

            QueryResponse queryResponse = new QueryResponse()
            {
                ReferenceId = command.ReferenceId,
            };

            IAfterQueryPrefilter afterQueryPrefilter =
                prefilters.OfType <IAfterQueryPrefilter>().FirstOrDefault();

            if (afterQueryPrefilter != null)
            {
                queryResponse.Result = afterQueryPrefilter.Execute(collectionValues);
            }
            else
            {
                IEnumerable <object> values = collectionValues.AsEnumerable();

                ModelAttributesInfo modelAttributesInfo = property.Key.GetModelAttributesInfo();

                if (modelAttributesInfo.QueryEntryAuthAttributes.Any())
                {
                    values = values.Where(value => property.Key.CanQueryEntry(information, serviceProvider, value));
                }

                values = values.Select(v => v.GetAuthenticatedQueryModel(information, serviceProvider));

                queryResponse.Result = values.ToList();
            }

            return(queryResponse);
        }
Beispiel #30
0
        public ChangeResponse(EntityEntry change, SapphireDbContext db)
        {
            Value         = change.Entity;
            PrimaryValues = Value.GetType().GetPrimaryKeyValues(db, Value);

            CollectionName = ((SapphireDbContext)change.Context).GetType().GetDbSetTypes()[change.Metadata.ClrType].ToLowerInvariant();

            switch (change.State)
            {
            case EntityState.Added:
                State = ChangeState.Added;
                break;

            case EntityState.Deleted:
                State = ChangeState.Deleted;
                break;

            case EntityState.Modified:
                State = ChangeState.Modified;
                break;
            }
        }