Exemplo n.º 1
0
        public async Task <IActionResult> Delete(Guid id)
        {
            try
            {
                var serviceResult = await ResourceService.DeleteAsync(id);

                if (serviceResult.Resource == null)
                {
                    return(NoContent());
                }

                if (serviceResult.Errors.Count > 0)
                {
                    return(BadRequest(serviceResult));
                }

                return(Ok());
            }
            catch (Exception ex)
            {
                var result = new ResourceResult <EmployeeResource>();

                while (ex != null)
                {
                    result.Exceptions.Add(ex.Message);
                }

                return(BadRequest(result));
            }
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Post([FromBody] EmployeeResource resource)
        {
            try
            {
                // Create rescource
                var serviceResult = await ResourceService.InsertAsync(resource);

                // if return error message if needed
                if (serviceResult.Errors.Count > 0)
                {
                    return(BadRequest(serviceResult));
                }

                // On succes return url with id and newly created resource
                return(CreatedAtAction(nameof(Get), new { id = serviceResult.Resource.Id }, serviceResult.Resource));
            }
            catch (Exception ex)
            {
                var result = new ResourceResult <EmployeeResource>(resource);

                while (ex != null)
                {
                    result.Exceptions.Add(ex.Message);
                }

                return(BadRequest(result));
            }
        }
        public void UsesCustomIdInCollections()
        {
            var person = new Person(id: "abc", prefill: true)
            {
                Friends = new List <Person>
                {
                    new Person(id: "def", prefill: true),
                    new Person(id: "ghi", prefill: true),
                    new Person(id: "jkl", prefill: true),
                }
            };

            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = DefaultResource,
                Result   = person
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "abc").ToString()));

            _output.WriteLine(result.ToString());

            var ids      = result["data"]["relationships"]["friends"]["data"].Select(t => t.Value <string>("id"));
            var expected = person.Friends.Select(p => p.Identifier);

            Assert.Equal(expected, ids);
        }
        public void UsesCustomIdInUrls()
        {
            var person = Get.Person(id: "abc");
            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = DefaultResource,
                Result   = person
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "abc").ToString()));

            _output.WriteLine(result.ToString());

            var job     = result["data"]["relationships"]["job"]["links"];
            var friends = result["data"]["relationships"]["friends"]["links"];

            var self           = new Uri(result["links"]["self"].ToString()).AbsolutePath;
            var jobSelf        = new Uri(job["self"].ToString()).AbsolutePath;
            var jobRelated     = new Uri(job["related"].ToString()).AbsolutePath;
            var friendsSelf    = new Uri(friends["self"].ToString()).AbsolutePath;
            var friendsRelated = new Uri(friends["related"].ToString()).AbsolutePath;
            var included       = new Uri(result["included"][0]["links"]["self"].ToString()).AbsolutePath;

            Assert.Equal("/api/people/abc", self);
            Assert.Equal("/api/people/abc/relationships/employer/", jobSelf);
            Assert.Equal("/api/people/abc/employer/", jobRelated);
            Assert.Equal("/api/people/abc/relationships/friends/", friendsSelf);
            Assert.Equal("/api/people/abc/friends/", friendsRelated);
            Assert.Equal("/api/corporations/456/", included);
        }
Exemplo n.º 5
0
        public async Task <IActionResult> Edit(Guid id)
        {
            // Check if new or edit
            String url = apiUrl + ((id.IsNullOrEmpty()) ? "create" : $"{id}");

            using (var client = restClient.CreateClient(User))
            {
                using (var response = await client.GetAsync(url))
                {
                    var document = await response.Content.ReadAsStringAsync();

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        var demoDoc  = JsonConvert.SerializeObject(new EmployeeResource());
                        var resource = JsonConvert.DeserializeObject <EmployeeResource>(document);

                        var result = mapper.Map <EmployeeModel>(resource);

                        return(PartialView(nameof(Edit), result));
                    }

                    else
                    {
                        var result = new ResourceResult <EmployeeResource>();

                        if (response.StatusCode == HttpStatusCode.NotFound)
                        {
                            result.Errors.Add(new ValidationError($"Record with id {id} is not found"));
                        }

                        return(StatusCode(response.StatusCode.ToInt32(), result));
                    }
                }
            }
        }
        public void HandlesNullValues()
        {
            var person = new Person(id: "45");

            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = DefaultResource,
                Result   = person
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "45").ToString()));

            _output.WriteLine(result.ToString());

            var relationships = result["data"]["relationships"];
            var attributes    = result["data"]["attributes"];

            Assert.NotNull(attributes["first-name"]);
            Assert.NotNull(attributes["last-name"]);
            Assert.NotNull(attributes["age"]);

            Assert.Null(relationships["job"]["data"]);
            Assert.Null(relationships["friends"]["data"]);
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Edit(Int32 id)
        {
            String url = apiUrl + ((id == 0) ? "create" : $"{id}");

            using (var response = await apiClient.GetAsync(url))
            {
                var document = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var resource = JsonConvert.DeserializeObject <UploadedFileResource>(document);

                    var result = mapper.Map <UploadedFileModel>(resource);

                    return(PartialView(nameof(Edit), result));
                }

                else
                {
                    var result = new ResourceResult <UploadedFileResource>();

                    if (response.StatusCode == HttpStatusCode.NotFound)
                    {
                        result.Errors.Add(new ValidationError($"Record with id {id} is not found"));
                    }

                    return(StatusCode(response.StatusCode.ToInt32(), result));
                }
            }
        }
Exemplo n.º 8
0
        public ActionResult ScriptsCompacted()
        {
            ResourceResult result = new ResourceResult(JbstController.SupportScriptPath);

            result.Filename     = "jbst.min.js";
            result.IsAttachment = true;
            result.IsDebug      = false;
            return(result);
        }
Exemplo n.º 9
0
        public ResourceResult GetPrefab(string prefab)
        {
            ResourceResult result;

            if (!_map.TryGetValue(prefab, out result))
            {
                result       = new ResourceResult(_coroutineProvider, prefab);
                _map[prefab] = result;
            }

            return(result);
        }
Exemplo n.º 10
0
        public ResourceResult <T> Get <T>(string prefab) where T : UnityEngine.Object
        {
            ResourceResult result;

            if (!_map.TryGetValue(prefab, out result))
            {
                result       = new ResourceResult <T>(_coroutineProvider, prefab);
                _map[prefab] = result;
            }

            return((ResourceResult <T>)result);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Process the owin request.
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <returns></returns>
        public virtual async Task Invoke(IDictionary <string, object> environment)
        {
            var context = new OwinContext(environment);

            try
            {
                environment[FilesConfig.OwinKey] = _options;

                _options.Log.LogDebug("{0} for {1}{2}", context.Request.Method, context.Request.PathBase, context.Request.Path);

                ResourceResult test = _options.DataStore.GetResource(context, context.Request.Path);

                if (test.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    // TODO: handle query string part?
                    //var fullUrl = context.Request.Uri.ToString();
                    //if (resource.Resource != null && resource.Resource.ResourceType == ResourceType.Collection && !fullUrl.EndsWith("/", StringComparison.Ordinal))
                    //{
                    //    context.Response.Headers.Replace("Content-Location", fullUrl + "/");
                    //}

                    var            code = 0;
                    IMethodHandler handler;
                    if (Handlers.TryGetValue(context.Request.Method, out handler))
                    {
                        code = await handler.HandleAsync(test.Resource).ConfigureAwait(false);
                    }

                    if (code == 0)
                    {
                        await _next.Invoke(environment).ConfigureAwait(false);
                    }
                    else
                    {
                        context.Response.StatusCode = (int)code;
                    }
                }
                else
                {
                    context.Response.StatusCode = (int)test.StatusCode;
                }
            }
            catch (Exception ex)
            {
                _options.Log.LogError("FilesMiddleware.Invoke: " + ex.ToString());
                //context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                //return context.Response.WriteAsync(ex.Message);
                throw;
            }
        }
        public void ThrowsRightException()
        {
            var person = new PersonWithNoId();
            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = new CompanyResource(),
                Result   = person
            };

            Assert.Throws <JsonApiException>(() =>
            {
                target.Serialize(resourceResult, GetUri(id: "123").ToString());
            });
        }
        public void HandlesNullResources()
        {
            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = DefaultResource,
                Result   = null
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri().ToString()));

            _output.WriteLine(result.ToString());

            Assert.Equal(JTokenType.Null, result["data"].Type);
        }
        public void UsesTitle()
        {
            var company = Get.Company();
            var target  = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = new CompanyResource(),
                Result   = company
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri("/corporations", "456").ToString()));

            _output.WriteLine(result.ToString());

            Assert.Equal("corporation", result["data"]["type"]);
        }
        public void UsesSpecifiedPropertyId()
        {
            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = DefaultResource,
                Result   = DefaultObject
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "abc").ToString()));

            _output.WriteLine(result.ToString());

            var id = result["data"].Value <string>("id");

            Assert.Equal(DefaultObject.Identifier, id);
        }
        public void DocumentMustNotContainIncludedForEmptySet()
        {
            var people = new Person[0];

            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = DefaultResource,
                Result   = people
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri().ToString()));

            _output.WriteLine(result.ToString());

            Assert.Null(result["included"]);
        }
        public void DocumentMustContainAtLeastOneDataOrErrorOrMeta()
        {
            var people = new Person[] { };

            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = DefaultResource,
                Result   = people
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri().ToString()));

            _output.WriteLine(result.ToString());

            Assert.NotNull(result["data"]);
        }
        public void AttributesSufficient()
        {
            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = DefaultResource,
                Result   = DefaultObject
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "123").ToString()));

            _output.WriteLine(result.ToString());

            var attributes = result["data"]["attributes"];

            Assert.True(attributes["numberOfLegs"] == null);
            Assert.Equal(3, attributes.Count());
        }
        public void UsesDefaultPropertyId()
        {
            var data   = new PersonWithNoJob();
            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = new PersonWithDefaultIdResource(),
                Result   = data
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "123").ToString()));

            _output.WriteLine(result.ToString());

            var id = result["data"].Value <string>("id");

            Assert.Equal(data.Id, id);
        }
        public void SupportsGuidIds()
        {
            var guid = new GuidAsId();

            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = new PersonWithDefaultIdResource(),
                Result   = guid
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "123").ToString()));

            _output.WriteLine(result.ToString());

            Assert.NotNull(result["data"]["id"]);
            Assert.Equal(guid.Id, Guid.Parse(result["data"]["id"].ToString()));
        }
        public void AttributesComplete()
        {
            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = DefaultResource,
                Result   = DefaultObject
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "123").ToString()));

            _output.WriteLine(result.ToString());

            var attributes = result["data"]["attributes"];

            Assert.Equal(DefaultObject.FirstName, attributes.Value <string>("first-name"));
            Assert.Equal(DefaultObject.LastName, attributes.Value <string>("last-name"));
            Assert.Equal(DefaultObject.Age, attributes.Value <int>("age"));
        }
        public void SerializeOnlyWhatYouHave()
        {
            var company = new GuidAsId();

            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = new CompanyResource(),
                Result   = company
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "123").ToString()));

            _output.WriteLine(result.ToString());

            Assert.Null(result["data"]["attributes"]["name"]);
            Assert.Null(result["data"]["attributes"]["location"]);
            Assert.Null(result["data"]["attributes"]["number-of-employees"]);
        }
        public void UsesCustomIdInRelationships()
        {
            var person   = new PersonWithDifferentId(id: "abc", prefill: true);
            var resource = new PersonWithDifferentIdResource();

            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = resource,
                Result   = person
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "abc").ToString()));

            _output.WriteLine(result.ToString());

            var id = result["data"]["relationships"]["job"]["data"].Value <string>("id");

            Assert.Equal(person.Job.CompanyId, id);
        }
        public void SerializesEnumerables()
        {
            var people = Get.People(5);

            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = DefaultResource,
                Result   = people
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri().ToString()));

            _output.WriteLine(result.ToString());

            var included = result["included"] as JArray;
            var jobLinks = (result["data"] as JArray)?[0]["relationships"]["job"]["links"];

            Assert.Equal(1, included?.Count);
            Assert.Equal("/api/people/0/employer/", new Uri(jobLinks?["related"]?.ToString()).AbsolutePath);
        }
Exemplo n.º 25
0
        public async Task <IActionResult> Put([FromBody] EmployeeResource resource)
        {
            try
            {
                var currentResource = await ResourceService.FindAsync(resource.Id);

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

                var serviceResult = await ResourceService.UpdateAsync(resource);

                if (serviceResult.Errors.Count > 0)
                {
                    return(BadRequest(serviceResult));
                }

                return(Ok(serviceResult.Resource));
            }
            catch (Exception ex)
            {
                var result = new ResourceResult <EmployeeResource>(resource);

                while (ex != null)
                {
                    result.Exceptions.Add(ex.Message);

                    if (ex is ConcurrencyException)
                    {
                        return(StatusCode(HttpStatusCode.Conflict.ToInt32(), result));
                    }

                    ex = ex.InnerException;
                }

                return(BadRequest(result));
            }
        }
        public void SerializesRelationshipData()
        {
            var person = new PersonWithNoJob();
            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = new PersonWithDefaultIdResource(),
                Result   = person
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "123").ToString()));

            _output.WriteLine(result.ToString());

            var relationships = result["data"]["relationships"];
            var job           = relationships["job"];
            var friends       = relationships["friends"];

            Assert.Null(job["data"]);
            Assert.NotNull(friends["data"]);
        }
Exemplo n.º 27
0
        private JObject BuildJsonResult(ResourceResult resourceResult, string requestUri)
        {
            var serializationContext = new SerializationContext
            {
                Object           = resourceResult.Result,
                Resource         = resourceResult.Resource,
                IncludedSections = new JArray(),
                BaseUrl          = requestUri,
                QueryContext     = resourceResult.QueryContext
            };

            if (serializationContext.Object == null)
            {
                return(SerializeNull(serializationContext));
            }

            var objectJson = JToken.FromObject(serializationContext.Object, _serializer);

            serializationContext.IsCollection = objectJson is JArray;

            var result = new JObject
            {
                ["data"]  = SerializeArrayOrObject(serializationContext, objectJson, SerializeData),
                ["links"] = new JObject
                {
                    ["self"] = new JValue(serializationContext.BaseUrl)
                }

                ["links"] = CreateTopLevelLinks(serializationContext, serializationContext.IsCollection ? objectJson.Count() : 0)
            };

            if (serializationContext.IncludedSections.Count > 0)
            {
                result["included"] = serializationContext.IncludedSections;
            }

            return(result);
        }
        public void IncludesRelationshipData()
        {
            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = DefaultResource,
                Result   = DefaultObject
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "123").ToString()));

            _output.WriteLine(result.ToString());

            var included = result["included"] as JArray;
            var job      = included?[0];

            Assert.Equal(1, included?.Count);
            Assert.Equal("http://example.com/api/corporations/456/", included?[0]?["links"]?["self"]?.ToString());

            Assert.Equal(DefaultObject.Job.Id, job?["id"]);
            Assert.NotNull(job?["attributes"]);
        }
Exemplo n.º 29
0
        private JObject BuildJsonResult(ResourceResult resourceResult, string requestUri)
        {
            var serializationContext = new SerializationContext
            {
                Object = resourceResult.Result,
                Resource = resourceResult.Resource,
                IncludedSections = new JArray(),
                BaseUrl = requestUri,
                QueryContext = resourceResult.QueryContext
            };

            if (serializationContext.Object == null)
            {
                return SerializeNull(serializationContext);
            }

            var objectJson = JToken.FromObject(serializationContext.Object, _serializer);
            serializationContext.IsCollection = objectJson is JArray;

            var result = new JObject
            {
                ["data"] = SerializeArrayOrObject(serializationContext, objectJson, SerializeData),
                ["links"] = new JObject
                {
                    ["self"] = new JValue(serializationContext.BaseUrl)
                }

                ["links"] = CreateTopLevelLinks(serializationContext, serializationContext.IsCollection ? objectJson.Count() : 0)
            };

            if (serializationContext.IncludedSections.Count > 0)
            {
                result["included"] = serializationContext.IncludedSections;
            }

            return result;
        }
        public void HandlesRecursiveProperties()
        {
            var firstModel  = new Recursion.FirstModel();
            var secondModel = new Recursion.SecondModel();

            firstModel.Model  = secondModel;
            secondModel.Model = firstModel;

            var target = new ResourceSerializer(urlBuilder: new DefaultUrlPathBuilder("/api"));

            var resourceResult = new ResourceResult
            {
                Resource = new Recursion.Resource(),
                Result   = firstModel
            };

            var result = JToken.Parse(target.Serialize(resourceResult, GetUri(id: "123").ToString()));

            _output.WriteLine(result.ToString());

            var id = result["data"].Value <string>("id");

            Assert.Equal(firstModel.Id, id);
        }
Exemplo n.º 31
0
 public HttpCreatedResult(string location, ResourceResult inner) : base(inner)
 {
     _location = location;
 }
Exemplo n.º 32
0
 public ETaggedResult(string value, ResourceResult inner) : base(inner)
 {
     _value = value;
 }
Exemplo n.º 33
0
 protected BeforeFilterResult(ResourceResult inner)
 {
     _inner = inner;
 }
Exemplo n.º 34
0
 public HttpCreatedResult(string location, ResourceResult inner) : base(inner)
 {
     _location = location;
 }
Exemplo n.º 35
0
        public string Serialize(ResourceResult resourceResult, string requestUri)
        {
            var processedResult = BuildJsonResult(resourceResult, requestUri);

            return processedResult.ToString(Formatting.None, _config.JsonConverters.ToArray());
        }