Exemple #1
0
 public IHttpActionResult UploadPicture([FromBody] RoomImageUploadModel model)
 {
     // Check if model.Image contains byte[]
     if (model.Images != null)
     {
         // Generate Guid as Id and new image name in UploadResult constructor
         ImageUploadResult imageUploadResult = new ImageUploadResult(model.Images.Count);
         // Create folder if not exists
         System.IO.Directory.CreateDirectory(imagesRootPath + model.RoomId);
         int i = 0;
         // Save images to filesystem
         foreach (byte[] bytes in model.Images)
         {
             var fs = new BinaryWriter(new FileStream(
                                           imagesRootPath + model.RoomId + '\\' + imageUploadResult.Id[i].ToString() + ".jpg",
                                           FileMode.Append, FileAccess.Write));
             fs.Write(bytes);
             fs.Close();
             i++;
         }
         MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
         imageUploadResult.HttpStatusCode = HttpStatusCode.Created;
         return(Ok(imageUploadResult));
     }
     else
     {
         return(Content(HttpStatusCode.BadRequest, model.ToString()));
     }
 }
Exemple #2
0
        /// <summary>
        /// http://www.asp.net/web-api/overview/formats-and-model-binding/bson-support-in-web-api-21
        /// </summary>
        public async Task Transmit(Image <Bgr, byte> image)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(RootUrl);

                // Set the Accept header for BSON.
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));

                // POST using the BSON formatter.
                MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
                try
                {
                    var result = await client.PostAsync("api/pi/PostImage", image, bsonFormatter);

                    result.EnsureSuccessStatusCode();
                    //return result;
                }
                catch (Exception httpEx)
                {
                    Console.WriteLine(httpEx.Message);
                    //return default(HttpResponseMessage);
                }
            }
        }
Exemple #3
0
        public static void RegisterDbWebApi(this HttpConfiguration config, bool supportRazor = true, bool supportJsonp = true, bool supportXlsx = true, bool supportCsv = true, bool supportBson = true)
        {
            DbWebApiOptions.DerivedParametersCacheExpireInterval = TimeSpan.FromMinutes(15);

#if WEB_API2
            if (supportBson)
            {
                BsonMediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
                bsonFormatter.AddMediaTypeMapping("bson", BsonMediaTypeFormatter.DefaultMediaType, null);
                config.Formatters.Add(bsonFormatter);
            }
#endif
            if (supportCsv)
            {
                config.AddFormatPlug(new CsvFormatPlug());
            }
            if (supportXlsx)
            {
                config.AddFormatPlug(new XlsxFormatPlug());
            }
            if (supportJsonp)
            {
                config.Formatters.Add(new JsonpMediaTypeFormatter());
            }
            if (supportRazor)
            {
                config.Formatters.Add(new RazorMediaTypeFormatter());
            }
        }
Exemple #4
0
        public static void Register(HttpConfiguration config)
        {
            config.Services.Replace(typeof(ITraceWriter), new SimpleTracer());

            // Web API 路由
            var constraintResolver = new DefaultInlineConstraintResolver();

            constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));
            config.MapHttpAttributeRoutes(constraintResolver);

            var bson = new BsonMediaTypeFormatter();

            bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.contoso"));
            config.Formatters.Add(bson);
            config.Formatters.Add(new ProductCsvFormatter());

            var provider = new SimpleModelBinderProvider(typeof(GeoPoint), new GeoPointModelBinder());

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
            config.Services.Add(typeof(ValueProviderFactory), new CookieValueProviderFactory());

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
Exemple #5
0
        public bool Put(Player player)
        {
            try
            {
                Execute(() =>
                {
                    var client = new HttpClient
                    {
                        BaseAddress = new Uri(_baseUrl)
                    };
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));

                    var req = new PutDataRequest
                    {
                        ApiKey  = _apiKey,
                        Context = "Player"
                    };
                    req.SetObject(player);

                    var bsonFormatter = new BsonMediaTypeFormatter();
                    var res           = client.PutAsync("api/admin/Data", req, bsonFormatter).Result;
                    res.EnsureSuccessStatusCode();
                }, 5);

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error($"Put(Player({player.Id}))", ex);
                return(false);
            }
        }
Exemple #6
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //.....................................................................
            var config = GlobalConfiguration.Configuration;

            var json = config.Formatters.JsonFormatter;

            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            //---------------------------------------------------------------
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            //.....................................................................

            var bson = new BsonMediaTypeFormatter();

            bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.contoso"));
            config.Formatters.Add(bson);
            //.....................................................................
            ////config.MessageHandlers.Add(new System.Security.ApiKeyHandler());
            //.....................................................................
        }
        /// <summary>
        /// 创建MediaTypeFormatter
        /// </summary>
        /// <param name="mediaType"></param>
        /// <returns></returns>
        private MediaTypeFormatter CreateMediaTypeFormatter(string mediaType)
        {
            MediaTypeFormatter mediaTypeFormatter = null;

            switch (mediaType)
            {
#if RavenRpcHttpProtocol40
#else
            case MediaType.bson:
                mediaTypeFormatter = new BsonMediaTypeFormatter();
                break;

            case MediaType.msgpack:
                mediaTypeFormatter = new MsgPackTypeFormatter();
                break;
#endif
            case MediaType.form:
                mediaTypeFormatter = new FormUrlEncodedMediaTypeFormatter();
                break;

            case MediaType.xml:
                mediaTypeFormatter = new XmlMediaTypeFormatter();
                break;

            case MediaType.json:
            default:
                mediaTypeFormatter = new JsonMediaTypeFormatter();
                break;
            }

            return(mediaTypeFormatter);
        }
        public async Task <HttpResponseMessage> DownloadFile(Guid id)
        {
            var _client = new HttpClient();
            MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
            var result = await _client.GetAsync($"http://files.localhost.net/api/values/GetFile?id={id}");

            return(result);
        }
Exemple #9
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            config.Services.Replace(typeof(IExceptionHandler), new AppExceptionHandler());
            config.Services.Replace(typeof(IExceptionLogger), new AppExceptionLogger());
            // Web API routes

            // Support for More Media Types
            var bson = new BsonMediaTypeFormatter();

            bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.contoso"));
            config.Formatters.Add(bson);


            // DelegatingHandler[] handlers = new DelegatingHandler[]{new TokenAuthenicationHandler()};

            // Create a message handler chain with an end-point.
            // var routeHandlers = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), handlers);

            config.MapHttpAttributeRoutes();

            //config.Routes.MapHttpRoute(
            //  name: "DefaultPublicApi",
            //  routeTemplate: "apiV2/public/{id}",
            //  defaults: new { controller = "MyKeyController", Id = RouteParameter.Optional }
            //  );

            config.Routes.MapHttpRoute(
                name: "ApiRoot",
                routeTemplate: "api/public/{method}",
                defaults: new { controller = "MyKeyController", method = "ApiKey" }
                );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: null,
                handler: HttpClientFactory.CreatePipeline(
                    new HttpControllerDispatcher(config),
                    new DelegatingHandler[]
            {
                new TokenAuthenicationHandler()
            })
                // handler: new TokenAuthenicationHandler(GlobalConfiguration.Configuration)
                );



            // config.MessageHandlers.Add(new TokenAuthenicationHandler());
        }
Exemple #10
0
 public void SaveProducer()
 {
     try
     {
         bool       reLoadList = false;
         HttpClient client     = new HttpClient();
         client.BaseAddress = new Uri(baseUrl);
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
         client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token.access_token);
         string action = string.Empty;
         if (producerView.CurrentProducer.Id == 0)
         {
             //insert
             action     = insertAction;
             reLoadList = true;
         }
         else
         {
             action = updateAction;
         }
         //update
         MediaTypeFormatter  bsonFormatter = new BsonMediaTypeFormatter();
         HttpResponseMessage response      = client.PostAsync(action, producerView.CurrentProducer, bsonFormatter).Result;
         response.EnsureSuccessStatusCode();
         MediaTypeFormatter[] formatters       = new MediaTypeFormatter[] { bsonFormatter };
         ProducerResponse     producerResponse = response.Content.ReadAsAsync <ProducerResponse>(formatters).Result;
         if (producerResponse.Success)
         {
             if (producerResponse.Producer != null)
             {
                 if (reLoadList)
                 {
                     LoadProducers();
                     producerView.SelectedId = producerResponse.Producer.Id;
                 }
             }
         }
         else
         {
             throw new ProducerException(producerResponse.ErrorCode, producerResponse.ErrorMessage);
         }
     }
     catch (Exception ex)
     {
         StackTrace st = new StackTrace();
         StackFrame sf = st.GetFrame(0);
         MethodBase currentMethodName = sf.GetMethod();
         Guid       errorId           = Guid.NewGuid();
         //Log error here
         producerView.HandleException(ex, currentMethodName.Name, errorId);
     }
 }
Exemple #11
0
        public static void RegisterDbWebApi(this HttpConfiguration config, bool supportRazor = true, bool supportJsonp = true, bool supportXlsx = true, bool supportCsv = true, bool supportBson = true, bool supportFormUrlEncoded = true, bool supportMultipartForm = true)
        {
            if (config.Properties.ContainsKey(_RegisteredPropertyKey))
            {
                throw new InvalidOperationException("Registered DbWebApi Repeatedly");
            }

            DbWebApiOptions.DerivedParametersCacheExpireInterval = TimeSpan.FromDays(1);

            config.SupportMediaTypeShortMapping();
#if WEB_API2
            if (supportBson)
            {
                BsonMediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
                bsonFormatter.AddMediaTypeMapping("bson", BsonMediaTypeFormatter.DefaultMediaType, null);
                config.Formatters.Add(bsonFormatter);
            }
#endif
            if (supportCsv)
            {
                config.AddFormatPlug(new CsvFormatPlug());
            }
            if (supportXlsx)
            {
                config.AddFormatPlug(new XlsxFormatPlug());
            }
            if (supportJsonp)
            {
                config.Formatters.Add(new JsonpMediaTypeFormatter());
            }
            if (supportRazor)
            {
                config.Formatters.Add(new RazorMediaTypeFormatter());
            }
            if (supportFormUrlEncoded)
            {
                WebFormUrlEncodedMediaTypeFormatter.ReplaceJQueryMvcFormUrlEncodedFormatter(config.Formatters);
            }
            if (supportMultipartForm)
            {
                config.Formatters.Add(new MultipartFormDataMediaTypeFormatter());
            }

            config.Properties.TryAdd(_RegisteredPropertyKey, true);
        }
        public async Task SendAsBson <T>(T data, string requestUrl)
        {
            // TODO: Introduce an HttpClientProvider to detach from the HttpClient type
            // and make the code more testable
            using (var client = new HttpClient())
            {
                // Set the Accept header to ContentType BSON
                var mediaType = new MediaTypeWithQualityHeaderValue("application/bson");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(mediaType);

                // POST using a BSON formatter
                var bsonFormatter = new BsonMediaTypeFormatter();
                var result        = await client.PostAsync(requestUrl, data, bsonFormatter);

                result.EnsureSuccessStatusCode();
            }
        }
Exemple #13
0
        /// <summary>
        /// http://www.asp.net/web-api/overview/formats-and-model-binding/bson-support-in-web-api-21
        /// </summary>
        public async Task Transmit(Image <Bgr, byte> image)
        {
            if (!_enabled)
            {
                return;
            }

            if (_transmitting)
            {
                return;
            }

            _transmitting = true;
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(RootUrl);

                // Set the Accept header for BSON.
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));

                // POST using the BSON formatter.
                MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
                try
                {
                    var result = await client.PostAsync(UrlRoute, GetPostBody(image), bsonFormatter);

                    result.EnsureSuccessStatusCode();
                }
                catch (Exception httpEx)
                {
                    const int retryMilliseconds = 20000;
                    Console.WriteLine($"BsonPost: {httpEx}. Retrying in {retryMilliseconds}");
                    _enabled             = false;
                    _retryTimer          = new Timer(retryMilliseconds);
                    _retryTimer.Elapsed += (sender, args) => _enabled = true;
                    _retryTimer.Start();
                }
                finally
                {
                    _transmitting = false;
                }
            }
        }
Exemple #14
0
        public void SaveProduct()
        {
            bool       reLoadList = false;
            HttpClient client     = new HttpClient();

            client.BaseAddress = new Uri(baseUrl);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token.access_token);
            string action = string.Empty;

            if (productView.CurrentProduct.Id == 0)
            {
                //insert
                action     = insertAction;
                reLoadList = true;
            }
            else
            {
                action = updateAction;
            }
            //update
            MediaTypeFormatter  bsonFormatter = new BsonMediaTypeFormatter();
            HttpResponseMessage response      = client.PostAsync(action, productView.CurrentProduct, bsonFormatter).Result;

            response.EnsureSuccessStatusCode();
            MediaTypeFormatter[] formatters      = new MediaTypeFormatter[] { bsonFormatter };
            ProductResponse      productResponse = response.Content.ReadAsAsync <ProductResponse>(formatters).Result;

            if (productResponse.Success)
            {
                if (productResponse.Product != null)
                {
                    if (reLoadList)
                    {
                        LoadProducts();
                        productView.SelectedId = productResponse.Product.Id;
                    }
                }
            }
            else
            {
                throw new ProductException(productResponse.ErrorCode, productResponse.ErrorMessage);
            }
        }
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            // Configure Json.Net serializer to use camel case property names
            config.Formatters.JsonFormatter.SerializerSettings
            .ContractResolver = new CamelCasePropertyNamesContractResolver();

            // Configure Json.Net to handle cyclical references
            //config.Formatters.JsonFormatter.SerializerSettings
            //    .PreserveReferencesHandling = PreserveReferencesHandling.All;

            // Configure the Xml formatter serializer to handle cyclical references
            // - Add a reference to System.Runtime.Serialization
            //var dcs = new DataContractSerializer(typeof(Person), null, int.MaxValue,
            //    false, /* preserveObjectReferences */ true, null);
            //config.Formatters.XmlFormatter.SetSerializer<Person>(dcs);

            // Configure both json and xml to handle cycles
            // - Install the AspNetWebApi2Helpers.Serialization package
            config.Formatters.JsonPreserveReferences();
            config.Formatters.XmlPreserveReferences();

            // Add Bson media type formatter
            var bson = new BsonMediaTypeFormatter();

            bson.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All;
            config.Formatters.Add(bson);

            // Add Protobuf formatter
            // - Add [ProtoContract] and [ProtoMember] attributes to Person class
            config.Formatters.Add(new ProtoBufFormatter());

            app.UseWebApi(config);
            app.UseWelcomePage();
        }
Exemple #16
0
        public bool Put(Player player)
        {
            var copy = player;

            if (player.HasMedals)
            {
                // Don't save medals on the remote server, as it will take too much space and there is no use to it (so far)
                copy = (Player)player.Clone();
                copy.PurgeMedals();
            }

            try
            {
                Execute(() =>
                {
                    var client = new HttpClient
                    {
                        BaseAddress = new Uri(_baseUrl)
                    };
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));

                    var req = new PutDataRequest
                    {
                        ApiKey  = _apiKey,
                        Context = "Player"
                    };
                    req.SetObject(copy);

                    var bsonFormatter = new BsonMediaTypeFormatter();
                    var res           = client.PutAsync("api/admin/Data", req, bsonFormatter).Result;
                    res.EnsureSuccessStatusCode();
                }, 5);

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error($"Put(Player({player.Id}))", ex);
                return(false);
            }
        }
Exemple #17
0
        public async Task <K> Post <T, K>(string urlArguments, T obj)
        {
            var client = GetHttpClient();

            MediaTypeFormatter formatter;

            if (_useBSON)
            {
                formatter = new BsonMediaTypeFormatter();
            }
            else
            {
                formatter = new JsonMediaTypeFormatter();
            }

            var response = await client.PostAsync(new Uri($"{_baseURL}{urlArguments}"), obj, formatter);

            var data = await response.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <K>(data));
        }
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            // 默认返回Json数据
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            var bson = new BsonMediaTypeFormatter();

            bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/bson"));
            config.Formatters.Add(bson);

            appBuilder.UseWebApi(config);
        }
        public async Task <ServerRequest> UploadFileAsync(FileDTO.FileDTO fileDTO)
        {
            var serverRequest = new ServerRequest();

            try {
                HttpClient _client = new HttpClient();

                _client.DefaultRequestHeaders.Accept.Clear();
                _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));

                MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();

                await _client.PostAsync("http://files.localhost.net/api/values/PostFile?id", fileDTO, bsonFormatter);

                return(serverRequest);
            }
            catch {
                serverRequest.ErrorOccured = true;
                serverRequest.Message      = "Error was occcured when you try Upload File";
                return(serverRequest);
            }
        }
Exemple #20
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            config.Filters.Add(new WebApiTrackerAttribute());

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            config.Formatters.Add(new ProtoBufFormatter());
            config.Formatters.Add(new MessagePackFormatter());

            config.Formatters.Add(new ProductCsvFormatter());
            var bson = new BsonMediaTypeFormatter();

            bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.contoso"));
            config.Formatters.Add(bson);
            appBuilder.UseWebApi(config);
        }
Exemple #21
0
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
            // 将 Web API 配置为仅使用不记名令牌身份验证。
            //config.SuppressDefaultHostAuthentication();
            //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // 默认返回Json数据
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            var bson = new BsonMediaTypeFormatter();

            bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/bson"));
            config.Formatters.Add(bson);

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
Exemple #22
0
        static async Task RunAsync()
        {
            MediaTypeFormatter formatter = new BsonMediaTypeFormatter();

            MediaTypeFormatter[] formatters = new MediaTypeFormatter[] { formatter, };

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = _baseAddress;

                // All responses in BSON format
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));

                // POST api/MyData to create api/MyData/1 (send and receive MyData)
                MyData data = new MyData
                {
                    Name     = "First",
                    Decimal  = -90998887666m,
                    Double   = 37.777777777777777777d,
                    Long     = 238470192387401239L,
                    TimeSpan = TimeSpan.Zero,
                };
                Uri[] uris = new Uri[2];

                Console.WriteLine("POSTing to '/api/MyData'");
                HttpResponseMessage response = await client.PostAsync <MyData>("api/MyData", data, formatter);

                response.EnsureSuccessStatusCode();
                uris[0] = response.Headers.Location;
                Console.WriteLine("  ... success; created resource at '{0}'", uris[0].PathAndQuery);
                Console.WriteLine("  ... response was {0} bytes", response.Content.Headers.ContentLength);

                // Unused but could confirm returned data is unchanged (MyDataController makes no changes on POST)
                data = await response.Content.ReadAsAsync <MyData>(formatters);

                // POST api/MyData to create api/MyData/2
                data = new MyData
                {
                    Name     = "Second",
                    Decimal  = 999999999999m,
                    Double   = 3.3498712034e37d,
                    Long     = -91348701321872304L,
                    TimeSpan = new TimeSpan(0, 12, 13, 14, 123),
                };

                Console.WriteLine("POSTing to '/api/MyData'");
                response = await client.PostAsync <MyData>("api/MyData", data, formatter);

                response.EnsureSuccessStatusCode();
                uris[1] = response.Headers.Location;
                Console.WriteLine("  ... success; created resource at '{0}'", uris[1].PathAndQuery);

                // GET api/MyData (receive enumeration of MyData)
                Console.WriteLine("GETting from '/api/MyData'");
                response = await client.GetAsync("api/MyData");

                response.EnsureSuccessStatusCode();
                Console.WriteLine("  ... success; response was {0} bytes", response.Content.Headers.ContentLength);

                MyData[] allData = await response.Content.ReadAsAsync <MyData[]>(formatters);

                foreach (MyData returned in allData)
                {
                    PrettyPrint("  ...", returned);
                }

                // DELETE api/MyData/x (receive MyData)
                foreach (Uri uri in uris)
                {
                    Console.WriteLine("DELETing resource at '{0}'", uri.PathAndQuery);
                    response = await client.DeleteAsync(uri);

                    response.EnsureSuccessStatusCode();

                    data = await response.Content.ReadAsAsync <MyData>(formatters);

                    PrettyPrint("  ... success;", data);
                }
            }
        }
        public static void Register(HttpConfiguration config)
        {
            //// Uncomment the following to use the documentation from XML documentation file.
            //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));

            //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
            //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
            //// formats by the available formatters.
            //config.SetSampleObjects(new Dictionary<Type, object>
            //{
            //    {typeof(string), "sample string"},
            //    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
            //});

            // Extend the following to provide factories for types not handled automatically (those lacking parameterless
            // constructors) or for which you prefer to use non-default property values. Line below provides a fallback
            // since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
            config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif

            // Extend the following to use a preset object directly as the sample for all actions that support a media
            // type, regardless of the body parameter or return type. The lines below avoid display of binary content.
            // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
            var    bsonFormatter = new BsonMediaTypeFormatter();
            byte[] bson;
            using (var s = new MemoryStream())
            {
                bsonFormatter.WriteToStream(typeof(string), "Hello world", s, Encoding.UTF8);
                bson = s.ToArray();
            }
            config.SetSampleForMediaType(
                new ByteSample {
                Bytes = bson
            },
                new MediaTypeHeaderValue("application/bson"));


            var rss = @"<?xml version=""1.0"" encoding=""UTF-8"" ?>
                <rss version=""2.0"">
                <channel>
                 <title>Title</title>
                 <description>Desc</description>
                 <link>http://www.test.com</link>
                 <pubDate>Tue, 21 Jan 2014 18:45:00 +0000 </pubDate>
 
                 <item>
                  <title>Item</title>
                  <description>Desc</description>
                  <link>http://www.test.com/1</link>
                 <pubDate>Tue, 21 Jan 2014 18:45:00 +0000 </pubDate>
                 </item>
 
                </channel>
                </rss>";
            config.SetSampleResponse(rss, new MediaTypeHeaderValue("text/rss"), "Values", "Get");

            //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
            //// and have IEnumerable<string> as the body parameter or return type.
            //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));

            //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
            //// and action named "Put".
            //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");

            //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
            //// on the controller named "Values" and action named "Get" with parameter "id".
            //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");

            //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
            //config.SetActualRequestType(typeof(string), "Values", "Get");

            //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
            //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
            //config.SetActualResponseType(typeof(string), "Values", "Post");
        }
Exemple #24
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);


            SetContentView(Resource.Layout.AddPost);
            edtBrnd        = FindViewById <EditText>(Resource.Id.edtBrnd);
            edtDescription = FindViewById <EditText>(Resource.Id.edtDescription);
            edtYr          = FindViewById <EditText>(Resource.Id.edtYr);
            btnSave        = FindViewById <Button>(Resource.Id.btnSave);
            btnChoseImage  = FindViewById <Button>(Resource.Id.btnGetImage);
            ImageView      = FindViewById <ImageView>(Resource.Id.imgView);

            var localIDUser = Application.Context.GetSharedPreferences("Users", FileCreationMode.Private);
            int ID          = localIDUser.GetInt("IDUser", 0);

            btnSave.Click += async delegate
            {
                byte[] image = GetByteArrImageFromUri(SelectedImagePath);
                Post   post  = new Post();
                post.IDUser      = ID;
                post.Description = edtDescription.Text;
                post.Image       = "eeee";
                post.Year        = Int32.Parse(edtYr.Text);
                post.Brend       = edtBrnd.Text;
                post.Comment     = "eee";
                post.RealImage   = image;

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
                client.DefaultRequestHeaders.Add("Host", "localhost");
                MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
                try
                {
                    var result = client.PostAsync("http://10.0.2.2:44393/api/Post/Post", post, bsonFormatter).Result;
                    if (result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode == System.Net.HttpStatusCode.NoContent)
                    {
                        Clear();
                        Toast.MakeText(this, "Your post is saved!", ToastLength.Long).Show();
                        var intent = new Intent(this, typeof(MainActivity));
                        StartActivity(intent);
                    }
                }
                catch (Exception ex)
                {
                    Toast.MakeText(this, "Your post is not saved!", ToastLength.Long).Show();
                }



                //HttpResponseMessage httpResponse = new HttpResponseMessage();
                //var json = JsonConvert.SerializeObject(post);
                //var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
                //client.DefaultRequestHeaders.Add("Accept", "application/json");
                //client.DefaultRequestHeaders.Add("Host", "localhost");
                //try
                //{
                //    httpResponse = await client.PostAsJsonAsync(@"http://10.0.2.2:44393/api/Post/Post", post);
                //    if (httpResponse.StatusCode == System.Net.HttpStatusCode.OK || httpResponse.StatusCode == System.Net.HttpStatusCode.NoContent)
                //    {
                //        Clear();
                //        Toast.MakeText(this, "Your post is saved!", ToastLength.Long).Show();
                //        var intent = new Intent(this, typeof(MainActivity));
                //        StartActivity(intent);
                //    }

                //}
                //catch (Exception ex)
                //{
                //    Toast.MakeText(this, "Your post is not saved!", ToastLength.Long).Show();
                //}
            };

            btnChoseImage.Click += async delegate
            {
                ChoseImage();
            };
        }
        public async Task <ActionResult> UploadRoomImage(RoomViewModel roomViewModel)
        {
            if (ModelState.IsValid)
            {
                // Check if uploadedFiles != null
                if (roomViewModel.Images != null && roomViewModel.Images.Count() > 0)
                {
                    var roomImagesUploadModel = new RoomImagesUploadModel()
                    {
                        RoomId = roomViewModel.Id,
                        Images = new List <byte[]>()
                    };
                    foreach (HttpPostedFileBase file in roomViewModel.Images)
                    {
                        using (var reader = new BinaryReader(file.InputStream))
                        {
                            roomImagesUploadModel.Images.Add(reader.ReadBytes(file.ContentLength));
                        }
                    }
                    // Set the Accept header for BSON.
                    Client.DefaultRequestHeaders.Accept.Clear();
                    Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
                    // POST using the BSON formatter.
                    MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
                    try
                    {
                        var response = await Client.PostAsync <RoomImagesUploadModel>("api/Image/Upload/", roomImagesUploadModel, bsonFormatter);

                        if ((int)response.StatusCode == 200)
                        {
                            // Use BSON formatter to deserialize the response content
                            MediaTypeFormatter[] formatters = new MediaTypeFormatter[] {
                                new BsonMediaTypeFormatter()
                            };
                            ImageUploadResult imageUploadResult = await response.Content.ReadAsAsync <ImageUploadResult>(formatters);

                            for (int i = 0; i < roomViewModel.Images.Count(); i++)
                            {
                                // Create Dto and send to Database
                                RoomImageDTO roomImageDTO = new RoomImageDTO()
                                {
                                    Id     = imageUploadResult.Id[i],
                                    RoomId = roomImagesUploadModel.RoomId
                                };
                                roomImageService.Create(roomImageDTO);
                            }

                            TempData["ErrorMessage"] = "Images uploaded and a record has been creaded in database";
                            return(RedirectToAction("Edit", new { id = roomViewModel.Id.ToString() }));
                        }
                        else
                        {
                            TempData["ErrorMessage"] = "Bad responce, Status Code " + (int)response.StatusCode;
                            return(RedirectToAction("Edit", new { id = roomViewModel.Id.ToString() }));
                        }
                    }
                    catch
                    {
                        TempData["ErrorMessage"] = "Can't connect to API";
                        return(RedirectToAction("Edit", new { id = roomViewModel.Id.ToString() }));
                    }
                    // If response is Ok
                }
                else
                {
                    TempData["ErrorMessage"] = "File is empty";
                    return(RedirectToAction("Edit", new { id = roomViewModel.Id.ToString() }));
                }
            }
            else
            {
                TempData["ErrorMessage"] = "Room model state is not valid";
                return(RedirectToAction("Edit", new { id = roomViewModel.Id.ToString() }));
            }
        }