Web api call lost in dll function - c#

I am developing an web services in mvc asp.net 5.
I am using a SDK from a dll, but when I call a function from this dll it does not respond. It stays waiting an does not throw an error.
I am compiling in x86. This is the code
public Respuesta TimbrarFactura(String ConceptoDocumento, String Serie, double Folio, String password)
{
try
{
int resp = SDK.fEmitirDocumento(ConceptoDocumento, Serie, Folio, password, "");
if (resp == 0)
{
return new Respuesta(true, "Se timbro el documento");
}
else
{
try
{
SDK.fError(resp, sMensaje, 255);
}
catch(Exception e)
{
}
return new Respuesta(false, sMensaje.ToString());
}
}catch(Exception ex)
{
return null;
}
}
I added a try catch block to get some error, but the catch block is never entered. What could be causing this?

Related

Possibly fixing exception in Catch

Is it possible that I would bind a method and fix the error in the catch response? (for example take this code below)
try
{
if (icheck == 0)
{
BindRegister();
}
else
{
Label1.Text = "Error Message";
}
}
catch
{
icheck = 0;
BindRegister();
}
Is the catch just responsible for writing down the error message? (I'm using this code in my ASP.net web app)

Checking for Web Service connectivity

I've developed a simple Web Service and a Windows Phone 8 app to consume it.
Everything works as intended but the way my current (working) code stands, it's assuming the Web Service to always be running and available. Seeing as that may not always be the case, I'd like to try and add some kind of connectivity testing before I start sending requests. I've read that there's no straightforward way of being certain that the WS is up and running other than querying it somehow.
With that in mind, here's what my LoadData method structure looks like (Feb. 26th):
public void LoadData(string articleCode = null)
{
try
{
this.ArticleItems.Clear();
MyServiceSoapClient ws = new MyServiceSoapClient();
CheckWebService();
if (this.isWebServiceUp)
{
if (!String.IsNullOrEmpty(articleCode))
{
ws.GetBasicDataAsync(articleCode);
ws.GetBasicDataCompleted += Ws_GetBasicDataCompleted;
//(irrelevant code supressed for clarity)
this.IsDataLoaded = true;
}
}
else
{
this.ArticleItems.Add(new ItemViewModel() { LineOne = "Could not connect to Web Service." });
ws.Abort();
}
}
}
And it still throws an unhandled CommunicationException error.
EDIT: After taking into consideration both suggestions and doing some searching, I've tried to set up a "heartbeat"-type method but it's not working correctly. Asynchronous programming is a relatively new paradigm for me so I most likely am missing something but here goes my attempt at an implementation thus far (getting a "Unable to cast object of type 'System.Net.Browser.OHWRAsyncResult' to type 'System.Net.HttpWebResponse'" exception):
public void CheckWebService()
{
try
{
Uri wsURL = new Uri("http://localhost:60621/WebService1.asmx");
//try accessing the web service directly via its URL
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(wsURL);
request.Method = "HEAD";
//next line throws: "Unable to cast object of type 'System.Net.Browser.OHWRAsyncResult' to type 'System.Net.HttpWebResponse'."
using (var response = (System.Net.HttpWebResponse)request.BeginGetResponse(new AsyncCallback(ServiceCallback), request))
{
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception("Error locating web service");
}
}
}
catch (System.ServiceModel.FaultException fe)
{
this.ArticleItems.Add(new ItemViewModel() { LineOne = fe.Message });
}
catch (System.ServiceModel.CommunicationException ce)
{
this.ArticleItems.Add(new ItemViewModel() { LineOne = ce.Message });
}
catch (System.Net.WebException we)
{
this.ArticleItems.Add(new ItemViewModel() { LineOne = we.Message });
}
catch (Exception ex)
{
this.ArticleItems.Add(new ItemViewModel() { LineOne = ex.Message });
}
}
private void ServiceCallback(IAsyncResult asyncResult)
{
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)asyncResult.AsyncState;
using (var response = (System.Net.HttpWebResponse)request.EndGetResponse(asyncResult))
{
if (response != null && response.StatusCode == System.Net.HttpStatusCode.OK)
{
this.isWebServiceUp = true;
request.Abort();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

C# Recursive function approach?

I have a recursive function in a windows service. This function upon completion rewinds itself as it has been repeated multiple times in recursion. Isn't that an overhead ?
Is there any way to avoid unwinding ? Is there any better approach?
Edit : In this method, I get 100 records from DB and then process them and then get another 100 and so on till all the records in DB have been processed.
Also, there is no limit of how many total records there might be in the db so this function can repeat itself quite a lot.
public void ServiceFunctionality()
{
try
{
// Get Data From WEBAPI
HttpClient client = new HttpClient();
HttpResponseMessage response = response = client.GetAsync("webapi url link").Result;
Response<ServiceWrapper> objResponse = response.Content.ReadAsAsync<Response<ServiceWrapper>>().Result;
if (objResponse != null)
{
if (objResponse.isSuccess == true)
{
listContact = objResponse.data.lContact;
int MaxPKinSelectedRecords = objResponse.data.MaxPKinSelectedRecords;
int MaxPKinTotalRecords = objResponse.data.MaxPKinTotalRecords;
if (listContact != null && listContact.Count>0)
{
try
{
Parallel.ForEach(listContact, contact =>
{
// some code...
});
// Recursive Call
if (MaxPKinTotalRecords != MaxPKinSelectedRecords)
{
ServiceFunctionality();
}
}
catch (Exception ex)
{
// Logging
}
}
}
else
{
// Logging
}
}
else
{
// Logging
}
}
catch (Exception ex)
{
// Logging
}
}
You can always unwind to a while loop. Because your calls aren't altering state, this is trival.
public void ServiceFunctionality()
{
bool done = false;
while(!done) {
try
{
done = true; //if we don't reset this, we're done.
// Get Data From WEBAPI
HttpClient client = new HttpClient();
HttpResponseMessage response = response = client.GetAsync("webapi url link").Result;
Response<ServiceWrapper> objResponse = response.Content.ReadAsAsync<Response<ServiceWrapper>>().Result;
if (objResponse != null)
{
if (objResponse.isSuccess == true)
{
listContact = objResponse.data.lContact;
int MaxPKinSelectedRecords = objResponse.data.MaxPKinSelectedRecords;
int MaxPKinTotalRecords = objResponse.data.MaxPKinTotalRecords;
if (listContact != null && listContact.Count>0)
{
try
{
Parallel.ForEach(listContact, contact =>
{
// some code...
});
// set loop variable
if (MaxPKinTotalRecords != MaxPKinSelectedRecords)
{
done = false;
}
}
catch (Exception ex)
{
// Logging
}
}
}
else
{
// Logging
}
}
else
{
// Logging
}
}
catch (Exception ex)
{
// Logging
}
}
}
Do not use recursion for calling a function whenever you have alternate suitable solution. I personally almost never do
I have tried to keep it same other than using a while..
Do not forget to break your loop. I tried to handle this thing but still
Just to be very careful, never take a risk of infinite loop on server I took maxPossibleIterations. So that in case of any mistake your web service server would not have to go for infinite iterations
public void ServiceFunctionality()
{
long maxPossibleIterations = 999999;
try
{
while (true)
{
maxPossibleIterations++;
// Get Data From WEBAPI
HttpClient client = new HttpClient();
HttpResponseMessage response = response = client.GetAsync("webapi url link").Result;
Response<ServiceWrapper> objResponse = response.Content.ReadAsAsync<Response<ServiceWrapper>>().Result;
if (objResponse != null)
{
if (objResponse.isSuccess == true)
{
listContact = objResponse.data.lContact;
int MaxPKinSelectedRecords = objResponse.data.MaxPKinSelectedRecords;
int MaxPKinTotalRecords = objResponse.data.MaxPKinTotalRecords;
if (listContact != null && listContact.Count>0)
{
try
{
Parallel.ForEach(listContact, contact =>
{
// some code...
});
if (MaxPKinTotalRecords == MaxPKinSelectedRecords)
{
break;
}
}
catch (Exception ex)
{
// Logging
}
}
else
break; //Important
}
else
{
// Logging
break;
}
}
else
{
// Logging
break;
}
} // End while
}
catch (Exception ex)
{
// Logging
}
}

Returning a bool and rethrowing an exception

Is it possible to return a bool and also rethrow an exception within the same method? Ive tried with the following code and it keeps saying that unreachable code is detected or that i cant exit the finally block.
public bool AccessToFile(string filePath)
{
FileStream source = null;
try
{
source = File.OpenRead(filePath);
source.Close();
return true;
}
catch (UnauthorizedAccessException e)
{
string unAuthorizedStatus = "User does not have sufficient access privileges to open the file: \n\r" + filePath;
unAuthorizedStatus += e.Message;
MessageBox.Show(unAuthorizedStatus, "Error Message:");
throw;
}
catch (Exception e)
{
string generalStatus = null;
if (filePath == null)
{
generalStatus = "General error: \n\r";
}
else
{
generalStatus = filePath + " failed. \n\r";
generalStatus += e.Message;
}
MessageBox.Show(generalStatus, "Error Message:");
throw;
}
finally
{
if (source != null)
{
source.Dispose();
}
}
}
Once you throw an exception, processing in your current method finishes and the exception works up the call stack. Either handle your exceptions locally and then return your boolean, or throw them and let them bubble up and handle them at the front end.

Android app connecting to a webservice - not working

Iam trying to connect my App to a WCF service that I created in asp.net.
The service runs on my localmachine:
http://localhost:8080/Service.svc/
But for some reasons my Android can not connect to this http-adress.
This is the error:
09-12 14:50:44.540: WARN/System.err(593): org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1:8080 refused
this is the method in wcf, Iam trying to return a collection with some values.
/// <returns>An enumeration of the (id, item) pairs. Returns null if no items are present</returns>
protected override IEnumerable<KeyValuePair<string, SampleItem>> OnGetItems()
{
// TODO: Change the sample implementation here
if (items.Count == 0)
{
items.Add("A", new SampleItem() { Value = "A" });
items.Add("B", new SampleItem() { Value = "B" });
items.Add("C", new SampleItem() { Value = "C" });
}
return this.items;
}
And this is how the connection in the android looks like:
public void getData(String url)
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
try
{
response = httpClient.execute(httpGet);
Log.i(TAG,response.getStatusLine().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}/* catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} */catch (Exception e){
e.printStackTrace();
}finally{
httpGet.abort();
}
}
127.0.0.1 refers to localhost in the Emulator, not your machine.
Use 10.0.2.2 to connect to your host machine.
Do also make sure you have requested the INTERNET permission in your AndroidManifest.xml

Categories