Android app connecting to a webservice - not working - c#

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

Related

Web api call lost in dll function

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?

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);
}
}

Windows service Signalr authentication expires

I have a Windows Services which connects to a Signalr Hub.
The Service receives barcode scans and sends the barcode to the Hub.
Users request en webpage which uses jTable to show the scanned barcodes in a grid.
The webapplication uses winforms authentication with sliding expiration.
This works fine till some point in time the authentication cookie becomes invalid. How can i detect if an authentication cookie becomes invalid?
At startup off the service I create a hub connection.
private static IHubProxy _bufferProxy;
private static HubConnection _hubConnection;
protected static async void InitBufferHub()
{
bool connected = false;
while(!connected)
{
try
{
_hubConnection = new HubConnection(Settings.Default.HubConnection);
Cookie returnedCookie;
var authResult = AuthenticateUser("user", "password", out returnedCookie);
if (authResult)
{
_hubConnection.CookieContainer = new CookieContainer();
_hubConnection.CookieContainer.Add(returnedCookie);
Log.Debug("User logged in");
}
else
{
Log.Debug("Login failed");
}
_bufferProxy = _hubConnection.CreateHubProxy("buffer");
await _hubConnection.Start();
connected = true;
Log.Debug("Hub proxy created");
}
catch (Exception ex)
{
Log.Error("OnStart", ex);
Thread.Sleep(100);
}
}
}
internal static async void SendBufferItem(BufferItem bufferItem)
{
try
{
if (_hubConnection.State == ConnectionState.Disconnected)
{
_bufferProxy = null;
_hubConnection.Dispose();
InitBufferHub();
}
await _bufferProxy.Invoke("RecordCreated", bufferItem);
}
catch (Exception ex)
{
Log.Error("SendBufferItem error: ", ex);
}
}

How to pass through a proxy server in c# using the windows azure marketplace bing api

I am working on a school project where I am required to search the web with a particular search string and return the urls of webpages where the search string were found. I am using the bing api Windows azure marketplace. But the problem is my school uses a proxy server that requires a username and password. I have valid credentials but i don't know have to bypass the proxy server programmatically using c#.
Could I please get a sample of how to connect to the bing api through a proxy server?
NB: Here is a sample of what i already have in c#
static void Main(string[] args)
{
try
{
const string bingkey = "my id";
bing.Credentials = new NetworkCredential(bingkey, bingkey);
var results = SearchAsync("search string");
// IWebProxy proxy2 = HttpWebRequest.DefaultWebProxy;
int i =0;
foreach (var result in results.Result)
{
Console.WriteLine(result.Url);
++i;
}
Console.WriteLine(i);
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
catch (DataServiceClientException e)
{
Console.WriteLine(e.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadKey();
}
public async static Task<IEnumerable<WebResult>> SearchAsync(string query)
{
DataServiceQuery<WebResult> webquery = bing.Web(query, null, null, null, null, null, null, null);
var results = await Task.Factory.FromAsync(webquery.BeginExecute(null, null), asyncResult => webquery.EndExecute(asyncResult));
return results;
}

Simple webclient request returning MS.InternalMemoryStream

I have a simple webclient that connects to a webpage and returns the data. The code is as follows:
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("https://domain.com/register.php?username=" + txtbUser.Text);
webClient.OpenReadCompleted +=
new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
//Process web service result here
MessageBox.Show(e.Result.ToString());
}
else
{
//Process web service failure here
MessageBox.Show(e.Error.Message);
}
}
The data coming from e.Result is MS.InternalMemoryStream and not the data coming back from the webpage, the data coming back from the webpage should just be a 0 or 1. Any idea's?
thanks,
Nathan
.ToString() returns the name of the class - in this case, InternalMemoryStream. You have to READ the stream to get the result. Check this out

Categories