How to connect WPF(C#) app to a Node.js API route? - c#

So I have a WPF application that I want to connect to a RESTful API made with Node.js express server, I have the API on my local pc and the WPF app as well and I want to connect the WPF app to a route in the API called "meals", is there a way to do that?

Yes there is a way to do that
the below code sends a post and a get requests to the API just change the port to whatever port you're running your API on
private static readonly HttpClient client = new HttpClient();
public async void SendPostRequestToAPI(){
// POST REQUEST
try
{
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://localhost:port", content);
var responseString = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
// GET REQUEST
try
{
var responseString = await client.GetStringAsync("http://localhost:port");
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
}
don't forget to use the following directive
using System.Net.Http;

Related

HttpClient behavior in Xamarin Android APK

I have an Xamarin.Android APK.
When installed in a tablet locally at the company, it works perfectly. I already installed it in about 3 tablets and it is working as expected.
The problem is when I send the APK to be installed in a tablet at my customer (it is located in another state), it seems that the HttpClient is not working as expected.
To test it, I'm showing a Toast with the response of the request. It should return the Role of the user.
Locally, it returns the Role as expected. In the customer, it returns an empty string. No error is thrown locally and in the server as well.
Searching on the web, I found that this could be related with a deadlock. So, I put a .ConfigureAwait(false) on my Get method:
public static async Task<string> CheckLoginAsync(string cpf, string password)
{
try
{
_client = new HttpClient();
_client.BaseAddress = new Uri(ApiUrls.Base);
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Vault.CreateToken(cpf));
_client.Timeout = TimeSpan.FromSeconds(Constants.CheckLoginAsyncTimeout);
var url = $"{ApiUrls.UserLoginApp}/{cpf}/{password}";
var result = await _client.GetAsync(url).ConfigureAwait(false);
if (result.IsSuccessStatusCode)
{
var response = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<string>(response);
}
return null;
}
catch (TaskCanceledException tcex)
{
throw new TaskCanceledException("TaskCanceled", tcex.InnerException);
}
catch (Exception ex)
{
throw new LoginUnsuccessfulException("LoginFailedDB", ex.InnerException);
}
}
After that, it started working and the error started in another method. I try to do the same thing using the .ConfigureAwait(false) but the response is coming null:
private async Task<AppBaseData> GetAppBaseDataAsync(string username)
{
try
{
_client = new HttpClient();
_client.BaseAddress = new Uri(ApiUrls.Base);
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Vault.CreateToken(username));
_client.Timeout = TimeSpan.FromSeconds(Constants.LoadBaseDataAsyncTimeout);
var url = $"{ApiUrls.SupportAppBaseData}/{username}";
var result = await _client.GetAsync(url).ConfigureAwait(false);
if (result.IsSuccessStatusCode)
{
var response = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<AppBaseData>(response);
}
return null;
}
catch (TaskCanceledException ex)
{
throw new TaskCanceledException("TaskCanceled", ex.InnerException);
}
catch (Exception ex)
{
throw new DataNotReadedException("BaseDataDB", ex.InnerException);
}
}
I have no idea of what is causing this problem since it works with the same APK locally and in the customer is not working. The customer network have already been changed to a wifi tethering and the behavior still continues.
The above methods are inside a Task.Run().

Xamarin.Forms HTTP Post to Web Service - 404 Error

Sorry if this question has been asked already but I can not seem to find one that relates to my issue. I have a web service built using C# Asp.Net Web API, here I have the following POST method:
[HttpPost]
[Route("AddLocation")]
public void PostLocation(Locations model)
{
using (Entities db = new Entities())
{
C_btblFALocation newLocation = new C_btblFALocation()
{
cLocationCode = model.Code,
cLocationDesc = model.Description
};
db.C_btblFALocation.Add(newLocation);
db.SaveChanges();
}
}
In my Xamarin.Forms project I have my Rest Service Class:
public async Task SaveLocationAsync(Locations item)
{
var uri = new Uri(string.Format(Constants.LocationSaveRestUrl));
try
{
var json = JsonConvert.SerializeObject(item);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(#" Location successfully added.");
}
else
{
Debug.WriteLine(#" Oops, there seems to be a problem.");
}
}
catch (Exception ex)
{
Debug.WriteLine(#" ERROR {0}", ex.Message);
}
}
And my URL is set in my Constants class:
public static string LocationSaveRestUrl = "http://172.16.124.18/ArceusService/api/Assets/AddLocation/";
The problem is I keep getting a 404 error. I have tried every way I can think of to set the URL but no luck. The data seems to be passed through fine from debugging but I don't know how the URL should be for a POST method?
Thanks for any help!
How is your client variable declared? Usually you set a BaseAddress and in your Get/PostAsync you only set the actual resource URI.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}

How can I use the access token to get a list of projects from a website in c#?

I am trying to create a C# console application to download project details from a website which supports REST OAuth 2.0. How do I make a request/response call to the website using the Access Token?
Here is my code:
public string token = "4bjskfa2-b37d-6244-8413-3358b18c91b6";
public async Task GetProjectsAsync()
{
try
{
HttpClient client = new HttpClient();
var projects = "https://app.rakenapp.com/api/v2/projects?" + token;
client.CancelPendingRequests();
HttpResponseMessage output = await client.GetAsync(projects);
if (output.IsSuccessStatusCode)
{
string response = await output.Content.ReadAsStringAsync();
project proj = JsonConvert.DeserializeObject<project>(response);
if (proj != null)
{
Console.WriteLine(proj.name); // You will get the projects here.
}
}
}
catch (Exception ex)
{
//catching the exception
}
}
you need to add a header to your request:
string url = "https://app.rakenapp.com/api/v2/projects";
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorizationToken);
HttpResponseMessage response = await httpClient.GetAsync(url);
var contents = await response.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<project>.contents);
return model;
}

Handling a bool Response using HttpClient windows phone

I'm developing a windows phone app that generates a QRcode, when the code is scanned, then response has to come back as true, please look at my code and advice as i'm getting a false response even thought the other app has scanned the code.
private async void queryQRCode(string code)
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var authorisationHeader = GenerateBasicAuthorizationParameter("merchant-" + ObjUserData.MerchantId, ObjUserData.PassApiPassword); // 12ED5A5F2B38ACCBE437731BB2AC1F30 35A09A5C2AE97F055A0FDAEDA5A7093D
//Console.WriteLine ("http content - " + httpContent.ReadAsStringAsync().Result);
HttpResponseMessage httpResponse = new HttpResponseMessage();
// Do the actual request and await the response
client.DefaultRequestHeaders.Authorization = authorisationHeader;
var f = QueryCodeUrl + "/" + code + "/scanned";
httpResponse = await client.GetAsync(new Uri(f));
//httpResponse.EnsureSuccessStatusCode();
// If the response contains content we want to read it!
if (httpResponse.Content != null)
{
var responseContent = await httpResponse.Content.ReadAsStringAsync();
// From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
Debug.WriteLine(responseContent);
try
{
ScannedCodeResult res = JsonConvert.DeserializeObject<ScannedCodeResult>(responseContent);
Debug.WriteLine("RETURNED RESPONSE IS "+res.scanned.ToString());
if (res.scanned == false)
{
queryQRCode(code);
}
else
{
Debug.WriteLine("YAY!!!! The User has successfully scanned the application");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + ex.StackTrace);
}
// var qrResponse = (VcsMasterPassService.MasterPassModels.QRCodeResponse)JsonConvert.DeserializeObject (responseContent, typeof(VcsMasterPassService.MasterPassModels.QRCodeResponse));
// CreateQRCodeImage (qrResponse.code);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + ex.StackTrace);
}
finally
{
}
}
Above problem is caused by windows phone caching.

How to know when a A-Synchronous REST call in Windows 8.1 Mobile Library has been completed?

Background::
I am creating a Windows 8.1 Mobile SDK that will have a License Manager(LM) Module.
The client will have to Call The License Manager in their code once whenever the application starts.
The license manager will register the client and send a set of JSON Response that will be stored on the device for future validations.
The License Manager function makes REST Calls to our server.
Problem::
What will be the best place within a Windows 8.1 application to call the License Manager Function provided in the SDK?
How to make the call to the LM Synchronous, so that the client gets a chance to handle responses in case the license is not validated. Or before the client calls the other APIs included in the SDK.
Work Done::
I have created the LM function and returns the desired results.
Created a Demo App that calls the LM on a button click.
Please find the sample code below,
Client Application:
private async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
var x = await sdk.InitializeAsync("xxxxxxx-xxx-xxxx");
//Calling an API included in the SDK
APIResponse res = await laas.Function1_Async(par1, par2);
msg.Text = x.ToString();
}
catch (Exception ex)
{
}
}
SDK:
public async Task<int> InitializeAsync(string apiKey)
{
int status = 0;
if (!_isInitialized)
{
status = await GetLicenseInfo(localSettings);
}
this._isInitialized = true;
return status;
}
private async Task<int> GetLicenseInfo(Windows.Storage.ApplicationDataContainer localSettings)
{
APIResponse res = new APIResponse();
res.Status = -10;
res.Message = "Unknown Error!";
// Create the web request
StringBuilder data = new StringBuilder();
data.Append(*JSON String*);
string Uri = _regisUrl;
using (HttpClient client = new HttpClient())
{
Uri url = new Uri(Uri);
StringContent content = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Host = url.Host;
try
{
using (HttpResponseMessage response = await client.PostAsync(url, content))
{
if (response.IsSuccessStatusCode)
{
res = JsonConvert.DeserializeObject<APIResponse>(await response.Content.ReadAsStringAsync());
//Check that the Response is Success
if (res.Status == 1)
localSettings.Values["IsDeviceRegistered"] = StringCipher.Encrypt("registered");
}
}
}
catch
{
}
}
return res.Status;
}
Any Help would be appreciated.
This will change your code to be Synchronous...
Task<int> t = sdk.InitializeAsync("xxxxxxx-xxx-xxxx");
t.Wait();
var myvalue = t.Result;
.....

Categories

Resources