When calling CreateDocumentAsync(), do I need to check the ResourceResponse<Document> for errors? - azure-cosmosdb

When calling CreateDocumentAsync(), do I need to check the ResourceResponse for errors? For example, there is a .StatusCode property.
Or will try-catch handle all possible error conditions?

Try catch is the way,
try
{
//Get a Document client
using (client = new DocumentClient(new Uri(endpointUrl), authorizationKey))
{
RunDemoAsync(databaseId, CollectionId).Wait();
}
}
catch (DocumentClientException de)
{
Exception baseException = de.GetBaseException();
Console.WriteLine("{0} error occurred: {1}, Message: {2}", de.StatusCode, de.Message, baseException.Message);
}
catch (Exception e)
{
Exception baseException = e.GetBaseException();
Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
}
finally
{
Console.WriteLine("End of demo, press any key to exit.");
Console.ReadKey();
}

Related

I get same error in try and in catch on context.SaveChangesAsync

I have function:
private async Task<ServiceResponse> deleteCountryByAdmin(Country dataForDelete, CancellationToken cancellationToken)
{
try
{
_context.Set<Country>().Remove(dataForDelete);
_context.SaveChangesAsync(cancellationToken);
return ServiceResponse.Success(dataForDelete.Id);
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
if (sqlException.Number == 547)
{
dataForDelete.Active = false;
await _context.SaveChangesAsync(cancellationToken);
return ServiceResponse.Success(dataForDelete.Id);
}
else throw;
}
else throw;
}
}
Here I try to delete Country, but if that entry exist in another table, instead of delete I set Active property to false. Problem is that even when I enter into this part of code:
if (sqlException.Number == 547)
{
dataForDelete.Active = false;
await _context.SaveChangesAsync(cancellationToken);
return ServiceResponse.Success(dataForDelete.Id);
}
I still get error for trying to delete statement conflicted with reference constraint.

CancellationToken Source does not return taskcancelled when token.cancel is called

Below is the Service method that i call....
after i have called the service... my net goes off and i cancel the token
Which means after i have hit the service i cancel the token... is there a way to cancel the service i have called...
below is my code
public async Task<List<MeritData>> GetSyncupData(string Id, string BusinessDate, CancellationToken cancellationToken)
{
List<MeritData> PendingData = new List<MeritData>();
HttpResponseMessage responseMessage = null;
try
{
cancellationToken.ThrowIfCancellationRequested();
var api = RestService.For<IInventoryMeritStatusApi>(_httpClient);
responseMessage = await api.GetMeritData(Id, BusinessDate, cancellationToken).ConfigureAwait(false);
if (cancellationToken.IsCancellationRequested)
cancellationToken.ThrowIfCancellationRequested();
if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK)
{
// my code on success
}
}
catch (SocketException SocketEx)
{
ServiceException serviceException = new ServiceException("SocketException", SocketEx);
throw serviceException;
}
catch (HttpRequestException httpReqEx)
{
ServiceException serviceException = new ServiceException("NoInternet", httpReqEx);
throw serviceException;
}
catch (ServiceException serviceEx)
{
ServiceException serviceException = new ServiceException("NoInternet", serviceEx);
throw serviceException;
}
catch (OperationCanceledException ex)
{
Console.WriteLine("TaskCanceledException GetProduct");
throw ex;
}
catch (Exception ex)
{
throw ex;
}
return PendingData;
}
after the line
responseMessage = await api.GetMeritData(Id, BusinessDate, cancellationToken).ConfigureAwait(false);
is executed i switch off the net and call cancellationTokenSource.Cancel();
it takes a long time and finally get a "httprequestexception" not a token cancelled exception
how do i solve this ? i want to cancel the call to the webservice when token.Cancel is called

Thread disrupting execution of ASP.net main application

I have an ASP.net web app that spawns a process (in a thread). This thread calls a '.dll' to connect to another 'subsystem'.
Problem is, when there are errors connecting to the 'subsystem', it affects my main application (main UI) and I get a 'connection refused message'. I have already put in 'try-catch' error handling routines in my thread. FYI, I would like to treat the thread as a 'Fire and forget' thread.
The thread is spawned when btnSubmit is clicked.
Please refer to trimmed-down extract of code.
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
txt_hide.Value = sStatus;
if (sStatus == "")
{
//create thread for posting
id = Guid.NewGuid();
Thread th = new Thread(() => postXMLClass.PostXML(sSeqNo));
th.Start();
sStatus = "Transaction generated..please check posting status..";
lblMessage.Text = "Transaction Generated...";
}
else
{
FormView1.DataBind(); //refresh the form
clib.Show2("Error generating transaction : " + sStatus, sender);
lblMessage.Text = "Error generating transaction : " + sStatus;
}
}
catch (SqlException ex)
{
lblMessage.Text = "Error generating transaction ...: " + ex.Message;
}
catch (Exception ex)
{
//sqc.Transaction.Rollback();
lblMessage.Text = "Error encountered...: " + ex.Message;
throw;
}
finally
{
if (dbc != null) dbc.Dispose();
if (clib != null) clib.Dispose();
}
}
public static void PostXML(string inlinkcode)
{
string sToken = "", sXMLOut = "";
Xml.Router.XMLRouter cX = new Xml.Router.XMLRouter();
try
{
cX.set_Options("com.xml.router.nameServer", appSetArray[0]);
cX.set_Options("com.xml.router.nameServerPort", appSetArray[2]);
cX.set_Options("com.xml.router.logicalServerName", appSetArray[1]);
{
sLinkcode = inlinkcode;
if (sLinkcode != null && sLinkcode != "")
{
strxml = "<?xml version=\"1.0\" encoding='UTF-8' ?>";
strxml += "<TableLinkRequest version=\"1.0\"><DocumentLinkStart><Request><StartParams>";
strxml += "<CmpCode>X</CmpCode><DocCode></DocCode></TableLinkRequest>";
sXMLOut = cX.Send(sToken, strxml);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception {0}", ex.Message);
}
finally
{
if (cX != null) cX.Logoff(sToken);
}
}

Reading InputStream of NANOHTTPD gives Socket TimeOut Exception

I am trying to read the InputStream from IHTTPSession.getInputStream() using the following code but its gives Socket TimeOut Exception every time.
private String readInStream(InputStream in){
StringBuffer outBuffer=new StringBuffer();
BufferedInputStream bis=new BufferedInputStream(in);
try {
while(bis.available()>0){
int ch= bis.read();
outBuffer.append((char)ch);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("DATA_Length", "outputBuffer :"+outBuffer.toString().length());
return outBuffer.toString();
}
i also tried the following Method but the same exception arises
private String readInStream(InputStream in){
String line="";
StringBuffer outBuffer=new StringBuffer();
BufferedReader rd=new BufferedReader(new InputStreamReader(in));
try {
while((line=rd.readLine()) != null){
outBuffer.append(line);
}
} catch (IOException e) {
Log.e("IOException", "IOException in readInStream:");
e.printStackTrace();
}
Log.e("DATA_Length", "outputBuffer :"+outBuffer.toString().length());
return outBuffer.toString();
}
Getting the content length from the header and reading up to it solved the problem.
Can confirm the accepted answer works (getting content length from the header and reading up to it). Here is some example code to turn the InputStream into a String:
try {
int contentLength = Integer.valueOf(session.getHeaders().get("content-length"));
String msg = new String(in.readNBytes(contentLength)); // the request body
} catch (IOException e) {
e.printStackTrace();
}
If you want to prevent a NullPointerException here, check whether the content-length header actually exists before parsing it to an integer.

IOException: The process cannot access the file 'filename' because it is being used by another process

I have this code in my asp.net project:
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
using (StreamWriter sw = File.CreateText(Server.MapPath(#"~/AboutUs.txt")))
{
sw.Write(FreeTextBox1.Text);
sw.Close();
sw.Dispose();
lblError.Text = "تغییرات با موفقیت ذخیره شد.";
lblError.CssClass = "success";
}
}
catch (Exception ex)
{
lblError.Text = "خطایی روی داده است!" + "\n" + ex.ToString();
lblError.CssClass = "error";
}
finally
{
lblError.Visible = true;
}
}
Sometimes (not always) when I hit btnSave following error is occurred:
IOException: The process cannot access the file 'filename' because it is being used by another process
Why?
You just Run your application after see windows task manager-->Processes, any notepad.exe running you just right click then click end process . .

Resources