コード例 #1
0
        /// <seealso cref="http://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing" />
        /// <seealso cref="http://james.newtonking.com/json/help/index.html?topic=html/QueryJsonDynamic.htm" />
        /// <seealso cref="http://james.newtonking.com/json/help/index.html?topic=html/LINQtoJSON.htm" />
        public static List <Customer> TryParseCustomers(this WebApiConsumerResponse response)
        {
            if (response == null || string.IsNullOrWhiteSpace(response.Content))
            {
                return(null);
            }

            //        dynamic dynamicJson = JObject.Parse(response.Content);

            //        foreach (dynamic customer in dynamicJson.value)
            //        {
            //            string str = string.Format("{0} {1} {2}", customer.Id, customer.CustomerGuid, customer.Email);
            //str.Dump();
            //        }

            var    json     = JObject.Parse(response.Content);
            string metadata = (string)json["@odata.context"];

            if (!string.IsNullOrWhiteSpace(metadata) && metadata.EndsWith("#Customers"))
            {
                var customers = json["value"].Select(x => x.ToObject <Customer>()).ToList();

                return(customers);
            }

            return(null);
        }
コード例 #2
0
        private void GetResponse(HttpWebResponse webResponse, WebApiConsumerResponse response, FolderBrowserDialog dialog)
        {
            if (webResponse == null)
            {
                return;
            }

            response.Status        = string.Format("{0} {1}", (int)webResponse.StatusCode, webResponse.StatusDescription);
            response.Headers       = webResponse.Headers.ToString();
            response.ContentType   = webResponse.ContentType;
            response.ContentLength = webResponse.ContentLength;

            var ct = response.ContentType;

            if (ct.HasValue() && (ct.StartsWith("image/") || ct.StartsWith("video/") || ct == "application/pdf"))
            {
                dialog.Description = "Please select a folder to save the file return by Web API.";

                var dialogResult = dialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    string fileName = null;
                    if (webResponse.Headers["Content-Disposition"] != null)
                    {
                        fileName = webResponse.Headers["Content-Disposition"].Replace("inline; filename=", "").Replace("\"", "");
                    }
                    if (fileName.IsEmpty())
                    {
                        fileName = "web-api-response";
                    }

                    var path = Path.Combine(dialog.SelectedPath, fileName);

                    using (var stream = File.Create(path))
                    {
                        webResponse.GetResponseStream().CopyTo(stream);
                    }

                    System.Diagnostics.Process.Start(path);
                }
            }
            else
            {
                using (var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    // TODO: file uploads should use async and await keywords
                    response.Content = reader.ReadToEnd();
                }
            }
        }
コード例 #3
0
        public bool ProcessResponse(HttpWebRequest webRequest, WebApiConsumerResponse response, FolderBrowserDialog folderBrowserDialog)
        {
            if (webRequest == null)
            {
                return(false);
            }

            var             result      = true;
            HttpWebResponse webResponse = null;

            try
            {
                webResponse = webRequest.GetResponse() as HttpWebResponse;
                GetResponse(webResponse, response, folderBrowserDialog);
            }
            catch (WebException wex)
            {
                result      = false;
                webResponse = wex.Response as HttpWebResponse;
                GetResponse(webResponse, response, folderBrowserDialog);
            }
            catch (Exception ex)
            {
                result           = false;
                response.Content = string.Format("{0}\r\n{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse.Dispose();
                }
            }
            return(result);
        }
コード例 #4
0
        private void CallTheApi()
        {
            if (txtUrl.Text.HasValue() && !txtUrl.Text.EndsWith("/"))
            {
                txtUrl.Text += "/";
            }

            if (cboPath.Text.HasValue() && !cboPath.Text.StartsWith("/"))
            {
                cboPath.Text = "/" + cboPath.Text;
            }

            var context = new WebApiRequestContext
            {
                PublicKey         = txtPublicKey.Text,
                SecretKey         = txtSecretKey.Text,
                Url               = txtUrl.Text + (radioOdata.Checked ? "odata/" : "api/") + txtVersion.Text + cboPath.Text,
                HttpMethod        = cboMethod.Text,
                HttpAcceptType    = radioJson.Checked ? ApiConsumer.JsonAcceptType : ApiConsumer.XmlAcceptType,
                AdditionalHeaders = cboHeaders.Text
            };

            if (cboQuery.Text.HasValue())
            {
                context.Url = string.Format("{0}?{1}", context.Url, cboQuery.Text);
            }

            if (!context.IsValid)
            {
                "Please enter Public-Key, Secret-Key, URL and method.".Box(MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Debug.WriteLine(context.ToString());
                return;
            }

            var           apiConsumer    = new ApiConsumer();
            var           response       = new WebApiConsumerResponse();
            var           sb             = new StringBuilder();
            StringBuilder requestContent = null;
            Dictionary <string, object> multiPartData = null;

            lblRequest.Text = "Request: " + context.HttpMethod + " " + context.Url;
            lblRequest.Refresh();

            // Create multipart form data.
            if (cboFileUpload.Text.HasValue())
            {
                try
                {
                    var fileUploadModel = JsonConvert.DeserializeObject(cboFileUpload.Text, typeof(FileUploadModel)) as FileUploadModel;
                    multiPartData = apiConsumer.CreateMultipartData(fileUploadModel);
                }
                catch
                {
                    cboFileUpload.RemoveCurrent();
                    cboFileUpload.Text = string.Empty;
                    "File upload data is invalid.".Box(MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }

            var webRequest = apiConsumer.StartRequest(context, cboContent.Text, multiPartData, out requestContent);

            txtRequest.Text = requestContent.ToString();

            var result = apiConsumer.ProcessResponse(webRequest, response, folderBrowserDialog1);

            lblResponse.Text = "Response: " + response.Status;
            sb.Append(response.Headers);

            if (result && response.Content.HasValue())
            {
                if (radioJson.Checked && radioOdata.Checked)
                {
                    var customers = response.TryParseCustomers();
                    if (customers != null)
                    {
                        sb.AppendLine("Parsed {0} customer(s):".FormatInvariant(customers.Count));
                        customers.ForEach(x => sb.AppendLine(x.ToString()));
                        sb.Append("\r\n");
                    }
                }
            }

            sb.Append(response.Content);
            txtResponse.Text = sb.ToString();

            cboPath.InsertRolled(cboPath.Text, 64);
            cboQuery.InsertRolled(cboQuery.Text, 64);
            cboContent.InsertRolled(cboContent.Text, 64);
            cboHeaders.InsertRolled(cboHeaders.Text, 64);
            cboFileUpload.InsertRolled(cboFileUpload.Text, 64);
        }