When i call
public static async Task<User> GetUserAsync(string name)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Resource.RestBaseURI);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("APIKey", Resource.APIKey);
var responseMessage = await client.GetAsync($"api/Users/{name}");
if (!responseMessage.IsSuccessStatusCode)
throw new HttpResponseException(responseMessage.StatusCode);
var userDb = responseMessage.Content.ReadAsAsync<UserDb>().Result;
if (userDb == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
var user = DbClientConverter.UserDbToUser(userDb);
user.RefuelEntityList = await RefuelEntityCommunicator.GetRefuelEntitiesAsync(user);
return user;
}
}
catch (HttpResponseException httpResponseException)
{
throw new HttpResponseException(httpResponseException.Response.StatusCode);
}
catch (HttpRequestException httpRequestException)
{
throw new HttpRequestException(httpRequestException.Message, httpRequestException);
}
catch (Exception exception)
{
throw new Exception(exception.Message, exception);
}
}
on Xamarin Android
the await client.GetAsync in line 12 causes a exception:
"The type initializer for 'System.Net.Http.FormattingUtilities' threw an exception"
the same code used in a WPF Application is no problem.
Any ideas how to fix this?
Solution 1: It seems that some dependencies are broken. Have you tried to reinstall NuGet package?
From the package manager, run Update-Package Microsoft.AspNet.WebApi -reinstall.
Solution 2: use NuGet to install the Web API 2.1 WebHost.
Solution 3: Install-Package Microsoft.AspNet.WebApi -Version 5.x.x
https://forums.xamarin.com/discussion/85204/problem-is-could-not-load-type-system-net-http-formattingutilities
Instead of
client.DefaultRequestHeaders.Add("APIKey", Resource.APIKey);
Use
client.DefaultRequestHeaders.TryAddWithoutValidation("APIKey", Resource.APIKey);
This is becuase "APIKey" here is a non-standard custom header
I guess it's a problem with ReadAsAsync extension method.
See here for a custom solution.
Related
I'm trying to authenticate an EWS application by using OAuth. Unfortunatelly, I get a NullReferenceException when calling FindFolders() (code below). But, what is interensting - not always, just sametimes. Is anyone facing this issue too and can help me with this?
This is code you should be interested in:
var cca = ConfidentialClientApplicationBuilder
.Create("hidden")
.WithClientSecret("hidden")
.WithTenantId("hidden")
.WithRedirectUri("http://localhost")
.Build();
var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
try
{
var authResult = await cca.AcquireTokenForClient(ewsScopes)
.ExecuteAsync();
// Configure the ExchangeService with the access token
var ewsClient = new ExchangeService();
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
ewsClient.ImpersonatedUserId =
new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "mail");
//Include x-anchormailbox header
ewsClient.HttpHeaders.Add("X-AnchorMailbox", "mail");
// Make an EWS call
var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(15));
foreach (var folder in folders)
{
Console.WriteLine(folder.DisplayName);
}
}
catch (MsalException ex)
{
Console.WriteLine($"Error acquiring access token: {ex}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex}");
}
What I've already tried is cloning this repository https://github.com/pawelFelcyn/ews-managed-api instead of installing nuget package. And it helped, as I could find where the exception is being thrown. It's in ServiceRequestBase.WrapStream(), becuase contentEncoding is null (you can see this on github - the file is in folder Core/Requests). I've just added a simple nullcheck like this:
if (contentEncoding is null)
{
return responseStream;
}
But this brings some other problems. As I understood, version of this library on github does not support somethig connected with Xml, what I need. Can anyone help me, please?
I want to deploy and install an .appxbundle with c# on a UWP(IoT) - Device.
The REST-API documentation is on this site.
My code is
public async static Task<bool> UploadApp(string ip, Stream upload, string fileName)
{
try
{
if (http == null)
GetHttp();
HttpContent content = new StreamContent(upload);
var param = new Dictionary<string, string> {
{ "package", fileName}
};
var urlparam = new FormUrlEncodedContent(param);
var urlVar = await urlparam.ReadAsStringAsync();
var response = await http.PostAsync(String.Format("http://{0}:8080/api/app/packagemanager/package?{1}", ip, urlVar), content);
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
The code is not working. I get an "Bad request" Error after I send it and I don't know what to change. Could someone help me?
EDIT: The message I get is "Missing .appx (or .eappx) or .appinstaller file in uploaded files". I can deploy and install the package with ARC as "multipart/form-data".
I'm making Xamarin.Forms app which should get JSON from api and then allow to display it. My code so far:
public async void jsonDownload()
{
connect();
await downloadData();
}
public void connect()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
}
public async Task<List<Jsonclass>> downloadData()
{
String url = "https://my-json-server.typicode.com/kgbzoma/TestJsonFile/all";
var uri = new Uri(string.Format(url, string.Empty));
try
{
var response = await client.GetAsync(uri).ConfigureAwait(false);
response.EnsureSuccessStatusCode(); //NEVER GET HERE
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
List = JsonConvert.DeserializeObject<List<Jsonclass>>(content);
}catch (Exception ex)
{
Debug.WriteLine(#" Error {0}", ex.Message);
}
return List;
}
Problem is that code don't even go to response.EnsureSuccessStatusCode(); so my list of objects is empty. On UWP version it's working without any problems.
Here i'm gettin exception: System.Net.Http.HttpRequestException with message An error occurred while sending the request.
SecureChannelFailure (The authentication or decryption has failed.)
or
System.Net.WebException: Error: TrustFailure
or
Mono.Security.Protocol.Tls.TlsException: Invalid certificate received from server.
By default, Xamarin.Android uses the older Mono Managed HttpClient handler that does not support TLS 1.2.
Open your Xamarin.Android project settings, goto Build / Android Build / General and use the AndroidClientHandler.
This will add the following MSBuild properties directly to your .csproj
<AndroidHttpClientHandlerType>Xamarin.Android.Net.AndroidClientHandler</AndroidHttpClientHandlerType>
<AndroidTlsProvider>btls</AndroidTlsProvider>
Note: If doing this manually in the .csproj, you need to add them to the debug AND release PropertyGroup.
Or programmatically set the HttpClient to use it:
client = new HttpClient(new AndroidClientHandler());
Note: You should be looking at the InnerException for these types of errors
catch (Exception ex)
{
Console.WriteLine(#" Error {0}", ex.Message);
Console.WriteLine(#" Error {0}", ex.InnerException?.Message);
}
The view 'Search' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Search.aspx
~/Views/Home/Search.ascx
~/Views/Shared/Search.aspx
~/Views/Shared/Search.ascx
~/Views/Home/Search.cshtml
~/Views/Home/Search.vbhtml
~/Views/Shared/Search.cshtml
~/Views/Shared/Search.vbhtml
I am working on a basic web application that reads data from an api. When I run the solution and try to access the view referenced by this controller from the code below, I get this error. I have narrowed it down to being the GetAsync line of code. This works on windows however does not work on my Mac.
From what I can find, the cross platform .net framework Mono, used by visual studio on OSX, does not support GetAsync. What are my options if I want to develop/test this on my Mac but also deploy on a azure server?
public async Task<ActionResult> Search(string ticker)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(demoapiurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage res = await client.GetAsync(string.Format("{0}&symbol={1}&apikey={2}", apiurl, ticker, apikey));
if (res.IsSuccessStatusCode)
{
var accResponse = res.Content.ReadAsStringAsync().Result;
var quotes = GettingStarted.FromJson(accResponse);
GettingStarted allquotes = JsonConvert.DeserializeObject<GettingStarted>(accResponse);
return View(allquotes);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception Message: " + ex.Message);
}
}
return View();
}
I started to learn Xamarin to develop application for iOS, Android and Windows Phone.
Seems a simple question but I don't know how to proceed with Xamarin.
I have the following lines of code:
public async Task<List<MyData>> GetItemsAsync()
{
HttpClient client = new HttpClient();
try {
string result = await client.GetStringAsync( "https://jsonplaceholder.typicode.com/posts/1" );
if(!string.IsNullOrWhiteSpace(result)) {
}
} catch( Exception ex ) {
return await Task.FromResult(new List<MyData>(0));
} finally {
client.Dispose(); //of course, I can use `using`
}
return await Task.FromResult(new List<MyData>(0));
}
When debug in Visual Studio Android Emulator(VisualStudio_android-23_x86_phone (Android 6.0 - API 23)), the line where starts with string result is stuck, nothing happens, no exception is thrown. I cannot use F10 in Visual Studio to inspect.
Also, I cannot use WebClient because System.Net doesn't include it.
Edit: If I remove await then I receive a general exception:
Where is my mistake ?
For those who meet the error:
Error: SecureChannelFailure (The authentication or decryption has failed.)
Please use specific handler for Android:
using (HttpClient myClient = new HttpClient(new AndroidClientHandler())) { }
or for iOS:
using(HttpClient myClient = new HttpClient(new CFNetworkHandler())) {}
References:
https://developer.xamarin.com/guides/cross-platform/macios/http-stack/
https://developer.xamarin.com/guides/android/application_fundamentals/http-stack/