public bool ProcessResponse(HttpWebRequest webRequest, WebApiConsumerResponse response) { if (webRequest == null) return false; bool result = true; HttpWebResponse webResponse = null; try { webResponse = webRequest.GetResponse() as HttpWebResponse; GetResponse(webResponse, response); } catch (WebException wexc) { result = false; webResponse = wexc.Response as HttpWebResponse; GetResponse(webResponse, response); } catch (Exception exc) { result = false; response.Content = string.Format("{0}\r\n{1}", exc.Message, exc.StackTrace); } finally { if (webResponse != null) { webResponse.Close(); webResponse.Dispose(); } } return result; }
/// <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); // Debug.WriteLine(str); //} var json = JObject.Parse(response.Content); string metadata = (string)json["odata.metadata"]; if (!string.IsNullOrWhiteSpace(metadata) && metadata.EndsWith("#Customers")) { var customers = json["value"].Select(x => x.ToObject <Customer>()).ToList(); return(customers); } return(null); }
private void GetResponse(HttpWebResponse webResponse, WebApiConsumerResponse response) { if (webResponse == null) { return; } response.Status = string.Format("{0} {1}", (int)webResponse.StatusCode, webResponse.StatusDescription); response.Headers = webResponse.Headers.ToString(); using (var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)) { response.Content = reader.ReadToEnd(); } }
private void GetResponse(HttpWebResponse webResponse, WebApiConsumerResponse response, FolderBrowserDialog folderBrowserDialog) { 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; if (string.Compare(response.ContentType, "application/pdf", StringComparison.OrdinalIgnoreCase) == 0) { folderBrowserDialog.Description = "Please select a folder to save the PDF file."; var dialogResult = folderBrowserDialog.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.pdf"; } using (var stream = File.Create(Path.Combine(folderBrowserDialog.SelectedPath, fileName))) { webResponse.GetResponseStream().CopyTo(stream); } } } else { using (var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)) { // TODO: file uploads should use async and await keywords response.Content = reader.ReadToEnd(); } } }
public bool ProcessResponse(HttpWebRequest webRequest, WebApiConsumerResponse response) { if (webRequest == null) { return(false); } bool result = true; HttpWebResponse webResponse = null; try { webResponse = webRequest.GetResponse() as HttpWebResponse; GetResponse(webResponse, response); } catch (WebException wexc) { result = false; webResponse = wexc.Response as HttpWebResponse; GetResponse(webResponse, response); } catch (Exception exc) { result = false; response.Content = string.Format("{0}\r\n{1}", exc.Message, exc.StackTrace); } finally { if (webResponse != null) { webResponse.Close(); webResponse.Dispose(); } } return(result); }
private void CallTheApi() { if (!string.IsNullOrWhiteSpace(txtUrl.Text) && !txtUrl.Text.EndsWith("/")) txtUrl.Text = txtUrl.Text + "/"; if (!string.IsNullOrWhiteSpace(cboPath.Text) && !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) }; if (!string.IsNullOrWhiteSpace(cboQuery.Text)) 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 requestContent = new StringBuilder(); var response = new WebApiConsumerResponse(); var sb = new StringBuilder(); lblRequest.Text = "Request: " + context.HttpMethod + " " + context.Url; lblRequest.Refresh(); var webRequest = apiConsumer.StartRequest(context, cboContent.Text, requestContent); txtRequest.Text = requestContent.ToString(); bool result = apiConsumer.ProcessResponse(webRequest, response); lblResponse.Text = "Response: " + response.Status; sb.Append(response.Headers); if (result && radioJson.Checked && radioOdata.Checked) { var customers = apiConsumer.TryParseCustomers(response); if (customers != null) { sb.AppendLine(string.Format("Parsed {0} customer(s):", customers.Count)); foreach (var customer in customers) sb.AppendLine(customer.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); }
private void GetResponse(HttpWebResponse webResponse, WebApiConsumerResponse response) { if (webResponse == null) return; response.Status = string.Format("{0} {1}", (int)webResponse.StatusCode, webResponse.StatusDescription); response.Headers = webResponse.Headers.ToString(); using (var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)) { // TODO: file uploads should use async and await keywords response.Content = reader.ReadToEnd(); } }
/// <remarks> /// http://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing /// http://james.newtonking.com/json/help/index.html?topic=html/QueryJsonDynamic.htm /// http://james.newtonking.com/json/help/index.html?topic=html/LINQtoJSON.htm /// </remarks> public List<Customer> TryParseCustomers(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); // Debug.WriteLine(str); //} var json = JObject.Parse(response.Content); string metadata = (string)json["odata.metadata"]; if (!string.IsNullOrWhiteSpace(metadata) && metadata.EndsWith("#Customers")) { var customers = json["value"].Select(x => x.ToObject<Customer>()).ToList(); return customers; } return null; }
private void CallTheApi() { if (txtUrl.Text.HasValue() && !txtUrl.Text.EndsWith("/")) txtUrl.Text = 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) }; 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(); if (radioApi.Checked && txtFile.Text.HasValue()) { var id1 = txtIdentfier1.Text.ToInt(); var id2 = txtIdentfier2.Text; var keyForId1 = "Id"; var keyForId2 = ""; multiPartData = new Dictionary<string, object>(); if (cboPath.Text.StartsWith("/Uploads/ProductImages")) { // only one identifier required: product id, sku or gtin keyForId2 = "Sku"; } else if (cboPath.Text.StartsWith("/Uploads/ImportFiles")) { // only one identifier required: import profile id or profile name keyForId2 = "Name"; // to delete existing import files: //multiPartData.Add("deleteExisting", true); } if (id1 != 0) multiPartData.Add(keyForId1, id1); if (id2.HasValue()) multiPartData.Add(keyForId2, id2); apiConsumer.AddApiFileParameter(multiPartData, txtFile.Text); } var webRequest = apiConsumer.StartRequest(context, cboContent.Text, multiPartData, out requestContent); txtRequest.Text = requestContent.ToString(); var result = apiConsumer.ProcessResponse(webRequest, response); lblResponse.Text = "Response: " + response.Status; sb.Append(response.Headers); if (result && 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); }