/// <summary>
        /// Gets a single model.
        /// </summary>
        /// <param name="id">Id of the entity.</param>
        public virtual async Task <HttpResponseMessage> Get(int?id)
        {
            //nullable needed incase something other than an int is passed.
            if (!id.HasValue)
            {
                return(await this.NotFound().ExecuteAsync(CancellationToken.None));
            }

            //var acceptTypes = this.GetAcceptContentTypes();

            TDTO dto;

            using (var context = LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()))
            {
                var model = context.GetSingle <TModel>(id.Value);

                //if (acceptTypes.Any() && !acceptTypes.Contains(MediaTypeValue.ANY) && !acceptTypes.Contains(MediaTypeValue.JSON))
                //{
                // return await this.PerformContentNegotiation(model, acceptTypes);
                //}

                //default functionality is to return the dto.
                dto = this.Factory.ToDTO(model);
            }

            return(await this.Ok(dto).ExecuteAsync(CancellationToken.None));
        }
        /// <summary>
        /// Deletes the given model.
        /// </summary>
        /// <param name="id">Id of the model.</param>
        public virtual IHttpActionResult Delete(int?id)
        {
            //nullable needed incase something other than an int is passed.
            if (!id.HasValue)
            {
                return(this.NotFound());
            }

            using (var context = LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()))
            {
                context.Delete <TModel>(id.Value);
            }

            return(this.OkNoContent());
        }
        protected virtual IQueryable <TModel> GetCollection(ODataQueryOptions <TModel> queryOptions)
        {
            using (var context = LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()))
            {
                var collection = context.GetCollection <TModel>();

                this.GetLogger().AppendLine("OData ApplyTo Started");

                var sw = Stopwatch.StartNew();

                collection = (IQueryable <TModel>)queryOptions.ApplyTo(collection, new ODataQuerySettings {
                    PageSize = WebApiConfig.PageSize
                });

                sw.Stop();
                this.GetLogger().AppendLine(string.Format("OData ApplyTo Done: {0} ms", sw.ElapsedMilliseconds));

                return(collection);
            }
        }
        /// <summary>
        /// Overriders must call this.Init() and run through permission checks and fire all the events.
        /// Do not call base. Typically only overridden to completely disable this method by using [NonAction] and then implementing your own Post()
        /// </summary>
        /// <param name="postedDto"></param>
        /// <returns></returns>
        public virtual IHttpActionResult Post(TDTO postedDto)
        {
            if (postedDto == null)
            {
                return(this.BadRequest("Invalid DTO."));
            }

            TModel model;

            try
            {
                model = this.Factory.FromDTO(postedDto);
            }
            catch (Exception ex)
            {
                return(this.BadRequest(ex.Message));
            }

            using (var context = LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()))
            {
                model = context.Create(model);
                return(this.Created(this.GetLocationUri(model), this.Factory.ToDTO(model)));
            }
        }
        /// <summary>
        /// Patches a model with the given changes.
        /// </summary>
        /// <param name="id">Id of the model.</param>
        /// <param name="json">Json object of the changes. Needs to be a single object with properties of base data types.</param>
        /// <returns></returns>
        public virtual IHttpActionResult Patch(int?id, JObject json)
        {
            //nullable needed incase something other than an int is passed.
            if (!id.HasValue)
            {
                return(this.NotFound());
            }

            if (json == null)
            {
                return(this.BadRequest("Invalid JSON."));
            }

            using (var context = LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()))
            {
                var userId = context.GetCurrentUser().Id;

                var dataInjectors = new List <IDataInjectable>
                {
                    new MyUserIdInjector(userId),
                    new UtcNowInjector()
                };

                var allProperties = typeof(TModel).GetProperties().Where(x => x.CanWrite).ToList();

                var validationErrors = new StringBuilder();

                var delta = new Dictionary <string, object>();

                var modelFound = context.Set <TModel>().FirstOrDefault(x => x.Id == id);
                if (modelFound == null)
                {
                    // CMDLogger.LogBusinessException("Model ID not found : " + id, json, string.Empty);
                }
                foreach (var o in json)
                {
                    var propInfo = allProperties.FirstOrDefault(x => String.Equals(x.Name, o.Key, StringComparison.CurrentCultureIgnoreCase));
                    if (null == propInfo)
                    {
                        continue;
                    }

                    var type = propInfo.PropertyType;

                    var injected = false;
                    foreach (var injectable in dataInjectors)
                    {
                        object tmp;

                        if (!injectable.TryParseObject(type, o.Value.ToString(), out tmp))
                        {
                            continue;
                        }

                        delta.Add(propInfo.Name, tmp);
                        injected = true;
                        break;
                    }

                    if (injected)
                    {
                        continue;
                    }

                    try
                    {
                        delta.Add(propInfo.Name, o.Value.ToObject(type));
                    }
                    catch
                    {
                        validationErrors.AppendFormat("Invalid data for: {0}", o.Key);
                        validationErrors.AppendLine();
                    }
                }

                if (json.Count != delta.Count)
                {
                    validationErrors.AppendLine("Invalid properties.");
                }

                if (validationErrors.Length > 0)
                {
                    return(this.BadRequest(validationErrors.ToString().Trim()));
                }
                var modelupdated = context.Update <TModel>(id.Value, delta);
                return(this.Ok(this.Factory.ToDTO(modelupdated)));
            }
        }
Beispiel #6
0
 public LuckIndiaDBContext GetDatabaseContext()
 {
     return(LuckIndiaDBContext.GetContextWithAccessToken(this.GetAccessToken(), this.GetLogger()));
 }