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’ve used RestSharp 106 in the past but now I’m trying to get a new project up and running with v107. I did a simple test below but I can’t get it to return any data so I must be missing something that I’m not understanding. I’ve put a breakpoint at the top of the method and can follow it all the way down until it makes the async call and then the app just quits. I see the initial logging but again nothing after the async call. I would have thought I would see some logging about the list count or even the “Application END” piece. Anyone have any ideas on what I’m doing wrong? I’ve kept but commented out some of the different things I’ve tried.
Link to the documentation I’m looking at.
https://restsharp.dev/intro.html#introduction
public async void Run()
{
_log.LogInformation("Application START");
try
{
var listPPC = new List<PriorPeriodCorrection>();
listPPC = await CallApi();
}
catch (Exception ex)
{
_log.LogError("Error: {0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
}
_log.LogInformation("Application END");
}
public async Task<List<PriorPeriodCorrection>> CallApi()
{
var listPPC = new List<PriorPeriodCorrection>();
var apiURL = "https://example.com";
var apiEndpoint = "api/payroll/getpriorpaycorrectiondata/from/2021-12-01/to/2021-12-07";
var proxyAddress = "http://example.com:9400";
var apiUsername = "someusername";
var apiPassword = "4PsaI69#tuv";
var options = new RestClientOptions(apiURL)
{
ThrowOnAnyError = true,
Timeout = 1000,
Proxy = new WebProxy(proxyAddress)
};
var client = new RestClient(options);
client.Authenticator = new HttpBasicAuthenticator(apiUsername, apiPassword);
var request = new RestRequest(apiEndpoint);
try
{
listPPC = await client.GetAsync<List<PriorPeriodCorrection>>(request);
//var response = await client.GetAsync<PriorPeriodCorrection>(request);
//var response = await client.GetAsync<List<PriorPeriodCorrection>>(request);
//var response = await client.GetAsync(request);
//if (!string.IsNullOrWhiteSpace(response.Content))
//{
// listPPC = JsonConvert.DeserializeObject<List<PriorPeriodCorrection>>(response.Content);
//}
//else
// _log.LogInformation("Response Content is Blank or NULL.");
}
catch (Exception ex)
{
_log.LogError("Error: {0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
}
_log.LogInformation("Response count: {0}", listPPC.Count);
return listPPC;
}
My winforms app sends PUT/POST requests to asp.net web api service. Mostly it sends json object as request's content and those request work well. Sometimes, when it needs to send jpg along with json object, so it creates multiPart request where jpg is content and json is passed in url, like so:
example.com/EditPart?id=193&PartJson=<serialized json object>
Here's full definition of the method sending the request:
public async void Edit(string attachmentPath)
{
using (var client = new HttpClient())
{
var serializedProduct = JsonConvert.SerializeObject(this, new JsonSerializerSettings { DateFormatString = "yyyy-MM-ddTHH:mm:ss.fff" });
string url = Secrets.ApiAddress + $"Edit{typeof(T).Name}?token=" + Secrets.TenantToken + $"&id={this.Id}&UserId={RuntimeSettings.UserId}" + $"&{typeof(T).Name}Json={serializedProduct}";
MultipartFormDataContent content = new MultipartFormDataContent();
try
{
using (var fileStream = System.IO.File.OpenRead(attachmentPath))
{
var fileInfo = new FileInfo(attachmentPath);
StreamContent fcontent = new StreamContent(fileStream);
fcontent.Headers.Add("Content-Type", "application/octet-stream");
fcontent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + fileInfo.Name + "\"");
content.Add(fcontent, "file", fileInfo.Name);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var result = await client.PutAsync(url, content);//<--stops here
if (result.IsSuccessStatusCode)
{
MessageBox.Show("Edycja zakończona powodzeniem!");
}
else
{
MessageBox.Show("Serwer zwrócił błąd przy próbie edycji. Wiadomość: " + result.ReasonPhrase);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Problem z wysyłką żądania do serwera. Wiadomość: " + ex.Message + ". " + ex.InnerException.Message, "Błąd żądania", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
It goes to await client.PutAsync(url, content); and then straight to exception saying: An error occurred while sending the request. The underlaying connection was closed. An unexpected error occurred on receive.
When I check in IIS logs, I see the request gets properly to the server, but ends with status 500 and win32 status 64.. I even put logging with NLog to EditPart method, but it never fires.. It looks like the method isn't called at all, but of course from IIS logs I know it is.
Here's complete EditPart definition on asp.net web api:
[HttpPut]
[Route("EditPart")]
[ResponseType(typeof(void))]
public HttpResponseMessage EditPart(string token, int id, int UserId, string PartJson)
{
try
{
JavaScriptSerializer jss = new JavaScriptSerializer();
JDE_Parts item = jss.Deserialize<JDE_Parts>(PartJson);
try
{
var items = db.JDE_Parts.Where(u => u.PartId == id);
if (items.Any())
{
Logger.Info("EditPart: Znalazłem odpowiednią część. Przystępuję do edycji Id={id}, UserId={UserId}", id, UserId);
JDE_Parts orgItem = items.FirstOrDefault();
//handle image
var httpRequest = HttpContext.Current.Request;
if (httpRequest.ContentLength > 0)
{
//there's a new content
if (httpRequest.ContentLength > Static.RuntimeSettings.MaxFileContentLength)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, $"{item.Name} przekracza dopuszczalną wielość pliku ({Static.RuntimeSettings.MaxFileContentLength} MB) i został odrzucony");
}
var postedFile = httpRequest.Files[0];
string filePath = "";
if (postedFile != null && postedFile.ContentLength > 0)
{
Logger.Info("EditPart: Znaleziono nowe pliki. Przystępuję do zapisu na dysku. Id={id}, UserId={UserId}", id, UserId);
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
filePath = $"{Static.RuntimeSettings.Path2Files}{item.Token + ext.ToLower()}";
string oFileName = db.JDE_Parts.Where(p => p.PartId == id).FirstOrDefault().Image;
if (!string.IsNullOrEmpty(oFileName))
{
// There was a file, must delete it first
Logger.Info("EditPart: Istnieją poprzednie pliki pod tą nazwą. Przystępuję do usuwania. Id={id}, UserId={UserId}", id, UserId);
System.IO.File.Delete(Path.Combine(RuntimeSettings.Path2Files, oFileName));
System.IO.File.Delete(Path.Combine(RuntimeSettings.Path2Thumbs, oFileName));
}
postedFile.SaveAs(filePath);
Logger.Info("EditPart: Zapisano pliki. Przystępuję do utworzenia miniatury.. Id={id}, UserId={UserId}", id, UserId);
Static.Utilities.ProduceThumbnail(filePath);
item.Image = item.Token + ext.ToLower();
}
}
try
{
Logger.Info("EditPart: Przystępuję do zapisu zmian w bazie danych. Id={id}, UserId={UserId}", id, UserId);
db.Entry(orgItem).CurrentValues.SetValues(item);
db.Entry(orgItem).State = EntityState.Modified;
db.SaveChanges();
Logger.Info("EditPart: Zapisano zmiany w bazie. Id={id}, UserId={UserId}", id, UserId);
}
catch (Exception ex)
{
Logger.Error("Błąd w EditPart. Id={id}, UserId={UserId}. Szczegóły: {Message}, nowa wartość: {item}", id, UserId, ex.ToString(), item);
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
}
catch (Exception ex)
{
Logger.Error("Błąd w EditPart. Id={id}, UserId={UserId}. Szczegóły: {Message}, nowa wartość: {item}", id, UserId, ex.ToString(), item);
return Request.CreateResponse(HttpStatusCode.NoContent);
}
}
catch (Exception ex)
{
Logger.Error("Błąd w EditPart. Id={id}, UserId={UserId}. Szczegóły: {Message}", id, UserId, ex.ToString());
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
return Request.CreateResponse(HttpStatusCode.NoContent);
}
What's weird is that all this worked perfectly well for months, until some time ago it stopped.. Also, when I debug the asp.net application on my machine, the request runs without any problem.. What else I can do to trace this issue?
When you debug the asp.net api application, it can run without any problem. This shows that there is no problem with the api application.
But the status in IIS logs is 500, errors greater than 500 are generally caused by the server, the client is normal. This contradicts the above conclusion that the api is no problem.
Since I don’t know the version of .net you are using, I’m not sure whether to use TLS 1.0, 1.1 or 1.2. Different versions of .net target different TLS, the latest 4.6 currently supports 1.2. So the most safe and effective way is to set all TLS and SSL.
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12| SecurityProtocolType.Ssl3;
It turned out that the problem was single line in my Edit method in the client app. After changing fcontent.Headers.Add("Content-Type", "application/octet-stream") to fcontent.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileInfo.Name)) it works flawlessly. In other words, my request wasn't even sent to the server. What's puzzling, though, is the fact that the same code had been working for months and then stopped..
public async void Edit(string attachmentPath)
{
using (var client = new HttpClient())
{
var serializedProduct = JsonConvert.SerializeObject(this, new JsonSerializerSettings { DateFormatString = "yyyy-MM-ddTHH:mm:ss.fff" });
string url = Secrets.ApiAddress + $"Edit{typeof(T).Name}?token=" + Secrets.TenantToken + $"&id={this.Id}&UserId={RuntimeSettings.UserId}" + $"&{typeof(T).Name}Json={serializedProduct}";
MultipartFormDataContent content = new MultipartFormDataContent();
try
{
using (var fileStream = System.IO.File.OpenRead(attachmentPath))
{
var fileInfo = new FileInfo(attachmentPath);
StreamContent fcontent = new StreamContent(fileStream);
fcontent.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileInfo.Name)); //fcontent.Headers.Add("Content-Type", "application/octet-stream");
fcontent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + fileInfo.Name + "\"");
content.Add(fcontent, "file", fileInfo.Name);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var result = await client.PutAsync(url, content);//<--stops here
if (result.IsSuccessStatusCode)
{
MessageBox.Show("Edycja zakończona powodzeniem!");
}
else
{
MessageBox.Show("Serwer zwrócił błąd przy próbie edycji. Wiadomość: " + result.ReasonPhrase);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Problem z wysyłką żądania do serwera. Wiadomość: " + ex.Message + ". " + ex.InnerException.Message, "Błąd żądania", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
I get "Response stream has already been completed." when the server call WriteAsync() method by using pi-stream.Only when I use Thread.sleep the client sometimes can get the stream during the sleeping time.But I know that's not the solution.So plz tell me what can I do!
I used .net core 2.2 and vs community 2019 16.2.3
proto:
rpc CppyFile(stream Chunk)returns(stream Back){}
message Chunk{
bytes Content=1;
string FileName=2;
string Flag=3;
}
message Back{
bytes Content=1;
UploadStatus statue=2;
string Flag=3;
}
Server:
await responseStream.WriteAsync(new Back
{
Content = ByteString.FromStream(stream),
Flag = fname,
Statue = new UploadStatus
{
Message = "2",
Code = UploadStatusCode.Unknown
}
});
client:
using (var call = client.CppyFile())
{
try
{
await call.RequestStream.WriteAsync(chunk);
Console.WriteLine("Sending");
//################################################################################## here's Problem
await call.RequestStream.CompleteAsync();
//Thread.Sleep(8 * 1000);
//##################################################################################
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
var responseReaderTask = Task.Run(async () =>
{
while (await call.ResponseStream.MoveNext())
{
var note = call.ResponseStream.Current;
//get sending from server
......
here's the detail error.
System.InvalidOperationException: Response stream has already been completed.
at Grpc.Core.Internal.AsyncCallServer2.CheckSendAllowedOrEarlyResult() in T:\src\github\grpc\src\csharp\Grpc.Core\Internal\AsyncCallServer.cs:line 195
at Grpc.Core.Internal.AsyncCallBase2.SendMessageInternalAsync(TWrite msg, WriteFlags writeFlags) in T:\src\github\grpc\src\csharp\Grpc.Core\Internal\AsyncCallBase.cs:line 124
EDIT 1: I added below the code who calls and uses the second method, and the error and data I recive
First of all sorry if my English isn't good enough, and sorry if there is another thread with the solution. I haven't found it.
Ok, I'm making a windows phone 8 app that uses a lot of info from a web service. The app makes different Json Post and uses the info. I maked a method for Posting that WORKS:
public static async void checkdeviceid()
{
//Where we are posting to:
Uri theUri = new Uri("urlofexample");
//Create an Http client
HttpClient aClient = new HttpClient();
//Class that will be serialized into Json
objetoslistas.checkdeviceidinput paquete = new objetoslistas.checkdeviceidinput();
//Set some values
paquete.Text = "deviceID";
paquete.Text2 = App.device_id;
//serialize data
var serializado = JsonConvert.SerializeObject(paquete);
//Post the data
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, new StringContent(JsonConvert.SerializeObject(paquete), Encoding.UTF8, "application/json"));
if (aResponse.IsSuccessStatusCode)
{
string res = await aResponse.Content.ReadAsStringAsync();
var respuestaperfil = JsonConvert.DeserializeObject<objetoslistas.checkdeviceidoutput>(res.ToString());
//Do something with the data
}
else
{
// show the response status code
String failureMsg = "HTTP Status: " + aResponse.StatusCode.ToString() + " - Reason: " + aResponse.ReasonPhrase;
}
}
This code its actually working, but the fact it's that my app will have maybe 30 or 40 diferent POST, so I tried to make a reusable method like this:
public static async Task<string> jsonPOST(Uri theUri, object paquete)
{
//Create an Http client and set the headers we want
HttpClient aClient = new HttpClient();
//serialize data
var serializado = JsonConvert.SerializeObject(paquete);
//Post the data
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, new StringContent(JsonConvert.SerializeObject(paquete), Encoding.UTF8, "application/json"));
if (aResponse.IsSuccessStatusCode)
{
string res = await aResponse.Content.ReadAsStringAsync();
return res;
}
else
{
// show the response status code
String failureMsg = "HTTP Status: " + aResponse.StatusCode.ToString() + " - Reason: " + aResponse.ReasonPhrase;
return failureMsg;
}
}
This code gives me problems in the main, were it's called. As I can understand, the problem is that, as the method calls some await process, the rest of the code continues with the execution without expect for the await result...
The code in Main is:
objetoslistas.checkdeviceidinput paquete = new objetoslistas.checkdeviceidinput();
paquete.Text = "deviceID";
paquete.Text2 = App.device_id;
Uri url = new Uri("urlofhteservice");
Task<string> recibo = metodosJson.jsonPOST(url, paquete);
var respuestaperfil = JsonConvert.DeserializeObject<objetoslistas.checkdeviceidoutput>(recibo.ToString);
if (respuestaperfil.Text2 == null)
{
IsolatedStorageSettings.ApplicationSettings["DeviceRegistered"] = true;
}
else
{
IsolatedStorageSettings.ApplicationSettings["DeviceRegistered"] = false;
}
And I recive this error (translated from google translator, sorry)
There was an exception of type 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.DLL but not controlled in the user code
The data I have in "recibo" is
recibo Id = 1, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}" System.Threading.Tasks.Task<string>
So as I understand the await method is still waiting.
Was I clear?
Thanks