download in async httpclient xml file - xamarin

I want to download an xml file in asynchronous and let the user know that the file is downloading while it does other moves in the app
public static async Task<string> GetRequestAsync(string url)
{
using (var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue })
{
HttpResponseMessage response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
with this command did not work successfully

Related

post request not working in xamarin forms

im trying to send a HTTP POST request from xamarin forms app to a webservice API on ASP.NET MVC, However, when i do it, i get status code 500 back from the server. I suspect it has something to do with the values in sending to API but i have not been able to figure it out.
Anyhelp is much appeciated
here is the
WEB API CODE
public void LogInFromMobile([FromBody] List<Creds> detail)
{
......
}
here is the
XAMARIN-FORMS APP CODE
public async void Button_Clicked(object sender, EventArgs e)
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Creds cr = new Creds();
cr.username = user.Text;
cr.password = pass.Text;
List<Creds> cred = new List<Creds>();
cred.Add(cr);
string url = #"http://IPHERE/LoginWebService.asmx/LogInFromMobile";
string json = JsonConvert.SerializeObject(cred);
HttpContent content = new StringContent(json);
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
await DisplayAlert("Alert", "Success", "Ok");
return;
}
else
{
await DisplayAlert("Alert", "Error", "Ok");
return;
}
}
}
catch(Exception ex)
{
await DisplayAlert("", ex.Message, "ok");
}
}

Cloud blob container uploading file working fine locally, but not working after hosting application

I don't know why getting the problem, earlier its working fine at local environment as well as at hosting environment. But now getting issue and getting the blank cloudBlockBlob.Uri.AbsoluteUri as well as image is not uploading at container.
private async Task<string> UploadToAzureAsync(IFormFile file)
{
try
{
var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
var cloudBlobContainer = cloudBlobClient.GetContainerReference("filecontainer");
if (await cloudBlobContainer.CreateIfNotExistsAsync())
{
await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions()
{
PublicAccess = BlobContainerPublicAccessType.Off
});
}
var fileName = file.FileName.Split("\\").LastOrDefault().Split('/').LastOrDefault();
var cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
cloudBlockBlob.Properties.ContentType = file.ContentType;
await cloudBlockBlob.UploadFromStreamAsync(file.OpenReadStream());
var url = cloudBlockBlob.Uri.AbsoluteUri;
return url ?? string.Empty;
}
catch (Exception)
{
return string.Empty;
}
}
Can anyone help me on this.
Thanks in advance!
You may try the below code:
[HttpPost]
public async Task UploadFileAsync([FromForm] IFormFile file)
{
CloudStorageAccount storageAccount = null;
if(CloudStorageAccount.TryParse(_configuration.GetConnectionString("StorageAccount"), out storageAccount))
{
var client = storageAccount.CreateCloudBlobClient();
var container = client.GetContainerReference("fileupload");
await container.CreateIfNotExistsAsync();
var blob = await container.GetBlobReferenceFromServerAsync(file.FileName);
await blob.UploadFromStreamAsync(file.OpenReadStream());
return Ok(blob.Uri);
}
return StatusCode(StatusCodes.Status500InternalServerError);
}

Why is this RestSharp file upload not working?

I have this ASP.NET Core Web API action method:
[HttpPost("PostDir")]
[DisableRequestSizeLimit]
public async Task<IActionResult> PostDir(string serverPath)
{
// Do stuff with file.
return Ok();
}
I don't know what to do with the file I am trying to upload or what it looks like in the action method because the action is never invoked: the client code below gets a 404 response:
public async Task PostDirAsync(string localDirPath, string serverDir)
{
var sourcePath = Path.Combine("Temp", Guid.NewGuid() + ".zip");
ZipFile.CreateFromDirectory(localDirPath, sourcePath, CompressionLevel.Fastest, true);
var rest = new RestClient("http://localhost:50424/api/File/PostDir");
var req = new RestRequest(Method.POST);
req.AddFile(Path.GetFileName(sourcePath), sourcePath);
req.AddHeader("Content-Type", "multipart/form-data");
req.AddParameter("serverPath", serverDir, ParameterType.QueryString);
var resp = rest.Execute(req);
}
What am I missing or doing wrong?

How to call the async Task Function?

My code for class AllWebApiOperations is
public AllWebApiOperations(string apiURI)
{
client = new HttpClient();
client.BaseAddress = new Uri(apiURI);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<string> GetDataAsync(string route)
{
string result= string.Empty;
HttpResponseMessage response = await client.GetAsync(route);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsAsync<string>();
}
return result;
}
I'm calling this in button click
string apiURI = #"http://localhost:35487/";
private async void btnCallWebApi_Click(object sender, EventArgs e)
{
AllWebApiOperations op = new AllWebApiOperations(apiURI);
var result = await op.GetDataAsync(apiURI + "api/products/");
Console.WriteLine(result);
}
My code web api is working properly as shown below
But I'm getting error while calling the function as shown below
I'm not sure why I'm getting this error, tried googling but can't find resolution.
Found the answer:
public async Task<string> GetDataAsync(string route)
{
string result= string.Empty;
HttpResponseMessage response = await client.GetAsync(route);
if (response.IsSuccessStatusCode)
{
**result = await response.Content.ReadAsAsync<string>();**
}
return result;
}
I should be using
**result = await response.Content.ReadAsStringAsync();**

Modify Request.Content in WebApi DelegatingHandler

I need to modify requested content to replace some characters (because of some unicode problems). Previously (in ASP.NET MVC), I did this with HttpModules; but in WebApi, it seems that I should DelegatingHandler but it is totally different.
How can I modify request.Content inside the SendAsync method? I need something like this:
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var s = await request.Content.ReadAsStringAsync();
// do some modification on "s"
s= s.replace("x","y");
request.Content = new StringContent(s);
var response = await base.SendAsync(request, cancellationToken);
return response;
}
In the code above, I think I should check the request's content type and then decide what to do. If yes, which checks should I do?
I did something like this in SendAsync. Although it is not a comprehensive solution, it works:
//first : correct the URI (querysting data) first
request.RequestUri = new Uri(Correcr(request.RequestUri.ToString()));
var contentType = request.Content.Headers.ContentType;
if (contentType != null)
{
if (contentType.MediaType == "application/x-www-form-urlencoded")//post,put,... & other non-json requests
{
var formData = await request.Content.ReadAsFormDataAsync();
request.Content = new FormUrlEncodedContent(Correct(formData));
}
else if (contentType.MediaType == "multipart/form-data")//file upload , so ignre it
{
var formData = await request.Content.ReadAsFormDataAsync();
request.Content = new FormUrlEncodedContent(Correct(formData));
}
else if (contentType.MediaType == "application/json")//json request
{
var oldHeaders = request.Content.Headers;
var formData = await request.Content.ReadAsStringAsync();
request.Content = new StringContent(Correct(formData));
ReplaceHeaders(request.Content.Headers, oldHeaders);
}
else
throw new Exception("Implement It!");
}
return await base.SendAsync(request, cancellationToken);
and this helper function:
private void ReplaceHeaders(HttpContentHeaders currentHeaders, HttpContentHeaders oldHeaders)
{
currentHeaders.Clear();
foreach (var item in oldHeaders)
currentHeaders.Add(item.Key, item.Value);
}

Resources