Httpclient Xamarin Forms call not working in Android - xamarin.forms

I am having a strange problem that occurs when debugging the xamarin forms app in android physical device.
The app goes to break mode and here is the output i receive:
Mono.Android[0xd6be8960] -> System[0xd6be9680]: 14
11-24 23:44:44.098 I/Choreographer(18685): Skipped 930 frames! The application may be doing too much work on its main thread.
Thread started: <Thread Pool> #8
Thread started: <Thread Pool> #9
11-24 23:44:44.807 D/Mono (18685): Assembly Ref addref Mono.Security[0xc17989e0] -> System[0xd6be9680]: 15
Thread started: <Thread Pool> #10
An unhandled exception occured.
I tried many solutions such as allowing the network access in the app, made sure that the all needed packages are there such as:
Microsoft.Bcl.Build
Microsoft.net.HTTP
Newtonsoft.json
This is my code which works fine in UWP
var request = new HttpRequestMessage();
request.RequestUri = new Uri("https://jsonplaceholder.typicode.com/users");
request.Method = HttpMethod.Get;
request.Headers.Add("Accept", "application/json");
var client = new HttpClient();
HttpResponseMessage response = await client.SendAsync(request);
HttpContent content = response.Content;
var statusCode = response.StatusCode;
var json = await content.ReadAsStringAsync();
EDIT: I am getting 2 main errors in the device log:
[ERROR] FATAL UNHANDED EXCEPTION: System.Net.HttpRequestException:An error occurred while sending the request --> System.Net.WebException:Error:SecureChannelFailure(The authentication or decryption has failed)

Change the default SSL/TLS implementation in Xamarin.Android.
Go to Android Project settings->Android Options->Advanced->SSL/TLS implementation and set it to Native TLS 1.2+

On some Cases you need to chagne the HttpClient Implementation to be AndroidClientHandler instead of Default as the following:

Related

Uploading files to SharePoint OnPremise 2016 using .NET Core 5.0 and HttpWebRequest C#

SharePoint CSOM is not supported in .NET Core 5.0, so I'm trying to use HttpWebRequest to upload files to SharePoint 2016 on-premise.
This code sample shown here works in .NET 4.7, however it throws errors when run on .NET Core.
public async Task<string> UploadFile(string folderName, string fileName, byte[] file)
{
// Url to upload file
string resourceUrl = _sharePointUrl + $"/_api/web/GetFolderByServerRelativeUrl('/opportunity/{folderName}')/Files/add(url='{fileName}',overwrite=true)";
HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
wreq.Credentials = _credentials;
wreq.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
// Get formdigest value from site
wreq.Headers.Add("X-RequestDigest", GetFormDigest());
wreq.Headers.Add("binaryStringRequestBody", "true");
wreq.Method = "POST";
wreq.Accept = "application/json; odata=verbose";
wreq.ContentLength = file.Length;
wreq.Timeout = 100000;
await wreq.GetRequestStream().WriteAsync(file, 0, file.Length);
HttpWebResponse response = (HttpWebResponse)wreq.GetResponse();
return response.StatusDescription;
}
Errors are listed below. The errors are happening on the
HttpWebResponse response = (HttpWebResponse)wreq.GetResponse();
line.
System.AggregateException: 'One or more errors occurred. (An error occurred while sending the request.)'
Inner Exception 1: WebException: An error occurred while sending the request.
Inner Exception 2: HttpRequestException: An error occurred while sending the request.
Inner Exception 3: IOException: The response ended prematurely.
What am I missing?
Does the HttpWebRequest in .NET Core work differently than the .NET framework version?
Do I need to use different headers or configure the request object differently?
Thanks in advance.

API call returns 408 (Your POST request is not being received quickly enough. Please retry) but works fine with Postman and ajax

Calling an external API from asp.net core 2.2 with framework 4.6.1 using HttpClient always returns 408 with an error message Your POST request is not being received quickly enough. Please retry but same code works fine with pure asp.net 2.2. The external API also works fine when I use Postman or ajax.
Here is the API call -
using (var client = _httpClientFactory.CreateClient())
{
client.BaseAddress = new Uri("https://example.com/authenticate");
var response = await client.PostAsync(string.Empty, new JsonContent(data));
var content = await response.Content.ReadAsStringAsync();
return StatusCode((int)response.StatusCode, content);
}

ServiceBus in Microsoft Orleans, OrleansPrepareFailedException exception

I'm using Microsoft Orleans for .net Core and I'm trying to receive ServiceBus messages and process them as fast as I can.
With parameter MaxConcurrentCalls set to 2 everything works fine. But with set 10 or 30 it throws an exception:
OrleansPrepareFailedException, Transaction 50038 aborted because Prepare phase did not succeed
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MichalBialecki.com.OrleansCore.AccountTransfer.Client.Program.<>c__DisplayClass4_0.<b__0>d.MoveNext()
code looks like this:
subscriptionClient.RegisterMessageHandler(
async (message, token) =>
{
var messageJson = Encoding.UTF8.GetString(message.Body);
var updateMessage = JsonConvert.DeserializeObject<AccountTransferMessage>(messageJson);
await client.GetGrain<IAccountGrain>(updateMessage.From).Withdraw(updateMessage.Amount);
await client.GetGrain<IAccountGrain>(updateMessage.To).Deposit(updateMessage.Amount);
await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
},
new MessageHandlerOptions(async args => Console.WriteLine(args.Exception + ", stack trace: " + args.Exception.StackTrace))
{ MaxConcurrentCalls = 30, AutoComplete = false });
My scenario is very simple. It handles account transfer messages and after updating account (Grain) balance, it sends message to a different ServiceBus topic. Currently on my local machine it can handel around 1500 messages per minute, but it feels kinda slow.
The problem was mishandling the state in a grain class. I used transactional state and persistent state at the same time, where I should have used only one. I managed to get my code running correctly for Orleans version 2.0 and .Net Core application.
Here is my code: https://github.com/mikuam/orleans-core-example
And here is my blog post about adding persistent storage to Microsoft Orleans in .Net Core: http://www.michalbialecki.com/2018/04/03/add-cosmosdb-persistent-storage-to-microsoft-orleans-in-net-core/

why main thread don't return response immediately when I call async method?

I have write a test code in a new web application as below:
public ActionResult Index()
{
Logger.Write("start Index,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
MyMethodAsync(System.Web.HttpContext.Current.Request);//no await and has warning
Logger.Write("end Index,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
return View();
}
private async Task MyMethodAsync(HttpRequest request)
{
Logger.Write("start MyMethodAsync,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
await SomeMethodAsync(request);
Logger.Write("end MyMethodAsync,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
}
And here is the log:
2017-11-15 19:55:31.904 start Index,threadId:35
2017-11-15 19:55:31.919 start MyMethodAsync,threadId:35
2017-11-15 19:55:31.919 end Index,threadId:35
2017-11-15 19:55:53.324 end MyMethodAsync,threadId:46
The client brower will receive response at about 2017-11-15 19:55:32 and it accord with my understanding. In my actual project production environment,it writes the same log as above, However, the client brower received response in about 22 seconds later at about 2017-11-15 19:55:54. It seems that even the main thread complete the work, the main thread do not return the response until the new thread complete the work.
I have debug this problem serveral days. Could you help me please?
async-await does not change the HTTP protocol. The request goes to the server, the server produces a response and sends it to the client.
It just changes how ASP.NET requests are processed by ASP.NET.
And it doesn't make the request handling faster. Quite the contrary.
But it does use more thread pool threads and makes the server more responsive under heavy load.

Windows 10 Universal App - Package doesn't work normally as debug mode

public async Task<List<Tip>> GetTips()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://APIURL ");
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse res = await request.GetResponseAsync();
StreamReader sr = new StreamReader(res.GetResponseStream());
string result = sr.ReadToEnd();
List<Tip> tips = JsonConvert.DeserializeObject<List<Tip>>(result);
return tips;
}
I am working on a project which need to consume an enterprise Web API(Https) and display the data on Win 10 live tile, it’s an UWP application.
But I found it only works when I ran it in IDE(Visual Studio 2015 debug mode) .
When I created a package for this app and run it by powershell for installation, request.GetResponseAsync method throws exception “The login request was denied”.
I tried to check Enterprise Authentication and Private Networks(Client & Server) options in Package.appxmanifest. But there was no effect.
Any idea how to make it work normally? Thanks.

Resources