So, I am using postman to test this post method and its working as expected when i am posting/uploading small size file, close to 1MB, but its throwing error when uploading bigger file, 8MB+.
Line where its throwing error:-
await Request.Form.Files[0].CopyToAsync(ms).ConfigureAwait(false);
Error:-
Request.Form.Files = 'Request.Form.Files' threw an exception of type 'System.InvalidOperationException'
Its a Net Core 3.1 Application.
Adding the complete code if anyone want to replicate it.
[HttpPost("File")]
[SAPolicy(SAPolicy.Admin, SAPolicy.ConsumerApp)]
public async Task<IActionResult> PostFile()
{
FileContractRequest fileContract = null;
try
{
if (Request.ContentLength > 0)
{
using (var ms = new MemoryStream())
{
await Request.Form.Files[0].CopyToAsync(ms).ConfigureAwait(false);
var data = ms.ToArray();
var newFileContract = new FileContractRequest()
{
ContentType = Request.Form.Files[0].ContentType,
Name = Path.GetFileName(Request.Form.Files[0].FileName),
Length = data.LongLength.ToString(),
CreationDate = DateTime.UtcNow,
Data = data
};
fileContract = newFileContract;
}
}
else
{
return new StandardResponse<FileContractResponse>(HttpStatusCode.NotAcceptable, null).Result;
}
}
catch (Exception ex)
{
throw ex;
}
var result = await _fileService.PostFile(fileContract).ConfigureAwait(false);
return new StandardResponse<FileContractResponse>(HttpStatusCode.OK, result).Result;
}
I looked in to couple of different blogs and could not find anything that helps me with my problem. Any help to fix this ? what i am missing here ?
Edit 1:-
Related
I am running .net application which fetches data from SQL database and displays on the form screen.
When I run the application in UAT, it works fine but in PROD, I am getting below exception
Query run fine on database but I am getting this exception.
PricingClinet.cs -
public async Task<SaveResponse> SaveAsync(Sheet sheet)
{
SaveResponse result = null;
try
{
var response = await _client.PostAsJsonAsync("Pricing/Save", sheet);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var jsonResult = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<SaveResponse>(jsonResult);
}
else
{
var errorMessage = string.Format("StatusCode: {0}\r\n{1}", response.StatusCode.ToString(), response.ReasonPhrase);
Logger.LogError(errorMessage);
result = new SaveResponse()
{
Success = false,
ErrorMessage = errorMessage
};
}
}
catch (Exception error)
{
Logger.LogError(error);
result = new SaveResponse()
{
Success = false,
ErrorMessage = ExceptionManager.RenderErrorMessage(error)
};
}
return result;
}
This error is hapenning in PROD only, not in UAT.
This is a timeout in a await _client.PostAsJsonAsync.
You need to confirm that your PROD configuration is correct e.g. points to the correct server.
If your configuration is correct then you need to either increase the timeout
(e.g. _client.Timeout = ...) or make the remote call faster (if it's in your control obviously).
I'm reading data from remote MongoDB realm which syncs to my local realm, but it seems I can't read from my local realm after sync.
This is the message I get when I try to read from my local realm:
Unable to open a realm at path '/data/user/0/com.companyname.appname/files/default.realm': Incompatible histories. Expected a Realm with no or in-realm history, but found history type 3 Path:Exception backtrace:\n<backtrace not supported on this platform>.
Here is my code:
private async Task<Realm> OpenRealm()
{
try
{
var user = App.realmApp.CurrentUser;
//if user is not logged on yet log on the user and sync
if (user == null)
{
var CurrentUser = await App.realmApp.LogInAsync(Credentials.Anonymous());
var config = new SyncConfiguration("Hirschs", CurrentUser);
_realm = await Realm.GetInstanceAsync(config);
return _realm;
}
else
{
return _realm = Realm.GetInstance();
}
}
catch (Exception ex)
{
await UserDialogs.Instance.AlertAsync(new AlertConfig
{
Title = "An error has occurred",
Message = $"An error occurred while trying to open the Realm: {ex.Message}"
});
// Try again
return await OpenRealm();
}
}
The problem here is that you are trying to create a new local realm in the same path where the synced realm already is.
I suppose that you would like to open the same realm synchronously (that is necessary if the device is offline). In this case you would just need to use the same configuration for both the sync and async calls, as reported in the documentation here.
You could do something like:
private async Task<Realm> OpenRealm()
{
try
{
var currentUser = App.realmApp.CurrentUser;
if (currentUser == null)
{
var currentUser = await App.realmApp.LogInAsync(Credentials.Anonymous());
var config = new SyncConfiguration("Hirschs", currentUser);
_realm = await Realm.GetInstanceAsync(config);
return _realm;
}
else
{
var config = new SyncConfiguration("Hirschs", currentUser);
_realm = Realm.GetInstance(config);
return _realm;
}
}
catch (Exception ex)
{
await UserDialogs.Instance.AlertAsync(new AlertConfig
{
Title = "An error has occurred",
Message = $"An error occurred while trying to open the Realm: {ex.Message}"
});
}
}
I'm trying to get Facebook leadgen ad data.
1-)As seen below, facebook sends the data to me successfully and I receive it successfully.
Successful Process img
2-)But the submissions I made on just this page do not come. What could be the reason for this?
Failed Process img
*But only the opinions I made on this page are not coming. What could be the reason for this?
Facebook doesn't even post. As seen in the picture, Server failure (102) information is displayed. What is the reason of this?
3-)The code I received the incoming data
Asp.Net Api Method
public async Task<HttpResponseMessage> Post([FromBody] JsonData data)
{
try
{
dbmanager db = new dbmanager();
db.Jsonkaydetv2(data);
var entry = data.Entry.FirstOrDefault();
var change = entry?.Changes.FirstOrDefault();
if (change == null) return new HttpResponseMessage(HttpStatusCode.BadRequest);
//Generate user access token here https://developers.facebook.com/tools/accesstoken/
const string token = "XXXX";
var leadUrl = $"https://graph.facebook.com/v2.10/{change.Value.LeadGenId}?access_token={token}";
var formUrl = $"https://graph.facebook.com/v2.10/{change.Value.FormId}?access_token={token}";
using (var httpClientLead = new HttpClient())
{
var response = await httpClientLead.GetStringAsync(formUrl);
if (!string.IsNullOrEmpty(response))
{
var jsonObjLead = JsonConvert.DeserializeObject<LeadFormData>(response);
db.JsonkaydetLeadFormData(jsonObjLead);
//jsonObjLead.Name contains the lead ad name
//Jsonkaydet(jsonObjLead.Name+"x");
//If response is valid get the field data
using (var httpClientFields = new HttpClient())
{
var responseFields = await httpClientFields.GetStringAsync(leadUrl);
if (!string.IsNullOrEmpty(responseFields))
{
var jsonObjFields =JsonConvert.DeserializeObject<LeadData(responseFields);
db.JsonkaydetLeadData(jsonObjFields);
//jsonObjFields.FieldData contains the field value
}
}
}
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception ex)
{
Jsonkaydet(ex.ToString());
Trace.WriteLine($"Error-->{ex.Message}");
Trace.WriteLine($"StackTrace-->{ex.StackTrace}");
return new HttpResponseMessage(HttpStatusCode.BadGateway);
}
}
I'm using ASP.NET 4.6 MVC. I'm saving an xml file as a byte array in my SQL db. I want to allow my user to download the file from the browser. I'm not getting any errors and no file is getting downloaded. I know there are plenty of these issues out there but I haven't seen one where a file isn't being downloaded (not even a corrupted one).
public ActionResult DownloadScript(int id) {
try {
var script = _db.PortalScripts.FirstOrDefault(i = >i.Id == id);
if (script != null) {
return File(script.ScriptBytes, "text/xml", script.Name);
}
}
catch(Exception e) {
FlashMessage.Danger("Error downloading script");
}
return RedirectToAction("Scripts");
}
[HttpPost]
public ActionResult UploadScript(HttpPostedFileBase file) {
try {
if (file.ContentLength > 0) {
var newScript = new PortalScript {
Name = Path.GetFileName(file.FileName),
Version = "190.161",
Description = "This is a placeholder",
Displayed = true
};
using(MemoryStream ms = new MemoryStream()) {
file.InputStream.CopyTo(ms);
newScript.ScriptBytes = ms.ToArray();
}
var existingScripts = _db.PortalScripts.FirstOrDefault(s = >s.ScriptBytes == newScript.ScriptBytes);
if (existingScripts == null) {
_db.PortalScripts.AddOrUpdate(newScript);
_db.SaveChanges();
FlashMessage.Confirmation(newScript.Name + " successfully uploaded");
}
else FlashMessage.Warning(newScript.Name + " already exists. Duplicate upload ignored.");
}
}
catch(Exception ex) {
FlashMessage.Danger("Upload failed: " + ex.Message);
}
return RedirectToAction("Scripts");
}
In my download method, my script variable is returning a properly filled out model. Not going into the catch either. Just getting redirected back to my original view with no file. Any suggestions??
I had this piece of code that initially worked fine. However, After adding it to a class where I store my methods that are reused, it keeps failing. The exception that is caught states that the CancellationTokenSource has been Disposed. Can someone point me in the right direction?
I have tried creating a new client and Adding CancellationToken.None to the PutAsync() method from HTTPClient Class but it still fails with the CancellationTokenSource Disposed exception.
public async void AddProduct(Product product)
{
string storeId = "";
try
{
var storeData = JObject.Parse(Connect.Json).SelectToken("store").ToString();
var stores = JsonConvert.DeserializeObject<List<Store>>(storeData);
var store = stores[0];
storeId = store.Id;
store.Products.Add(product);
ProdInfo info = new Info();
foreach(Product p in store.Products)
{
info.AddedProducts = + p.Id;
}
var content = JsonConvert.SerializeObject(info);
using (Connect.Client)
using (var response = await Connect.Client.PutAsync(_url + "/stores/" + storeId, new StringContent(content)))
{
var cont = response.Content;
string result = await cont.ReadAsStringAsync();
if ((int)response.StatusCode == 200)
{
this.JobResult = result;
//this.JobResult = "Store has been successfully updated";
}
else
{
this.JobResult = result;
//this.JobResult = "Store was not updated!";
}
}
}
catch (Exception ex)
{
//this.JobResult = "Store has not been updated due to an error.";
this.JobResult = ex.Message;
}
}
I was able to solve this by simple removing 'using(Connect.Client)' from all of my methods. As #sellotape stated, They were disposing of the HttpClient before I was able to use it again. Thank you all for your contributions.