public static HttpResponseMessage CreateResponse()
        {
            var content = new ObjectContent<ExampleEntityBody>(EntityBody, new[] {ExampleMediaType.Instance});
            content.Headers.ContentType = ExampleMediaType.ContentType;

            return new HttpResponseMessage {Content = content};
        }
        public HttpResponseMessage GetFoo()
        {
            var content = new ObjectContent<string>("woof", "text/plain", new[] { new PlainTextFormatter() });  // including formatters here doesn't actually help!
                var response = new HttpResponseMessage { Content = content };

                return response;
        }
        public void WhenInvokedContentHeadersShouldBeSetCorrectly()
        {
            var item = new Item { Id = 1, Name = "Filip" };
            var content = new ObjectContent<Item>(item, new ProtoBufFormatter());

            Assert.Equal("application/x-protobuf", content.Headers.ContentType.MediaType);
        }
 private static HttpResponseMessage BuildContent(IEnumerable<string> messages)
 {
     var exceptionMessage = new ExceptionResponse { Messages = messages };
     var formatter = new JsonMediaTypeFormatter();
     var content = new ObjectContent<ExceptionResponse>(exceptionMessage, formatter, "application/json");
     return new HttpResponseMessage { Content = content };
 }
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            if (!actionExecutedContext.Response.IsSuccessStatusCode)
            {
                var contentObject = actionExecutedContext.Response.Content as ObjectContent;
                if (contentObject != null)
                {
                    var modelState = contentObject.Value as ModelStateDictionary;
                    if (modelState != null)
                    {
                        var errors =
                            (from item in modelState
                            from value in item.Value.Errors
                            select value.ErrorMessage).ToArray();

                        var configuration = actionExecutedContext.Request.GetConfiguration();
                        var contentNegotiator = configuration.Services.GetContentNegotiator();
                        var formatters = configuration.Formatters;
                        var result = contentNegotiator.Negotiate(errors.GetType(), actionExecutedContext.Request, formatters);
                        var content = new ObjectContent(errors.GetType(), errors, result.Formatter, result.MediaType.MediaType);
                        actionExecutedContext.Response.Content = content;
                    }
                }
            }
        }
 public ObjectLayerContent(XmlNode node, LevelContent level) 
     : base(node)
 {
     // Construct xpath query for all available objects.
     string[] objectNames = (from x in level.Project.Objects select x.Name).ToArray<string>();
     string xpath = string.Join("|", objectNames);
     foreach (XmlNode objectNode in node.SelectNodes(xpath))
     {
         ObjectTemplateContent objTemplate = level.Project.Objects.First<ObjectTemplateContent>((x) => { return x.Name.Equals(objectNode.Name); });
         if (objTemplate != null)
         {
             ObjectContent obj = new ObjectContent(objectNode, objTemplate);
             foreach (ValueTemplateContent valueContent in objTemplate.Values)
             {
                 XmlAttribute attribute = null;
                 if ((attribute = objectNode.Attributes[valueContent.Name]) != null)
                 {
                     if (valueContent is BooleanValueTemplateContent)
                         obj.Values.Add(new BooleanValueContent(valueContent.Name, bool.Parse(attribute.Value)));
                     else if (valueContent is IntegerValueTemplateContent)
                         obj.Values.Add(new IntegerValueContent(valueContent.Name,
                             int.Parse(attribute.Value, CultureInfo.InvariantCulture)));
                     else if (valueContent is NumberValueTemplateContent)
                         obj.Values.Add(new NumberValueContent(valueContent.Name,
                             float.Parse(attribute.Value, CultureInfo.InvariantCulture)));
                     else if (valueContent is StringValueTemplateContent)
                         obj.Values.Add(new StringValueContent(valueContent.Name, attribute.Value));
                 }
             }
             foreach (XmlNode nodeNode in objectNode.SelectNodes("node"))
                 obj.Nodes.Add(new NodeContent(nodeNode));
             this.Objects.Add(obj);
         }
     }
 }
        public HttpContent CreateFormData(HttpResponseMessage previousResponse, ApplicationStateVariables stateVariables, IClientCapabilities clientCapabilities)
        {
            var content = new ObjectContent(typeof(object), stateVariables.Get<object>(key), new[] { clientCapabilities.GetMediaTypeFormatter(contentType) });
            content.Headers.ContentType = contentType;

            return content;
        }
        public void TestValidateResponse_ServerReturnsNfieldErrorCodeAndMessage_ThrowsNfieldErrorExceptionWithErrorCodeAndMessage()
        {
            // Arrange
            const HttpStatusCode httpStatusCode = HttpStatusCode.NotFound;
            const NfieldErrorCode nfieldErrorCode = NfieldErrorCode.ArgumentIsNull;
            const string message = "Message #1";

            var serverResponse = new HttpResponseMessage(httpStatusCode);
            var httpErrorMock = new Dictionary<string, object>()
                {
                    { "NfieldErrorCode", nfieldErrorCode },
                    { "Message", message }
                };
            HttpContent content = new ObjectContent<Dictionary<string, object>>(httpErrorMock, new JsonMediaTypeFormatter());
            serverResponse.Content = content;

            // Act
            Assert.ThrowsDelegate actCode = () => serverResponse.ValidateResponse();

            // Assert
            var ex = Assert.Throws<NfieldErrorException>(actCode);
            Assert.Equal(ex.HttpStatusCode, httpStatusCode);
            Assert.Equal(ex.NfieldErrorCode, nfieldErrorCode);
            Assert.Equal(ex.Message, message);
        }
Beispiel #9
0
 public static async Task<bool> SetLoginPropertyValue(string propertyName, string propertyValue)
 {
   bool _Response;
   try
   {
     using (var client = new HttpClient())
     {
       client.BaseAddress = new Uri(System.Web.Configuration.WebConfigurationManager.AppSettings["SSOURL"]);
       client.DefaultRequestHeaders.Accept.Clear();
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
       // New code:
       LoginPropertyModel _data = new LoginPropertyModel();
       _data.SessionToken = new Guid(Repositories.CookieRepository.GetCookieValue("SessionID", Guid.NewGuid().ToString()));
       _data.PropertyName = propertyName;
       _data.PropertyValue = propertyValue;
       var content = new ObjectContent<LoginPropertyModel>(_data, new JsonMediaTypeFormatter());
       HttpResponseMessage response = await client.PostAsync("API/LoginProperty",content);
       if (response.IsSuccessStatusCode)
       {
         _Response = response.Content.ReadAsAsync<bool>().Result;
         return _Response;
       }
       else
       {
         return false;
       }
     }
   }
   catch (Exception)
   {
     return false;
   }
 }
Beispiel #10
0
        public void TestMethod1()
        {
            try
            {
                Task serviceTask = new Task();
                serviceTask.TaskId = 1;
                serviceTask.Subject = "Test Task";
                serviceTask.StartDate = DateTime.Now;
                serviceTask.DueDate = null;
                serviceTask.CompletedDate = DateTime.Now;
                serviceTask.Status = new Status
                {
                    StatusId = 3,
                    Name = "Completed",
                    Ordinal = 2
                };
                serviceTask.Links = new System.Collections.Generic.List<Link>();
                serviceTask.Assignees = new System.Collections.Generic.List<User>();
                

                serviceTask.SetShouldSerializeAssignees(true);

                var formatter = new JsonMediaTypeFormatter();

                var content = new ObjectContent<Task>(serviceTask, formatter);
                var reuslt = content.ReadAsStringAsync().Result;

            }
            catch(Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        static async Task RunAsync(string portfolio)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var account = new CompletionUpdateModel
                {
                    PortfolioID = portfolio,
                    MMDate = "2013/10/15",
                    Cluster1 = "AC",
                    Cluster2 = "AB",
                    ResultURL = "http://cc/" + portfolio,
                    PhoneNumber = "5556667777",
                    TerminosCC = "1"
                };

                var BOB_SECRET_KEY = "VY72IUVROA6LTYHK";

                var totp = new OTPNet.TOTP(BOB_SECRET_KEY, 90);

                var jsonFormatter = new JsonMediaTypeFormatter();

                var content = new ObjectContent<CompletionUpdateModel>(account, jsonFormatter);

                var url = "https://1-dot-dazzling-rex-760.appspot.com/_ah/api/bob/v1/bob/completionupdate";

                var requestUri = new Uri(url);

                var request = new HttpRequestMessage
                {
                    RequestUri = requestUri,
                    Method = HttpMethod.Post,
                    Content = content
                };

                request.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
                request.Headers.Add("BobUniversity", "cc");

                var code = totp.now();

                request.Headers.Add("BobToken", code.ToString());

                var response = client.SendAsync(request).Result;

                Console.WriteLine("HTTP status code: {0}", response.StatusCode);

                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();

                    var caresponse = JsonConvert.DeserializeObject<CompletionUpdateResponseModel>(jsonString);

                    Console.WriteLine("Codigo: {0}", caresponse.Codigo);
                    Console.WriteLine("Mensaje: {0}", caresponse.Mensaje);
                }
            }
        }
        public void ReadAsAsyncOfT_WhenContentIsObjectContent_GoesThroughSerializationCycleToConvertTypes()
        {
            var content = new ObjectContent<int[]>(new int[] { 10, 20, 30, 40 }, new JsonMediaTypeFormatter());

            byte[] result = content.ReadAsAsync<byte[]>().Result;

            Assert.Equal(new byte[] { 10, 20, 30, 40 }, result);
        }
        public void Constructor_SetsFormatterProperty()
        {
            var formatter = new Mock<MediaTypeFormatter>().Object;

            var content = new ObjectContent<string>(null, formatter, mediaType: null);

            Assert.Same(formatter, content.Formatter);
        }
 public override HttpContent Create(object item)
 {
     var type = item.GetType();
     MediaTypeFormatter formatter = DefineFormatter(this.Accept, type);
     var content = new ObjectContent(type, item, formatter);
     content.Headers.ContentType = MediaTypeHeaderValue.Parse(this.ContentType);
     return content;
 }
 public HttpResponseMessage Post(ObjectContent<Model> c)
 {
     Model m = c.ReadAsAsync().Result;
     Console.WriteLine("x = {0}, y = {1}, z = {2}",m.x,m.y,m.z);
     return new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK
                };
 }
        public async void WhenUsedToDeserializeShouldCreateCorrectObject()
        {
            var formatter = new ProtoBufFormatter();
            var item = new Item { Id = 1, Name = "Filip" };
            var content = new ObjectContent<Item>(item, formatter);

            var deserializedItem = await content.ReadAsAsync<Item>(new[] {formatter});
            Assert.Same(item, deserializedItem);
        }
 public PaymentRepresentation PayForOrder(string paymentUri, PaymentRepresentation payment)
 {
     var httpClient = GetHttpClient(_baseUri);
     var content = new ObjectContent<PaymentRepresentation>(payment, new[] { new RestbucksMediaTypeFormatter() });
     content.Headers.ContentType = new MediaTypeHeaderValue(RepresentationBase.RestbucksMediaType);
     var responseMessage = httpClient.Put(paymentUri, content);
     var responseContent = responseMessage.Content.ReadAs<PaymentRepresentation>(new [] {new RestbucksMediaTypeFormatter()});
     return responseContent;
 }
 public OrderRepresentation CreateOrder(OrderRepresentation order)
 {
     var httpClient = GetHttpClient();
     var content = new ObjectContent<OrderRepresentation>(order, new [] {new RestbucksMediaTypeFormatter()});
     content.Headers.ContentType = new MediaTypeHeaderValue(RepresentationBase.RestbucksMediaType);
     var responseMessage = httpClient.Post(_baseUri+"/order", content);
     var responseContent = responseMessage.Content.ReadAs<OrderRepresentation>(new [] {new RestbucksMediaTypeFormatter()});
     return responseContent;
 }
        public void Constructor_SetsFormatterProperty()
        {
            var formatterMock = new Mock<MediaTypeFormatter>();
            formatterMock.Setup(f => f.CanWriteType(typeof(String))).Returns(true);
            var formatter = formatterMock.Object;

            var content = new ObjectContent<string>(null, formatter, mediaType: (MediaTypeHeaderValue)null);

            Assert.Same(formatter, content.Formatter);
        }
        public void EncryptTest_Int32Object()
        {
            var expected = Int32.MaxValue;
            var originContent = new ObjectContent<Int32>(expected, new JsonMediaTypeFormatter());
            var encryptedContent = target.Encrypt(originContent);
            var decryptedContent = target.Decrypt(encryptedContent);
            var actual = decryptedContent.ReadAsAsync<Int32>().Result;

            Assert.AreEqual(expected, actual);
        }
        private HttpResponseMessage Execute()
        {
            var content = new ObjectContent<Dictionary<string, object>>(_claims, new JsonMediaTypeFormatter());
            var message = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = content
            };

            return message;
        }
        private HttpResponseMessage Execute()
        {
            var content = new ObjectContent<Dictionary<string, object>>(Result, Formatter);
            var message = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = content
            };

            return message;
        }
        public void Constructor_CallsFormattersGetDefaultContentHeadersMethod()
        {
            var formatterMock = new Mock<MediaTypeFormatter>();
            formatterMock.Setup(f => f.CanWriteType(typeof(String))).Returns(true);

            var content = new ObjectContent(typeof(string), "", formatterMock.Object, "foo/bar");

            formatterMock.Verify(f => f.SetDefaultContentHeaders(typeof(string), content.Headers, "foo/bar"),
                                 Times.Once());
        }
        /*
         * getProperties --
         * 
         * Retrieves the specified set of properties for the given managed object
         * reference into an array of result objects (returned in the same oder
         * as the property list).
         */
        public static Object[] getProperties(ManagedObjectReference moRef, String[] properties)
        {
            // PropertySpec specifies what properties to
            // retrieve and from type of Managed Object
            PropertySpec pSpec = new PropertySpec();
            pSpec.type = moRef.type;
            pSpec.pathSet = properties;

            // ObjectSpec specifies the starting object and
            // any TraversalSpecs used to specify other objects 
            // for consideration
            ObjectSpec oSpec = new ObjectSpec();
            oSpec.obj = moRef;

            // PropertyFilterSpec is used to hold the ObjectSpec and 
            // PropertySpec for the call
            PropertyFilterSpec pfSpec = new PropertyFilterSpec();
            pfSpec.propSet = new PropertySpec[] { pSpec };
            pfSpec.objectSet = new ObjectSpec[] { oSpec };

            // retrieveProperties() returns the properties
            // selected from the PropertyFilterSpec


            ObjectContent[] ocs = new ObjectContent[20];
            ocs = ecb._svcUtil.retrievePropertiesEx(_sic.propertyCollector, new PropertyFilterSpec[] { pfSpec });

            // Return value, one object for each property specified
            Object[] ret = new Object[properties.Length];

            if (ocs != null)
            {
                for (int i = 0; i < ocs.Length; ++i)
                {
                    ObjectContent oc = ocs[i];
                    DynamicProperty[] dps = oc.propSet;
                    if (dps != null)
                    {
                        for (int j = 0; j < dps.Length; ++j)
                        {
                            DynamicProperty dp = dps[j];
                            // find property path index
                            for (int p = 0; p < ret.Length; ++p)
                            {
                                if (properties[p].Equals(dp.name))
                                {
                                    ret[p] = dp.val;
                                }
                            }
                        }
                    }
                }
            }
            return ret;
        }
        public override async Task<BerkeleyError> DeleteAsync(BerkeleyDb db, Byte[] key, BerkeleyDbDelete flag, BerkeleyDbMultiple multiple)
        {
            String requestUri = "api/database/delete/?handle=" + db.Handle.ToString() + "&flag=" + flag.ToStringEx() + "&multiple=" + multiple.ToStringEx();
            var content = new ObjectContent<Byte[]>(key, _formatter, (String)null);
            HttpResponseMessage response = await _httpClient.PostAsync(requestUri, content).ConfigureAwait(false);
            if (!response.IsSuccessStatusCode)
                return new BerkeleyError(response.StatusCode);

            BerkeleyDbError error = await SerializeHelper.GetErrorAsync(_serializer, response.Content).ConfigureAwait(false);
            return new BerkeleyError(error);
        }
        private HttpResponseMessage Execute()
        {
            var content = new ObjectContent<Dictionary<string, object>>(_claims, Formatter);
            var message = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = content
            };

            Logger.Info("Returning userinfo response.");
            return message;
        }
        public override async Task<BerkeleyResult<BerkeleyDtoGet>> GetDtoGet(BerkeleyCursor cursor, Byte[] key, BerkeleyDbOperation operation, BerkeleyDbMultiple multiple, int bufferSize)
        {
            var requestUri = "api/cursor/read/?handle=" + cursor.Handle.ToString() + "&operation=" + operation.ToStringEx() + "&multiple=" + multiple.ToStringEx() + "&size=" + bufferSize.ToString();
            var content = new ObjectContent<Byte[]>(key, _formatter, (String)null);
            HttpResponseMessage response = await _httpClient.PostAsync(requestUri, content).ConfigureAwait(false);
            if (!response.IsSuccessStatusCode)
                return new BerkeleyResult<BerkeleyDtoGet>(response.StatusCode);

            BerkeleyDtoGet berkeleyDataGet = await SerializeHelper.GetDataGetAsync(_serializer, response.Content).ConfigureAwait(false);
            return new BerkeleyResult<BerkeleyDtoGet>((BerkeleyDbError)berkeleyDataGet.ErrorCode, berkeleyDataGet);
        }
        public void LogsCorrectAmountOfRequests()
        {
            var routeDataMoq = new Mock<RouteDataProvider>();
            routeDataMoq.Setup(x => x.GetRouteData(It.IsAny<HttpRequestMessage>()))
                        .Returns(new RouteData
                            {
                                Controller = "GEOCODE",
                                Action = "GET"
                            });

            var content =
                new ObjectContent<ResultContainer<GeocodeAddressResult>>(new ResultContainer<GeocodeAddressResult>
                    {
                        Result = new GeocodeAddressResult
                            {
                                InputAddress = "tESTING",
                                Score = 100
                            }
                    }, new JsonMediaTypeFormatter());
            content.Headers.Add("X-Type", typeof(ResultContainer<GeocodeAddressResult>).ToString());

            var contentMoq = new Mock<HttpContentProvider>();
            contentMoq.Setup(x => x.GetResponseContent(It.IsAny<HttpResponseMessage>()))
                      .Returns(content);

            var handler = new ApiLoggingHandler
                {
                    InnerHandler = new TestHandler((r, c) => TestHandler.Return200()),
                    //DocumentStore = DocumentStore,
                    RouteDataProvider = routeDataMoq.Object,
                    HttpContentProvider = contentMoq.Object
                };

            var client = new HttpClient(handler);
            const int requests = 10;

            for (var i = 0; i < requests; i++)
            {
                var result =
                    client.GetAsync("http://mapserv.utah.gov/beta/WebAPI/api/v1/Geocode/326 east south temple/84111?apiKey=key")
                          .Result;

                Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            }

            int count;
            using (var s = DocumentStore.OpenSession())
            {
                count = s.Query<GeocodeStreetZoneUsage>()
                         .Customize(x => x.WaitForNonStaleResultsAsOfNow())
                         .Count();
            }
            Assert.That(count, Is.EqualTo(requests));
        }
        public void CompressingObjectContentShouldRetainContentType2()
        {
            //Arrange
            var jsonContent = new ObjectContent<Foo>(new Foo() {Bar = "Hello"}, "application/json");

            //Act
            var compressedContent = new CompressedContent(jsonContent);

            //Assert
            Assert.AreEqual("application/json", compressedContent.Headers.ContentType.MediaType);
        }
        public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
        {
            if (formatter == null)
            {
                throw new ArgumentNullException("formatter");
            }
            if (mediaType == null)
            {
                throw new ArgumentNullException("mediaType");
            }

            object       sample  = String.Empty;
            MemoryStream ms      = null;
            HttpContent  content = null;

            try
            {
                if (formatter.CanWriteType(type))
                {
                    ms      = new MemoryStream();
                    content = new ObjectContent(type, value, formatter, mediaType);
                    formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
                    ms.Position = 0;
                    StreamReader reader = new StreamReader(ms);
                    string       serializedSampleString = reader.ReadToEnd();
                    if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
                    {
                        serializedSampleString = TryFormatXml(serializedSampleString);
                    }
                    else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
                    {
                        serializedSampleString = TryFormatJson(serializedSampleString);
                    }

                    sample = new TextSample(serializedSampleString);
                }
                else
                {
                    sample = new InvalidSample(String.Format(
                                                   CultureInfo.CurrentCulture,
                                                   "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
                                                   mediaType,
                                                   formatter.GetType().Name,
                                                   type.Name));
                }
            }
            catch (Exception e)
            {
                sample = new InvalidSample(String.Format(
                                               CultureInfo.CurrentCulture,
                                               "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
                                               formatter.GetType().Name,
                                               mediaType.MediaType,
                                               UnwrapException(e).Message));
            }
            finally
            {
                if (ms != null)
                {
                    ms.Dispose();
                }
                if (content != null)
                {
                    content.Dispose();
                }
            }

            return(sample);
        }
Beispiel #31
-1
        static void Main(string[] args)
        {
            System.Threading.Thread.Sleep(100);
            Console.Clear();

            Console.WriteLine("**************************开始执行获取API***********************************");
            HttpClient client = new HttpClient();

            //Get All Product 获取所有
            HttpResponseMessage responseGetAll = client.GetAsync(url + "api/Products").Result;
            string GetAllProducts = responseGetAll.Content.ReadAsStringAsync().Result;
            Console.WriteLine("GetAllProducts方法:" + GetAllProducts);

            //Get Product根据ID获取
            HttpResponseMessage responseGetID = client.GetAsync(url + "api/Products/1").Result;
            string GetProduct = responseGetID.Content.ReadAsStringAsync().Result;
            Console.WriteLine("GetProduct方法:" + GetProduct);

            //Delete Product 根据ID删除
            HttpResponseMessage responseDeleteID = client.DeleteAsync(url + "api/Products/1").Result;
            // string DeleteProduct = responseDeleteID.Content.ReadAsStringAsync().Result;
            Console.WriteLine("DeleteProduct方法:" );

            //HttpContent abstract 类

            //Post  Product 添加Product对象
            var model = new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M };
            HttpContent content = new ObjectContent(typeof(Product), model, new JsonMediaTypeFormatter());
            client.PostAsync(url + "api/Products/", content);

            //Put Product  修改Product
            client.PutAsync(url + "api/Products/", content);

            Console.ReadKey();
        }