Example #1
0
        /// <summary>
        /// Performs a simple POST operation composed of one object corresponding to the entity type that the object was sent to.
        /// </summary>
        /// <param name="type">The type of object that needs to be resolved.</param>
        /// <param name="postBody">The POST body to be processed.</param>
        /// <returns>The response <see cref="Negotiator"/> with either a success or failure.</returns>
        protected Negotiator PerformSimplePost(dynamic type, string postBody)
        {
            var           instance = Activator.CreateInstance(type);
            IEntityObject savedThing;

            try
            {
                JsonConvert.PopulateObject(postBody, instance);
            }
            catch (Exception e)
            {
                return(ApiHelper.ConstructFailResponse(this.Negotiate, "create",
                                                       "The request was not properly formatted and could not be used to create the object!", this.Context,
                                                       HttpStatusCode.BadRequest, e));
            }

            // give a new uuid to the instance
            instance.Uuid = Guid.NewGuid();

            try
            {
                // acquire the response
                IEntityObject resp;

                try
                {
                    resp =
                        (IEntityObject)type.GetMethod("Find",
                                                      BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)
                        .Invoke(null, new[] { instance.Uuid });

                    if (resp != null)
                    {
                        // if there is an object of this type in the database then this POST is invalid
                        return(ApiHelper.ConstructFailResponse(this.Negotiate, type.Name,
                                                               "An object with this Uuid already exists and cannot be created!", this.Context,
                                                               HttpStatusCode.Conflict));
                    }
                }
                catch (Exception e)
                {
                    return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
                }

                var transaction = DatabaseSession.Instance.CreateTransaction();
                savedThing = instance.Save(transaction: transaction);
                DatabaseSession.Instance.CommitTransaction(transaction);
            }
            catch (Exception e)
            {
                return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
            }

            var container = new ResponseContainer();

            container.AddToResponse(savedThing);

            return(ApiHelper.ConstructSuccessResponse(this.Negotiate, container, this.Context,
                                                      HttpStatusCode.Created));
        }
Example #2
0
        /// <summary>
        /// Usergroup module
        /// </summary>
        public UsergroupModule()
        {
            // get
            this.Get(
                "/Usergroup",
                x =>
            {
                var entity = "Usergroup";

                var type = ApiHelper.GetEntityTypeFromName(@"Redshift.Seed.Model", entity, "Redshift.Seed");

                List <Attribute> attributes;

                var typeErrors =
                    ApiHelper.GetTypeErrors(this.Negotiate, entity, type, out attributes, this.Context);

                if (typeErrors != null)
                {
                    return(typeErrors);
                }

                List <Usergroup> resp;
                QueryParameterContainer queryParams;
                var count = -1L;

                try
                {
                    queryParams = this.ProcessQueryParameters(this.Request, type);
                }
                catch (Exception)
                {
                    return(ApiHelper.ConstructFailResponse(
                               this.Negotiate,
                               entity,
                               "The query parameters are badly formatted and cannot be parsed.",
                               this.Context,
                               HttpStatusCode.BadRequest));
                }

                try
                {
                    if (queryParams.IsFiltered && !queryParams.IsPaginated)
                    {
                        resp = Usergroup.Where(queryParams.FilterList, true, null, null, queryParams.OrderProperty,
                                               queryParams.IsDescending);

                        if (queryParams.IsCountExpected)
                        {
                            // all entities are already queried and in memory so simple count is fine
                            count = resp.Count;
                        }
                    }
                    else if (queryParams.IsPaginated)
                    {
                        // when paginating, always return count
                        queryParams.IsCountExpected = true;

                        resp = Usergroup.Where(queryParams.FilterList, true, queryParams.Limit, queryParams.Offset,
                                               queryParams.OrderProperty, queryParams.IsDescending);

                        // paginated response provide count always and the count is of total filtered records
                        count = Usergroup.CountWhere(queryParams.FilterList);
                    }
                    else
                    {
                        resp = Usergroup.Where(queryParams.FilterList, true, null, null, null, true);

                        if (queryParams.IsCountExpected)
                        {
                            // all entities are already queried and in memory so simple count is fine
                            count = resp.Count;
                        }
                    }
                }
                catch (Exception e)
                {
                    return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
                }

                var response = new ResponseContainer();
                response.AddToResponse(resp);

                // add count to the response
                if (queryParams.IsCountExpected)
                {
                    response.Add("count", new List <object> {
                        count
                    });
                }

                return(ApiHelper.ConstructSuccessResponse(this.Negotiate, response, this.Context));
            });

            this.Get(
                "/Usergroup/{uuid:guid}",
                x =>
            {
                // parse id
                var uuid = ApiHelper.GetIdFromString(x.uuid.ToString());

                if (uuid == null)
                {
                    return(ApiHelper.ConstructFailResponse(
                               this.Negotiate,
                               "uuid",
                               string.Format("The requested uuid {0} cannot be parsed.", x.uuid),
                               this.Context,
                               HttpStatusCode.BadRequest));
                }

                // parse entity
                var entity = "Usergroup";

                var type = ApiHelper.GetEntityTypeFromName(@"Redshift.Seed.Model", entity, "Redshift.Seed");

                List <Attribute> attributes;
                var typeErrors =
                    ApiHelper.GetTypeErrors(this.Negotiate, entity, type, out attributes, this.Context);

                if (typeErrors != null)
                {
                    return(typeErrors);
                }

                // acquire the response
                Usergroup resp;

                try
                {
                    resp = Usergroup.Find(uuid);
                }
                catch (Exception e)
                {
                    return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
                }

                if (resp == null)
                {
                    return(ApiHelper.ConstructFailResponse(
                               this.Negotiate,
                               "uuid",
                               string.Format("The requested {1} with id {0} does not exist.", uuid, entity),
                               this.Context));
                }

                var response = new ResponseContainer();
                response.AddToResponse(resp);

                return(ApiHelper.ConstructSuccessResponse(this.Negotiate, response, this.Context));
            });

            this.Post(
                "/Usergroup",
                x =>
            {
                var postBody = RequestStream.FromStream(this.Request.Body).AsString();

                var entity = "Usergroup";
                var type   = ApiHelper.GetEntityTypeFromName(@"Redshift.Seed.Model", entity, "Redshift.Seed");

                List <Attribute> attributes;

                var typeErrors = ApiHelper.GetTypeErrors(
                    this.Negotiate,
                    entity,
                    type,
                    out attributes,
                    this.Context);

                if (typeErrors != null)
                {
                    return(typeErrors);
                }

                // demoinstrates a way to generalize
                return(this.PerformSimplePost(type, postBody));
            });

            this.Put(
                "/Usergroup/{uuid:guid}",
                x =>
            {
                var uuid    = ApiHelper.GetIdFromString(x.uuid.ToString());
                var putBody = RequestStream.FromStream(Request.Body).AsString();

                var entity = "Usergroup";
                var type   = ApiHelper.GetEntityTypeFromName(@"Redshift.Seed.Model", entity, "Redshift.Seed");

                var typeErrors = ApiHelper.GetTypeErrors(
                    this.Negotiate,
                    entity,
                    type,
                    out var attributes,
                    this.Context);

                if (typeErrors != null)
                {
                    return(typeErrors);
                }

                IEntityObject savedResp;

                try
                {
                    // acquire the response
                    Usergroup resp;

                    try
                    {
                        resp = Usergroup.Find(uuid);

                        if (resp != null)
                        {
                            try
                            {
                                JsonConvert.PopulateObject(
                                    putBody,
                                    resp);

                                // make sure the uuid is set correctly/not being changed.
                                resp.Uuid = uuid;
                            }
                            catch (Exception e)
                            {
                                return(ApiHelper.ConstructFailResponse(this.Negotiate, "update",
                                                                       "The request was not properly formatted and could not be used to update the object!",
                                                                       this.Context, HttpStatusCode.BadRequest, e));
                            }
                        }
                        else
                        {
                            // if there is an object of this type in the database then this POST is invalid
                            return(ApiHelper.ConstructFailResponse(
                                       this.Negotiate,
                                       type.Name,
                                       "An object with this Uuid does not exist and cannot be updated!",
                                       this.Context,
                                       HttpStatusCode.NotFound));
                        }
                    }
                    catch (Exception e)
                    {
                        return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
                    }

                    var transaction = DatabaseSession.Instance.CreateTransaction();
                    savedResp       = resp.Save(transaction: transaction);
                    DatabaseSession.Instance.CommitTransaction(transaction);
                }
                catch (Exception e)
                {
                    return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
                }

                var container = new ResponseContainer();
                container.AddToResponse(savedResp);

                return(ApiHelper.ConstructSuccessResponse(this.Negotiate, container, this.Context));
            });
Example #3
0
        /// <summary>
        /// Resolves and delivers a GET request on an abstract supertype.
        /// </summary>
        /// <param name="entity">The abstract entity.</param>
        /// <returns>The response with all concrete entities.</returns>
        private Negotiator ResolveAbstractGet(string entity)
        {
            var types    = EntityResolverMap.AbstractToConcreteMap[entity];
            var response = new ResponseContainer();

            var filterDictionary = new Dictionary <Type, QueryParameterContainer>();

            foreach (var type in types)
            {
                try
                {
                    var queryParams = this.ProcessQueryParameters(this.Request, type);
                    filterDictionary.Add(type, queryParams);
                }
                catch (Exception)
                {
                    return(ApiHelper.ConstructFailResponse(
                               this.Negotiate,
                               entity,
                               "The query parameters are badly formatted and cannot be parsed.",
                               this.Context,
                               HttpStatusCode.BadRequest));
                }
            }

            foreach (var type in types)
            {
                if (filterDictionary.Values.Any(x => x.IsFiltered) && !filterDictionary[type].IsFiltered)
                {
                    // if some typpe is filtered but this type is not, exclude it
                    continue;
                }

                var typeErrors = ApiHelper.GetTypeErrors(this.Negotiate, entity, type, out var attributes, this.Context);

                if (typeErrors != null)
                {
                    continue;
                }

                List <IEntityObject> resp;

                try
                {
                    resp =
                        ((IEnumerable <IEntityObject>)
                         type.GetMethod(
                             "Where",
                             BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy,
                             null,
                             new[]
                    {
                        typeof(List <IWhereQueryContainer>), typeof(int?), typeof(int?),
                        typeof(PropertyInfo), typeof(bool)
                    },
                             null)
                         .Invoke(
                             null,
                             new object[]
                    {
                        filterDictionary[type].FilterList, filterDictionary[type].Limit, filterDictionary[type].Offset,
                        filterDictionary[type].OrderProperty, filterDictionary[type].IsDescending
                    })).ToList();
                }
                catch (Exception e)
                {
                    return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
                }

                response.AddToResponse(resp);
            }

            return(ApiHelper.ConstructSuccessResponse(this.Negotiate, response, this.Context));
        }