My translation of a given string doesn't work using AzureApi - c#

I want to translate a given string to a specific language and print the translation to console , but my console prints nothing , I am also trying to catch some error , but my console still prints nothing, anyone know why ?
Here are my headers:
using Newtonsoft.Json;
using System.Net.Http;
using NPOI.SS.Formula.Functions;
I have defined the necessary key and region and url attribute inside class block , but it just won't work like this :
public const string subscriptionKey = "mykey";
public const string region = "myregion";
public const string endpoint="https://api.cognitive.microsofttranslator.com/";
mykey consists of my subscription key and myregion consists of my region
Here is my main:
TranslateString();
Here is my implementation of method TranslateString
public static async void TranslateString()
{
string route = "translate?api-version=3.0&from=en&to=fr&to=zu";
string xmlString = "Hello , welcome";
try
{
object[] body = new object[] { new { Text = xmlString } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Headers.Add("Ocp-Apim-Subscription-Region", region);
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success , translated text:");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
else
{
Console.WriteLine("Error: " + response.StatusCode + " " + response.ReasonPhrase);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}

Here is your code with minimal changes to make it produce an output. The relevant change is for TranslateString() to return a Task, so that the main thread waits for the async call to complete. Another option would have been to make this a synchronous call.
This uses the .Net built-in Json serializer instead of Newtonsoft for simplicity.
This compiles as is using .Net7 with C#10, and your key and region filled in.
using System.Net;
using System.Text;
using System.Text.Json;
const string subscriptionKey = "mykey";
const string region = "myregion";
const string endpoint = "https://api.cognitive.microsofttranslator.com/";
Console.WriteLine("Program Start");
await TranslateString();
static async Task TranslateString()
{
string route = "translate?api-version=3.0&from=en&to=fr&to=zu";
string xmlString = "Hello , welcome";
try
{
object[] body = new object[] { new { Text = xmlString } };
var requestBody = JsonSerializer.Serialize(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Headers.Add("Ocp-Apim-Subscription-Region", region);
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success , translated text:");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
else
{
Console.WriteLine("Error: " + response.StatusCode + " " + response.ReasonPhrase);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}
}
The output is:
Program Start
Success , translated text:
[{"translations":[{"text":"Bonjour , bienvenue","to":"fr"},{"text":"Sawu , wamukelekile","to":"zu"}]}]
You will need to add deserializing the output.

Related

Translate single document using azure translator

I want to translate single document from one language to another please guide me how to do that i have done translating all the files in azure blob storage but not able to find to translate single file.
please find below code and let me know the changes.
string _FileName = Path.GetFileName(file.FileName);
fileName = _FileName;
string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
file.SaveAs(_path);
string route = "/batches";
string endpoint = "https://translator.cognitiveservices.azure.com/translator/text/batch/v1.0";
string filePath = UploadToAzureStorageAccount.UploadDocument(_path, "uploadeddocs");
string subscriptionKey = "key";
string json = ("" +
"{\"inputs\": " +
"[{\"storageType\": \"File\","+"\"source\": " +
"{\"sourceUrl\": \"https://cdposticketsstorage.blob.core.windows.net/uploadeddocs/test.docx?sp=r&st=2022-03-08T08:13:18Z&se=2022-03-08T16:13:18Z&spr=https&sv=2020-08-04&sr=b&sig=Pt68ogFCj6WSgEBUWI95YJ4GudOcyhEW1cgVXmFCing%3D\"," +
"\"storageSource\": \"AzureBlob\"" +
"}," +
"\"targets\": " +
"[{\"targetUrl\": \"https://cdposticketsstorage.blob.core.windows.net/translateddocs/translate.docx?sp=rcw&st=2022-03-08T11:15:45Z&se=2022-03-08T19:15:45Z&spr=https&sv=2020-08-04&sr=b&sig=QM2FhLxOIE%2FLjeLLfYyR2PmfkNb3nm70wZdCveSJC0M%3D\"," +
"\"storageSource\": \"AzureBlob\"," +
"\"language\": \"fr\"}]}]}");
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
string result = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Status code: {response.StatusCode}");
Console.WriteLine();
Console.WriteLine($"Response Headers:");
Console.WriteLine(response.Headers);
}
else
Console.Write("Error");
}
// TextTranslatorAPI client = new TextTranslatorAPI();
//string res = await client.DocumentTranslator(fileName);
//return res;
}
ViewBag.Message = "File Uploaded Successfully!!";
}
catch(Exception e)
{
ViewBag.Message = "File upload failed!!";
}

How to create issue in jira using c#

I'm trying to create an issue in JIRA cloud using c# and the REST API,
I get the 400 error (bad rquest), I dont know what I'm doing wrong !
This is My functions
public static string PostJsonRequest(string endpoint, string userid, string password, string json)
{
// Create string to hold JSON response
string jsonResponse = string.Empty;
using (var client = new WebClient())
{
try
{
client.Encoding = System.Text.Encoding.UTF8;
client.Headers.Set("Authorization", "Basic " + GetEncodedCredentials(userid, password));
client.Headers.Add("Content-Type: application/json");
client.Headers.Add("Accept", "application/json");
var uri = new Uri(endpoint);
var response = client.UploadString(uri, "POST", json);
jsonResponse = response;
}
catch (WebException ex)
{
// Http Error
if (ex.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
var statusCode = (int)wrsp.StatusCode;
var msg = wrsp.StatusDescription;
// throw new SmtpException(statusCode, msg);
}
else
{
// throw new HttpException(500, ex.Message);
}
}
}
return jsonResponse;
}
And this is my JSON
string json = #"{
'fields':
{
'project':
{
'key':'IS'
},
'summary':'REST Test',
'issuetype':
{
'name':'Bug'
},
}
}";
string Url = "https://XXXXXX.atlassian.net/rest/api/2/issue/";
Any Ideas on what I'm doing wrong ?

Amadeus for Developers, don't know how to configure?

So, for my homework, I need to make an application that will not use SQL(as I used to), but the rest api. Problem is that I never done this, and I don't know how to configure it.
So far I got this:
string strUrlTest = String.Format("https://test.api.amadeus.com/v1/shopping/flight-offers");
WebRequest requestObjGet = WebRequest.Create(strUrlTest);
requestObjGet.Method = "GET";
requestObjGet.Headers.Add("API KEY",
"API SECRET);
HttpWebResponse responseObjGet = null;
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();
string strResultTest = null;
using(Stream stream = responseObjGet.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strResultTest = sr.ReadToEnd();
sr.Close();
}
I just wanted to see with debugger if I got my all my data, but my program crashes at
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();
Could you help me figure it out?
I wrote a code example in C#, replace apikey and apisecret by the ones you get on the portal by creating an application. You can find a guide here.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace testApp
{
public class AmadeusTest
{
static void Main()
{
const string URL = "https://test.api.amadeus.com/v1/shopping/flight-destinations?origin=BOS";
string token = getToken();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "");
Task<HttpResponseMessage> response = client.SendAsync(request);
string myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result).ToString();
JObject jsonObject = JObject.Parse(myJsonResponse);
Console.WriteLine(myJsonResponse);
Console.WriteLine(jsonObject["data"][0]["destination"]);
client.Dispose();
}
private static string getToken()
{
const string apikey = "";
const string apisecret = "";
const string tokenURL = "https://test.api.amadeus.com/v1/security/oauth2/token";
string postData = $"grant_type=client_credentials&client_id={apikey}&client_secret={apisecret}";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(tokenURL);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");
request.Content = new StringContent(postData,
Encoding.UTF8,
"application/x-www-form-urlencoded");
Task<HttpResponseMessage> response = client.SendAsync(request);
if (response.Result.IsSuccessStatusCode)
{
string myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result).ToString();
JObject jsonObject = JObject.Parse(myJsonResponse);
client.Dispose();
string token = (string)jsonObject["access_token"];
return token;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.Result.StatusCode, response.Result.ReasonPhrase);
return response.Result.ReasonPhrase;
}
}
}
}
The getToken method is in charge of doing the authorization process (as explained here).
This token is used in the API call (in the Main method). It is added to the Authorization header with the value: Bearer {token}
Firstly, you need to get access token, to retrieve the data. How i accomplish this, you can see in code below.
[HttpGet("[action]")]
public async Task<List<FlightOffersModel>> GetData(string origin, string destination, string departureDate, string returnDate, string adults, string currency)
{
const string client_id = "oqsIlG0xAbnlXXXXXXXXXXg7GdYwemI5";
const string client_secret = "lAcXXXXXXXXX5AD0";
string token = await GetToken(client_id, client_secret);
const string baseUrl = "https://test.api.amadeus.com/v1/";
string urlParams = "shopping/flight-offers?origin=" + origin + "&destination=" + destination + "&departureDate=" + departureDate;
urlParams += returnDate == "" || returnDate == null ? "" : "&returnDate=" + returnDate;
urlParams += "&adults=" + adults + "&nonStop=false&currency=" + currency + "&max=50";
FlightOffer ff = null;
List<FlightOffersModel> model = new List<FlightOffersModel>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.amadeus+json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await client.GetAsync(urlParams);
if (response.IsSuccessStatusCode)
{
var x = await response.Content.ReadAsStringAsync();
var xx = JObject.Parse(x);
ff = JsonConvert.DeserializeObject<FlightOffer>(xx.ToString());
foreach (var fo in ff.Data)
{
FlightOffersModel temp = new FlightOffersModel();
foreach (var item in fo.OfferItems)
{
foreach (var service in item.Services)
{
if (item.Services.IndexOf(service) < 1)
{
temp.BrojPresjedanjaPovratak = item.Services.Length > 1 ? GetBrojPresjedanja(item.Services[1]) : 0;
temp.BrojPresjedanjaOdlazak = GetBrojPresjedanja(item.Services[0]);
temp.BrojPutnika = GetBrojPutnika(service.Segments);
temp.UkupnaCijena = item.Price.Total;
temp.Valuta = ff.Meta.Currency;
temp.PolazniAerodrom = GetAerodromName(service.Segments, "departure", ff.Dictionaries.Locations);
temp.OdredisniAerodrom = GetAerodromName(service.Segments, "arrival", ff.Dictionaries.Locations);
temp.DatumPolaska = GetDatumLeta(service.Segments, "departure");
temp.DatumPovratka = GetDatumLeta(service.Segments, "arrival");
model.Add(temp);
}
}
}
}
}
}
return model;
}
This part of code is to get access token
const string client_id = "oqsIlG0xAbnlXXXXXXXXXXg7GdYwemI5";
const string client_secret = "lAcXXXXXXXXX5AD0";
string token = await GetToken(client_id, client_secret);
and this is GetToken function:
private async Task<string> GetToken(string client_id, string client_secret)
{
AccessToken s = null;
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://test.api.amadeus.com/v1/security/oauth2/token"))
{
request.Content = new StringContent("grant_type=client_credentials&client_id=" + client_id + "&client_secret=" + client_secret, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
s = await response.Content.ReadAsAsync<AccessToken>();
}
}
}
return s.Access_token;
}
The rest of the code supplies data according to the parameters that user entered.

How to make HTTP call from Controller ? to Use web API's Asp.Net Core C#

I want to make HTTP calls to various services, POST/GET/DELETE.., and read responses JSON AND XML, How do I do this in C# on servers side?
In short: How to make Api call from Asp.Net Core C#.
Client side Ajax doesn't work, (for cross domains)
Use ajax to call controler:
$.ajax({
type: "GET",
url: "/API/Gumtreetoken?user=username&pasword=password",
success: function (atsakas) {
alert(atsakas);
},
error: function (error) {
alert("error");
}
});
And, from controller I use HTTPClient to make POST call and get needed values from XML responce.
[Authorize]
[Route("API/Gumtreetoken")]
public IActionResult GumtreePost(string user, string pasword)
{
string atsakas = "";
string token = "";
string id = "";
using (HttpClient client = new HttpClient())
{
//parametrai (PARAMS of your call)
var parameters = new Dictionary<string, string> { { "username", "YOURUSERNAME" }, { "password", "YOURPASSWORD" } };
//Uzkoduojama URL'ui
var encodedContent = new FormUrlEncodedContent(parameters);
try
{
//Post http callas.
HttpResponseMessage response = client.PostAsync("https://feed-api.gumtree.com/api/users/login", encodedContent).Result;
//nesekmes atveju error..
response.EnsureSuccessStatusCode();
//responsas to string
string responseBody = response.Content.ReadAsStringAsync().Result;
atsakas = responseBody;
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
//xml perskaitymui
XmlDocument doc = new XmlDocument();
//xml uzpildomas api atsakymu
doc.LoadXml(#atsakas);
//iesko TOKEN
XmlNodeList xmltoken = doc.GetElementsByTagName("user:token");
//iesko ID
XmlNodeList xmlid = doc.GetElementsByTagName("user:id");
token = xmltoken[0].InnerText;
id = xmlid[0].InnerText;
atsakas = "ID: " + id + " Token: " + token;
}
return Json(atsakas);
}
This should be Async, so, you could do like this:
[Authorize]
[Route("API/Gumtreetoken")]
public async Task<IActionResult> GumtreePost(string user, string pasword)
{
string atsakas = "";
string token = "";
string id = "";
using (HttpClient client = new HttpClient())
{
var parameters = new Dictionary<string, string> { { "username", "YOURUSERNAME" }, { "password", "YOURPASSWORD" } };
var encodedContent = new FormUrlEncodedContent(parameters);
try
{
HttpResponseMessage response = await client.PostAsync("https://feed-api.gumtree.com/api/users/login", encodedContent);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
atsakas = responseBody;
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(#atsakas);
XmlNodeList xmltoken = doc.GetElementsByTagName("user:token");
XmlNodeList xmlid = doc.GetElementsByTagName("user:id");
token = xmltoken[0].InnerText;
id = xmlid[0].InnerText;
atsakas = "ID: " + id + " Token: " + token;
}
return Json(atsakas);
}
Try this code: To make Api call from Asp.Net Core, Server Side (C#).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace core.api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public async Task<ActionResult<string>> Get()
{
string url="https://jsonplaceholder.typicode.com/todos"; // sample url
using (HttpClient client = new HttpClient())
{
return await client.GetStringAsync(url);
}
}
}
}

C# application/x-www-form-urlencoded OAuth and HTTP REST requests using HttpClient

So I'm trying to put together some very simple and elegant code samples to help people use my API. The latest language I'm tackling is C#.
I think the IETF OAuth2.0 standard I read implies the HTTP request Content-Type must be "application/x-www-form-urlencoded". The Django API server I have, currently seems to only support this Content-Type (for the OAuth resource). The other languages POST content this way by default!
After extensive research and several experiments I am wondering if I have missed something fundamental. Surely there would be a helpful library OR technique to create the ...urlencoded string OR at least someone else must have run into this???
I will outline some of the best solution I have so far bellow, but it just seems wrong.
Also from a bunch of internet browsing I figured I would use the HttpClient library. I like the fact that it uses the async model, which perhaps will be more useful for any developers using WPF or XAML or Windows 8 apps. It also works well for Consoles and Forms.
I use the Newtonsoft Json.Net library for serialization. First of all I create a POCO of the authorization strings. Then I serialize it to JSON, then to key/value pairs, then iterate through the key/value pairs catenating with the required '=' and '&' chars, then UTF-8, then escape the spaces etc.
//Setup HTTP request
HttpClient httpRequest = new HttpClient();
httpRequest.DefaultRequestHeaders.Add("Accept", "application/json");
string urlBase = "https://__secret__/api/v1/";
HttpResponseMessage msg = new HttpResponseMessage();
//POST to oauth to get token (must be sent as "application/x-www-form-urlencoded")
OAuthConfig oAuthCredentials = new OAuthConfig { client_id = client_id, client_secret = secret, username = "__secret__", password = "__secret__", grant_type = "__secret__" };
string jsonString = JsonConvert.SerializeObject(oAuthCredentials); //convert to JSON
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString); //convert to key/value pairs
string urlEncodedData = ConvertToFormUrlEncodedFormat(values);
HttpContent payload = new StringContent(urlEncodedData, Encoding.UTF8, "application/x-www-form-urlencoded");
msg = httpRequest.PostAsync(urlBase + "oauth/access_token/", payload).Result;
string responseBodyAsText = msg.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseBodyAsText);
Other options I could think of were...
Reflection, however digging into reflection in a code sample seems a bit manic.
It turns out that other than the OAuth setup, the rest of the API supports JSON type POSTs. So I guess I could write a function to walk through the oAuthConfig model and catenate a string, since that POCO model is unlikely to change and is the only model which requires urlEncoding that I can anticipate. That would save us from the slightly confusing use of the Dictionary. The use of the dictionary and then iterating is more generic, however perhaps a bit OTT.
I figure most of the time people will be using JSON, so showing how that might happen is useful.
In general it seems quite hard to serialize a POCO model to a string and/or to a urlEncoded string.
Questions
does OAuth mandate urlencoded, could you convert server-side?
is HttpClient the best choice, does async matter?
is there a better simpler way to serialize a POCO to ...form-urlencoded?
Thanks for any useful comments you may have.
var model = new LoginModel { Username = "patient#gmail.com", Password = "123456", DeviceId = "123456789", RoleId = 1 };
url.Append("/Login");
string data = JsonConvert.SerializeObject(model);// "{\"username\":\"dscdemo0#gmail.com\",\"password\":\"vipin123\"}";
NameValueCollection inputs = new NameValueCollection();
inputs.Add("json", data);
WebClient client = new WebClient();
var reply = client.UploadValues(url.ToString(), inputs);
string temp = Encoding.ASCII.GetString(reply);
var result = JsonConvert.DeserializeObject<MessageTemplateModel>
(temp);
Api Call
public async Task<IHttpActionResult> Login(HttpRequestMessage request)//(LoginModel modelN)
{
try
{
var form = request.Content.ReadAsFormDataAsync().Result;
var modelN = JsonConvert.DeserializeObject<LoginModel>(form["json"].ToString());
// token = JsonConvert.DeserializeObject<string>(form["token"].ToString());
bool istoken = _appdevice.GettokenID(modelN.DeviceId);
if (!istoken)
{
statuscode = 0;
message = ErrorMessage.TockenNotvalid;
goto invalidtoken;
}
User model = new User();
// var session = HttpContext.Current.Session;
// session.Add("UserRole", GetProfileId.UserRole);
var user = await _userManager.FindAsync(modelN.Username, modelN.Password);}}
i am able to call url-encoder request from device and web app.
//I disclaimer everything and note that I haven't re-checked if this posted code works.
using System;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json; //install with Nuget package installer- "json.Net"
using System.Net.Http; //install with Nuget package installer- "...Web API client libraries"
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json; //security risk till certificate fixed
namespace CSharpDemoCodeConsole
{
class Program
{
const string api_key = "your_api_key"; //set your api_key here
const string user_auth = "your_username" + ":" + "your_password"; // set your user credentials here
const string urlBase = "https://#SECRET.com#/api/v1";
static void Main(string[] args)
{
Console.WriteLine("Making call to webserver asynchronously");
MakeCallAsynchronously();
Console.WriteLine("**************************************");
Console.WriteLine("Making call to webserver synchronously");
MakeCallSynchronously();
Console.WriteLine("**************************************");
Console.WriteLine("Making call to webserver synchronously without Newtonsoft serialization");
MakeCallSynchronouslyWithoutNewtonSoft();
Console.WriteLine("Press spacebar to close the application");
Console.ReadKey();
}
private static void MakeCallAsynchronously()
{
//Always accept untrusted certificates - don't use in production
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//Setup request
string authorizeString = Convert.ToBase64String(Encoding.ASCII.GetBytes(user_auth));
HttpClient httpRequest = new HttpClient();
httpRequest.DefaultRequestHeaders.Add("Authorization", "Basic " + authorizeString);
httpRequest.DefaultRequestHeaders.Add("Accept", "application/json");
//GET from places resource
try
{
var requestTask = httpRequest.GetAsync(urlBase + "places/" + "?api_key=" + api_key,
System.Net.Http.HttpCompletionOption.ResponseContentRead);
//Update UI while waiting for task to complete
while (requestTask.Status != System.Threading.Tasks.TaskStatus.RanToCompletion)
{
Console.Write(".");
System.Threading.Thread.Sleep(30);
}
if (requestTask.Result.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Unexpected response from server: {0}", requestTask.Result);
return;
}
var places = JsonConvert.DeserializeObject<Page<Place>>(requestTask.Result.Content.ReadAsStringAsync().Result);
Console.WriteLine("GET places response " + requestTask.Result.Content.ReadAsStringAsync().Result);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return;
}
//POST to places resource
try
{
string jsonString = JsonConvert.SerializeObject(new Place { name = "test place", latitude = 0, longitude = 0 });
HttpContent payload = new StringContent(jsonString, Encoding.UTF8, "application/json");
var requestTask = httpRequest.PostAsync(urlBase + "places/" + "?api_key=" + api_key, payload);
//Update UI while waiting for task to complete
while (requestTask.Status != System.Threading.Tasks.TaskStatus.RanToCompletion)
{
Console.Write(".");
System.Threading.Thread.Sleep(30);
}
if (requestTask.Result.StatusCode != HttpStatusCode.Created)
{
Console.WriteLine("Unexpected response from server: {0}", requestTask.Result);
return;
}
Console.WriteLine("POST places response " + requestTask.Result.Content.ReadAsStringAsync().Result);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return;
}
}
private static void MakeCallSynchronously()
{
//Always accept untrusted certificates - don't use in production
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//Setup Request
string authorizeString = Convert.ToBase64String(Encoding.ASCII.GetBytes(user_auth));
var client = new WebClient();
client.Headers.Add("Authorization", "Basic " + authorizeString);
client.Headers.Add("Accept", "application/json");
//GET from places resource
try
{
var responseStream = client.OpenRead(urlBase + "places/" + "?api_key=" + api_key);
var response = (new StreamReader(responseStream).ReadToEnd());
var places = JsonConvert.DeserializeObject<Page<Place>>(response);
Console.WriteLine("GET places response " + response);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
}
//POST to places resource
try
{
client.Headers.Add("Accept", "application/json");
client.Headers.Add("Content-Type", "application/json");
string jsonString = JsonConvert.SerializeObject(new Place { name = "test place", latitude = 0, longitude = 0 });
client.Encoding = System.Text.Encoding.UTF8;
string response = client.UploadString(urlBase + "places/" + "?api_key=" + api_key, jsonString);
Console.WriteLine("POST places response " + response);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return;
}
}
private static void MakeCallSynchronouslyWithoutNewtonSoft()
{
//Always accept untrusted certificates - don't use in production
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//Setup Request
string authorizeString = Convert.ToBase64String(Encoding.ASCII.GetBytes(user_auth));
var client = new WebClient();
client.Headers.Add("Authorization", "Basic " + authorizeString);
client.Headers.Add("Accept", "application/json");
//GET from places resource
try
{
var responseStream = client.OpenRead(urlBase + "places/" + "?api_key=" + api_key);
MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);
ms.Position = 0;
var placesDeserializer = new DataContractJsonSerializer(typeof(Page<Place>));
var places = (Page<Place>)placesDeserializer.ReadObject(ms);
ms.Position = 0;
string response = (new StreamReader(ms).ReadToEnd());
ms.Close();
Console.WriteLine("GET places response " + response);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return;
}
//POST to places resource
try
{
client.Headers.Add("Accept", "application/json");
client.Headers.Add("Content-Type", "application/json");
DataContractJsonSerializer placesSerializer = new DataContractJsonSerializer(typeof(Place));
Place place = new Place { name = "test place", latitude = 0, longitude = 0 };
MemoryStream ms = new MemoryStream();
placesSerializer.WriteObject(ms, place);
byte[] json = ms.ToArray();
ms.Close();
string jsonString = Encoding.UTF8.GetString(json, 0, json.Length);
client.Encoding = System.Text.Encoding.UTF8;
string response = client.UploadString(urlBase + "places/" + "?api_key=" + api_key, jsonString);
Console.WriteLine("POST places response " + response);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return;
}
}
}
public class Place
{
[JsonProperty("url")]
public string url { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("latitude")]
public float latitude { get; set; }
[JsonProperty("longitude")]
public float longitude { get; set; }
}
public class Page<T>
{
[JsonProperty("count")]
public int count { get; set; }
[JsonProperty("next")]
public string next { get; set; }
[JsonProperty("previous")]
public string previous { get; set; }
[JsonProperty("results")]
public List<T> results { get; set; }
}
}

Categories