Esempio n. 1
0
        public HttpResponseMessage GetText(string type, [FromBody] string inputText)
        {
            // if string is empty
            if (string.IsNullOrWhiteSpace(inputText))
            {
                return Request.CreateResponse(HttpStatusCode.NoContent, "Empty string");
            }
            // save to file
            Func.SaveToFile(inputText);

            // parse into revalent models
            Text text = Parser.ParseInputText(inputText);

            // get formatter from type
            var formatter = FormatFactory.GetFormatter(type);

            // create respons content
            var content = new ObjectContent<Text>(
                text,								// What we are serializing
                formatter//,						// The media formatter
                //mediaTypeHeaderValue.MediaType	// The MIME (multimedia internet message exchange )type
                );

            return new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content = content
            };
        }
Esempio n. 2
0
 public static void ContainsFormatters(ObjectContent objectContent, IEnumerable<MediaTypeFormatter> formatters)
 {
     Assert.IsNotNull(objectContent, "objectContent cannot be null.");
     Assert.IsNotNull(formatters, "Test error: formatters must be specified.");
     Assert.IsNotNull(objectContent.Formatters, "Formatters property cannot be null.");
     CollectionAssert.IsSubsetOf(formatters.ToList(), objectContent.Formatters, "Formatters did not include all expected formatters.");
 }
Esempio n. 3
0
        private void ArrayOfBoolsSerializesAsOData(string expectedContent, bool json)
        {
            ObjectContent<bool[]> content = new ObjectContent<bool[]>(new bool[] { true, false, true, false },
                _formatter, GetMediaType(json));

            AssertEqual(json, expectedContent, content.ReadAsStringAsync().Result);
        }
Esempio n. 4
0
        private void ArrayOfIntsSerializesAsOData(string expectedContent, bool json)
        {
            ObjectContent<int[]> content = new ObjectContent<int[]>(new int[] { 10, 20, 30, 40, 50 }, _formatter,
                GetMediaType(json));

            AssertEqual(json, expectedContent, content.ReadAsStringAsync().Result);
        }
Esempio n. 5
0
        private void IEnumerableOfEntityTypeSerializesAsODataFeed(string expectedContent, bool json)
        {
            ODataMediaTypeFormatter formatter = CreateFormatter();

            IEnumerable<Employee> collectionOfPerson = new Collection<Employee>() 
            {
                (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee, 0),
                (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee, 1),
            };

            ObjectContent<IEnumerable<Employee>> content = new ObjectContent<IEnumerable<Employee>>(collectionOfPerson,
                formatter, json ? ODataMediaTypes.ApplicationJsonODataMinimalMetadata :
                ODataMediaTypes.ApplicationAtomXmlTypeFeed);

            string actualContent = content.ReadAsStringAsync().Result;

            if (json)
            {
                JsonAssert.Equal(expectedContent, actualContent);
            }
            else
            {
                RegexReplacement replaceUpdateTime = new RegexReplacement(
                    "<updated>*.*</updated>", "<updated>UpdatedTime</updated>");
                Assert.Xml.Equal(expectedContent, actualContent, replaceUpdateTime);
            }
        }
        public async void FormatterShouldBeAbleToDeserializeArticle()
        {
            var content = new ObjectContent<Article>(_article, _formatter);

            var deserializedItem = await content.ReadAsAsync<Article>(new[] { _formatter });

            Assert.That(_article, Is.SameAs(deserializedItem));
        }
        public void ContentHeadersAreAddedForJsonMediaType()
        {
            HttpContent content = new ObjectContent<Person[]>(new Person[] { new Person(0, new ReferenceDepthContext(7)) }, _formatter, "application/json");
            content.LoadIntoBufferAsync().Wait();

            Assert.Http.Contains(content.Headers, "DataServiceVersion", "3.0;");
            Assert.Equal(content.Headers.ContentType.MediaType, "application/json");
        }
        public void ContentHeadersAreAddedForXmlMediaType()
        {
            ObjectContent<IEnumerable<Person>> content = new ObjectContent<IEnumerable<Person>>(new Person[] { new Person(0, new ReferenceDepthContext(7)) }, _formatter);
            content.LoadIntoBufferAsync().Wait();

            Assert.Http.Contains(content.Headers, "DataServiceVersion", "3.0;");
            Assert.Http.Contains(content.Headers, "Content-Type", "application/xml; charset=utf-8");
        }
        private void ComplexTypeSerializesAsOData(string expectedContent, bool json)
        {
            ObjectContent<Person> content = new ObjectContent<Person>(new Person(0, new ReferenceDepthContext(7)),
                _formatter, CollectionTest.GetMediaType(json));


            CollectionTest.AssertEqual(json, expectedContent, content.ReadAsStringAsync().Result);
        }
Esempio n. 10
0
        public void EntityTypeSerializesAsODataEntry()
        {
            ODataMediaTypeFormatter formatter = CreateFormatter();
            Employee employee = (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee);
            ObjectContent<Employee> content = new ObjectContent<Employee>(employee, formatter);

            RegexReplacement replaceUpdateTime = new RegexReplacement("<updated>*.*</updated>", "<updated>UpdatedTime</updated>");
            Assert.Xml.Equal(BaselineResource.TestEntityTypeBasic, content.ReadAsStringAsync().Result, regexReplacements: replaceUpdateTime);
        }
 public void CanConvertFromStringReturnsFalseForObjectContent()
 {
     ObjectContent objectContent = new ObjectContent<int>(5);
     HttpParameterValueConverter converter = HttpParameterValueConverter.GetValueConverter(objectContent.GetType());
     if (converter.CanConvertFromString)
     {
         Assert.Fail(string.Format("CanConvertFromString was wrong for ObjectContent."));
     }
 }
        public void render_template_with_embedded_layout()
        {
            var view = new View("Test2", new { Name = "foo" });
            var content = new ObjectContent<View>(view, _formatter);

            var output = content.ReadAsStringAsync().Result;

            Assert.AreEqual("<html>Hello foo! Welcome to Razor!</html>", output);
        }
Esempio n. 13
0
        public void ArrayOfIntsSerializesAsOData()
        {
            // Arrange
            ObjectContent<int[]> content = new ObjectContent<int[]>(new int[] { 10, 20, 30, 40, 50 }, _formatter,
                ODataMediaTypes.ApplicationJsonODataMinimalMetadata);

            // Act & Assert
            JsonAssert.Equal(Resources.ArrayOfInt32, content.ReadAsStringAsync().Result);
        }
        public void render_simple_template()
        {
            var view = new View("Test1", new {Name = "foo"});
            var content = new ObjectContent<View>(view, _formatter);

            var output = content.ReadAsStringAsync().Result;

            Assert.AreEqual("Hello foo! Welcome to Razor!", output);
        }
        public void ComplexTypeSerializesAsOData()
        {
            // Arrange
            ObjectContent<Person> content = new ObjectContent<Person>(new Person(0, new ReferenceDepthContext(7)),
                _formatter, ODataMediaTypes.ApplicationJsonODataMinimalMetadata);

            // Act & Assert
            JsonAssert.Equal(Resources.PersonComplexType, content.ReadAsStringAsync().Result);
        }
Esempio n. 16
0
        public void ContentHeadersAreAddedForJsonMediaType()
        {
            ODataMediaTypeFormatter formatter = new ODataMediaTypeFormatter(GetSampleModel()) { Request = GetSampleRequest() };
            HttpContent content = new ObjectContent<Employee>(new Employee(0, new ReferenceDepthContext(7)), formatter, "application/json");
            content.LoadIntoBufferAsync().Wait();

            Assert.Http.Contains(content.Headers, "DataServiceVersion", "3.0;");
            Assert.Http.Contains(content.Headers, "Content-Type", "application/json; odata=verbose; charset=utf-8");
        }
Esempio n. 17
0
        public void ArrayOfBooleansSerializesAsOData()
        {
            // Arrange
            ObjectContent<bool[]> content = new ObjectContent<bool[]>(new bool[] { true, false, true, false },
                _formatter, ODataMediaTypes.ApplicationJsonODataMinimalMetadata);

            // Act & Assert
            JsonAssert.Equal(Resources.ArrayOfBoolean, content.ReadAsStringAsync().Result);
        }
 public void ApplySecurityToResponseData(ObjectContent responseObjectContent)
 {
     var removeSensitiveData = !_userSession.IsInRole(Constants.RoleNames.SeniorWorker);
     if (removeSensitiveData)
     {
         _log.DebugFormat("Applying security data masking for user {0}", _userSession.Username);
     }
     ((Task) responseObjectContent.Value).SetShouldSerializeAssignees(!removeSensitiveData);
 }
 public void ApplySecurityToResponseData(ObjectContent responseObjectContent)
 {
     var maskData = !_userSession.IsInRole(Constants.RoleNames.SeniorWorker);
     if (maskData)
     {
         _log.DebugFormat($"Applying security data masking for user {_userSession.Username}");
     }
     ((PagedDataInquiryResponse<Task>) responseObjectContent.Value).Items
         .ForEach(x => x.SetShouldSerializeAssignees(!maskData));
 }
Esempio n. 20
0
        public void ContentHeadersAreAddedForXmlMediaType()
        {
            ODataMediaTypeFormatter formatter = new ODataMediaTypeFormatter();

            ObjectContent<Employee> content = new ObjectContent<Employee>(new Employee(0, new ReferenceDepthContext(7)), formatter);
            content.LoadIntoBufferAsync().Wait();

            Assert.Http.Contains(content.Headers, "DataServiceVersion", "3.0;");
            Assert.Http.Contains(content.Headers, "Content-Type", "application/atom+xml; type=entry");
        }
Esempio n. 21
0
        public void ContentHeadersAreAddedForJsonMediaType()
        {
            ODataMediaTypeFormatter formatter = new ODataMediaTypeFormatter();

            HttpContent content = new ObjectContent<IEnumerable<Employee>>(new Employee[] { new Employee(0, new ReferenceDepthContext(7)) }, formatter, "application/json");
            content.LoadIntoBufferAsync().Wait();

            Assert.Http.Contains(content.Headers, "DataServiceVersion", "3.0;");
            Assert.Equal(content.Headers.ContentType.MediaType, "application/json");
        }
Esempio n. 22
0
        public void ContentHeadersAreAddedForXmlMediaType()
        {
            ODataMediaTypeFormatter formatter = new ODataMediaTypeFormatter(GetSampleModel()) { Request = GetSampleRequest() };

            ObjectContent<IEnumerable<Employee>> content = new ObjectContent<IEnumerable<Employee>>(new Employee[] { new Employee(0, new ReferenceDepthContext(7)) }, formatter);
            content.LoadIntoBufferAsync().Wait();

            Assert.Http.Contains(content.Headers, "DataServiceVersion", "3.0;");
            Assert.Http.Contains(content.Headers, "Content-Type", "application/atom+xml; type=feed; charset=utf-8");
        }
Esempio n. 23
0
        public void EntityTypeSerializesAsODataEntry()
        {
            // Arrange
            ODataMediaTypeFormatter formatter = CreateFormatter();
            Employee employee = (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee);
            ObjectContent<Employee> content = new ObjectContent<Employee>(employee, formatter,
                ODataMediaTypes.ApplicationJsonODataMinimalMetadata);

            // Act & Assert
            JsonAssert.Equal(Resources.EmployeeEntry, content.ReadAsStringAsync().Result);
        }
        public void render_template_with_specified_resolver()
        {
            var resolver = new EmbeddedResolver(this.GetType());
            var formatter = new HtmlMediaTypeViewFormatter(null, new RazorViewLocator(), new RazorViewParser(resolver));
            var view = new View("Test2", new { Name = "foo" });
            var content = new ObjectContent<View>(view, formatter);

            var output = content.ReadAsStringAsync().Result;

            Assert.AreEqual("<html>Hello foo! Welcome to Razor!</html>", output);
        }
        private static async Task<HttpContent> ToStreamContent(ObjectContent content)
        {
            Stream stream = await content.ReadAsStreamAsync();
            StreamContent streamContent = new StreamContent(stream);
            foreach (var header in content.Headers)
            {
                streamContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            return streamContent;
        }
Esempio n. 26
0
        public void CollectionOfObjectsSerializesAsOData()
        {
            Collection<object> collectionOfObjects = new Collection<object>();
            collectionOfObjects.Add(1);
            collectionOfObjects.Add("Frank");
            collectionOfObjects.Add(TypeInitializer.GetInstance(SupportedTypes.Person, 2));
            collectionOfObjects.Add(TypeInitializer.GetInstance(SupportedTypes.Employee, 3));

            ObjectContent<Collection<object>> content = new ObjectContent<Collection<object>>(collectionOfObjects, _formatter);

            Assert.Throws<ODataException>(() => content.ReadAsStringAsync().Result);
        }
Esempio n. 27
0
        public void ListOfStringsSerializesAsOData()
        {
            List<string> listOfStrings = new List<string>();
            listOfStrings.Add("Frank");
            listOfStrings.Add("Steve");
            listOfStrings.Add("Tom");
            listOfStrings.Add("Chandler");

            ObjectContent<List<string>> content = new ObjectContent<List<string>>(listOfStrings, _formatter);

            Assert.Xml.Equal(BaselineResource.TestListOfStrings, content.ReadAsStringAsync().Result);
        }
Esempio n. 28
0
        public void CollectionOfComplexTypeSerializesAsOData()
        {
            IEnumerable<Person> collectionOfPerson = new Collection<Person>() 
            {
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 0),
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 1),
                (Person)TypeInitializer.GetInstance(SupportedTypes.Person, 2)
            };

            ObjectContent<IEnumerable<Person>> content = new ObjectContent<IEnumerable<Person>>(collectionOfPerson, _formatter);

            Assert.Xml.Equal(BaselineResource.TestCollectionOfPerson, content.ReadAsStringAsync().Result);
        }
 static void Main(string[] args)
 {
     var client = new HttpClient(new StubMessageHandler());
     dynamic json = new JsonObject();
     json.prop1 = "value1";
     json.prop2 = "value2";
     json.cprop3 = new JsonObject();
     json.cprop3.prop1 = "inner value1";
     json.cprop3.prop2 = "inner value2";
     json.aprop4 = new JsonArray() {"abc"};
     
     var cont = new ObjectContent<JsonValue>(json,"application/json");
     client.PostAsync("http://www.example.com",cont).Wait();
 }
Esempio n. 30
0
        public void IEnumerableOfEntityTypeSerializesAsODataFeed()
        {
            ODataMediaTypeFormatter formatter = new ODataMediaTypeFormatter(GetSampleModel()) { Request = GetSampleRequest() };

            IEnumerable<Employee> collectionOfPerson = new Collection<Employee>() 
            {
                (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee, 0),
                (Employee)TypeInitializer.GetInstance(SupportedTypes.Employee, 1),
            };

            ObjectContent<IEnumerable<Employee>> content = new ObjectContent<IEnumerable<Employee>>(collectionOfPerson, formatter);

            RegexReplacement replaceUpdateTime = new RegexReplacement("<updated>*.*</updated>", "<updated>UpdatedTime</updated>");
            Assert.Xml.Equal(BaselineResource.TestFeedOfEmployee, content.ReadAsStringAsync().Result, regexReplacements: replaceUpdateTime);
        }
Esempio n. 31
0
        /// <summary>
        /// Called when the action is executed.
        /// </summary>
        /// <param name="actionExecutedContext">The action executed context.</param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Response == null)
            {
                return;
            }

            if (!actionExecutedContext.Response.IsSuccessStatusCode)
            {
                return;
            }

            object responseObject;

            if (!actionExecutedContext.Response.TryGetContentValue(out responseObject))
            {
                return;
            }

            var dQuery = ((dynamic)responseObject);

            if (dQuery.GetType().IsInstanceOfType(typeof(IQueryable)))
            {
                return;
            }

            var elementType = TypeFns.GetElementType(responseObject.GetType());

            NameValueCollection querystringParams =
                HttpUtility.ParseQueryString(actionExecutedContext.Request.RequestUri.Query);

            string filterQueryString = querystringParams["$filter"];

            if (!string.IsNullOrWhiteSpace(filterQueryString))
            {
                var func = BuildFilterFunc(filterQueryString, elementType);
                dQuery = func(dQuery as IQueryable);
            }

            int?   inlineCount       = null;
            string inlinecountString = querystringParams["$inlinecount"];

            if (!string.IsNullOrWhiteSpace(inlinecountString))
            {
                if (inlinecountString == "allpages")
                {
                    if (dQuery is IQueryable)
                    {
                        inlineCount = Queryable.Count(dQuery);
                    }
                }
            }


            string orderByQueryString = querystringParams["$orderby"];

            if (!string.IsNullOrWhiteSpace(orderByQueryString))
            {
                var orderByClauses = orderByQueryString.Split(',').ToList();
                var isThenBy       = false;
                orderByClauses.ForEach(obc => {
                    var func = BuildOrderByFunc(isThenBy, elementType, obc);
                    dQuery   = func(dQuery as IQueryable);
                    isThenBy = true;
                });
            }

            string skipQueryString = querystringParams["$skip"];

            if (!string.IsNullOrWhiteSpace(skipQueryString))
            {
                var count  = int.Parse(skipQueryString);
                var method = TypeFns.GetMethodByExample((IQueryable <String> q) => Queryable.Skip <String>(q, 999), elementType);
                var func   = BuildIQueryableFunc(elementType, method, count);
                dQuery = func(dQuery as IQueryable);
            }

            string topQueryString = querystringParams["$top"];

            if (!string.IsNullOrWhiteSpace(topQueryString))
            {
                var count  = int.Parse(topQueryString);
                var method = TypeFns.GetMethodByExample((IQueryable <String> q) => Queryable.Take <String>(q, 999), elementType);
                var func   = BuildIQueryableFunc(elementType, method, count);
                dQuery = func(dQuery as IQueryable);
            }

            string selectQueryString = querystringParams["$select"];

            if (!string.IsNullOrWhiteSpace(selectQueryString))
            {
                var selectClauses = selectQueryString.Split(',').Select(sc => sc.Replace('/', '.')).ToList();
                var func          = BuildSelectFunc(elementType, selectClauses);
                dQuery = func(dQuery as IQueryable);
            }

            string expandsQueryString = querystringParams["$expand"];

            if (!string.IsNullOrWhiteSpace(expandsQueryString))
            {
                if (!string.IsNullOrWhiteSpace(selectQueryString))
                {
                    throw new Exception("Use of both 'expand' and 'select' in the same query is not currently supported");
                }
                expandsQueryString.Split(',').Select(s => s.Trim()).ToList().ForEach(expand => {
                    dQuery = dQuery.Include(expand.Replace('/', '.'));
                });
            }

            // execute any DbQueries here, so that any exceptions thrown can be properly returned.
            // if we wait to have the query executed within the serializer, some exceptions will not
            // serialize properly.
            Object rQuery;

            if (dQuery is IQueryable)
            {
                rQuery = System.Linq.Enumerable.ToList((dynamic)dQuery);
            }
            else
            {
                rQuery = dQuery;
            }

            var formatter = ((dynamic)actionExecutedContext.Response.Content).Formatter;
            var oc        = new System.Net.Http.ObjectContent(rQuery.GetType(), rQuery, formatter);

            actionExecutedContext.Response.Content = oc;

            if (inlineCount.HasValue)
            {
                actionExecutedContext.Response.Headers.Add("X-InlineCount", inlineCount.ToString());
            }
        }