Xamarin Android project cannot connect to localhost API - http

I have been working on this problem for quite some time. I've read the many similar posts and their solutions don't help me (many posts are old and stale). I have a new Xamarin project and a localhost API that I am testing to. Initially I installed our production API locally and it doesn't connect. So I created a smaller test API and have had varying results in connecting. Xamarin Android will not connect with a "Failed to connect to localhost:XXXXX" message. I built a WPF project and get the same results. However I can connect to outside public API's (github) with both. I can connect to my localhost with a Windows forms desktop app and successfully get & post. Postman and httprepl both connect locally and successfully get & post. A couple of the other things the other posts suggested are 1) Client handler to ignore SSL - doesn't work, 2) Use the emulator's browser to connect to localhost - cannot connect. (this might be exposing where the problem really is but not sure).
Also The debugger seems to be behaving oddly. When the debugger gets to the HttpResponseMessageresponse.... line it rarely makes it to the next line so I cannot inspect the statuscode. The block I have below is in a try/catch and rarely makes it to the catch if the connection truly fails. Sometimes it will be caught at the catch and that's how I get the "failed to connect" message. Another developer here has run the project on his computer and gets the same results/errors on his computer.
HttpResponseMessage response = await client.SendAsync(request);
var Statuscode = response.StatusCode;
if (response.IsSuccessStatusCode)
{
var jsonbody = response.Content.ReadAsStringAsync().Result;
var ResponseBody = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
}
else
{
string oops = "Nothing";
}
I seem to be running out of options and am looking for any advice.
Thanks in advance.

Related

How do you initialize the Twilio Client in Meteor JS?

I'm having incredible difficulty setting up the Twilio Client in Meteor JS, and would really appreciate any help.
I have extracted the relevant code and error logs below. So far as I can tell, it should be simple. The code is just grabbing an authtoken which I have previously generated, and then trying to set up the device using that authtoken. But it's not working.
'click #initializeDevice'(event) {
var thisAuthToken = Session.get('myAuthToken');
console.log(thisAuthToken); // I have confirmed with Twilio support that these authtokens are correctly generated
const Device = require('twilio-client').Device;
Device.setup(thisAuthToken, { debug: true });
var myStatus = Device.status()
console.log(myStatus); //this is logging "offline"
Device.on('ready',function (device) {
log('Twilio.Device Ready!'); //this is not logging anything
});
},
When that code runs, it generates the following logs:
eyJhbGciDpvdXRnb2luZz9hcHBTaWQ9QVA2NDE2MzJmMzA1ZjJiY2I[Note:I have deleted part of the middle of the logged authtoken for the purpose of this public post]5YmMxOGQyOWVlNGU2ZGM0NjdmMzRiNDVhNCIsImV4cCI6MTU3Nz0ygbJKTx15GgNCWDkm-iUPjn_O1NZU6yovp4vjE
modules.js?hash=69069bec9aeba9503ae3467590cf182be57d9e62:3605 Setting up VSP
modules.js?hash=69069bec9aeba9503ae3467590cf182be57d9e62:3605 WSTransport.open() called...
modules.js?hash=69069bec9aeba9503ae3467590cf182be57d9e62:3605 Attempting to connect...
modules.js?hash=69069bec9aeba9503ae3467590cf182be57d9e62:3605 Closing and cleaning up WebSocket...
modules.js?hash=69069bec9aeba9503ae3467590cf182be57d9e62:3605 No WebSocket to clean up.
modules.js?hash=69069bec9aeba9503ae3467590cf182be57d9e62:3605 Could not connect to endpoint: ws does not work in the browser. Browser clients must use the native WebSocket object
modules.js?hash=69069bec9aeba9503ae3467590cf182be57d9e62:3605 Closing and cleaning up WebSocket...
modules.js?hash=69069bec9aeba9503ae3467590cf182be57d9e62:3605 No WebSocket to clean up.
calltemplate.js:31 offline
I'm doing this all from a local server, tunneled through NGROK. I've also set up the Twilio back end, linked the app, purchased a number, etc.
So far as I can tell, the issue, from the logs, appears to be something to do with the way that Meteor uses WebSockets.
Could not connect to endpoint: ws does not work in the browser. Browser clients must use the native WebSocket object
This is a not a Meteor related problem rather than browser issue.
Make sure your browser supports WebRTC
BTW, Your browser might be supporting it but you'd need to enable it.

Web Service Call Stopped Processing

I have a bunch of Xamarin iOS applications running on our Corporate iPhones and iPads. I recently upgraded my Visual Studio and Mac Book Pro to latest release version and my applications are no longer PROCESSING data from my web service correctly. I did not change version of Xamarin.Forms
VS 2017 Version 15.9.13
Xamarin.Forms.2.4.0.282
The web services are http. I have my NSAppTransportSecurityNSAllowsArbitraryLoads
set to allow http.
I am using the flag true to generate the Task.Factory.FromAsync methods in the Web Service Reference.cs file.
I could go on with describing how everything works if anyone needs more info.
Luckily, my Mac Book Pro Simulator has old and new versions of my apps installed in different iPhone/iPad devices for me to test. I installed fiddler to make sure all the requests/responses were the same. My old App in one device works and my new App in a different device fails. Same thing for ALL of my Applications. Old one works and new one fails.
When I review fiddler, the requests and responses are all working the same:
Request is made
App gets an authentication prompt
Authentication happens
Request returns code 200 with the data requested
The only difference in Fiddler is that two of the headers are in a different order: Working one has SOAPAction first and Content-Type next, the one failing has Content-Type and then SOAPAction. I am grasping at straws here because the order of these headers should not matter.
This is for all the applications. The only problem is that my new applications are ignoring the response. It is almost like the endMethod function from the parameter passed to FromAsync is never called.
This is the function call:
public async Task<ProcessLogon> ExecuteSaveLogon(DeviceItem DeviceItem)
{
ResultLogin = new ProcessLogon();
try
{
var ProcessLogon = await Task<WebServiceTrading.ProcessLogon>.Factory.FromAsync(serviceTrading.BeginSaveLogon, serviceTrading.EndSaveLogon, ToServiceTrading(DeviceItem), TaskCreationOptions.None);
ResultLogin = FromServiceTrading(ProcessLogon);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(#"ExecuteSaveLogon ERROR {0}", ex.Message);
}
return ResultLogin;
}
Does anyone know of any DEBUG or LOGGING tools that I could use to find out why my successful response is lost?

IdentityModel.OidcClient library doesn't seem to work with UWP

We are using ASP.NET Identity with IdentityServer4. We've added a Client to use with Azure AD. This works great within a web page, that part is working.
Our end goal is a UWP app, so we found the IdentityModel.OidcClient which has a UWP sample. This sample has two browser classes. We configured HTTPS, but the WabBrowser class now refuses to connect to the site at all. If I change the config to hit https://demo.identityserver.io then it works, but all the other config is the same, so I'm not sure what the problem could be. It shows an error message in the pop up browser that it could not connect.
I looked at the SystemBrowser class, but this logs in fine, then the browser window does not close, and even if we close it, the code doesn't move on to get back a result. Looking at the source, this is not surprising, it calls:
Launcher.LaunchUriAsync(new Uri(options.StartUrl));
and that's all. The RedirectUri is not passed in, and mechanism appears to exist to use it. So, the behaviour we see appears to be the extent of what the class can do.
Looking at the console .NET Core sample, it has a SystemBrowser class that works. I updated the UWP sample to use the Fall Creators Update and was able to bring in the ASP.NET Core dlls needed to compile this code. It sets up a class like this:
public LoopbackHttpListener(int port, string path = null)
{
path = path ?? String.Empty;
if (path.StartsWith("/")) path = path.Substring(1);
_url = $"http://127.0.0.1:{port}/{path}";
_host = new WebHostBuilder()
.UseKestrel()
.UseUrls(_url)
.Configure(Configure)
.Build();
_host.Start();
}
and I can confirm this gets called only once, but even if I hard code an unused IP address, I get an error that the IP is in use.
So, at this stage, the sample that exists for UWP works for the demo server but not for ours (I suspect an HTTPS issue, but that's not the error I get), and importing code that works for a Core sample, does not work either. I've spent a couple of days on this and would appreciate a nudge in the right direction.
So, to recap, the WabBrowser seems the best bet but, for my localhost IdentityServer I get this:
and if I try to use a .NET Core library that works elsewhere, it thinks a port is in use. I suspect I need to work out why WabBrowser can't connect to my local site. I have turned off Fiddler. I can browse to my https URL and get a disco document, in the browser, at https://localhost:44305/.well-known/openid-configuration.
There are extra steps necessary to enable localhost in the Web Authentication Broker -
https://msdn.microsoft.com/en-us/library/windows/desktop/jj658959%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
This website gave me the fix. Here is a synopsis:
Remove loopback isolation
For security and reliability reasons, UWP applications are not allowed to send requests to the loopback interface. While Visual Studio automatically creates exemptions for debugged apps, this feature won't be helpful in this case, as the authentication broker always executes in a separate process.
If you see this (cryptic) error message in your Windows event logs, then you're likely facing this issue:
AuthHost encountered a navigation error at URL: [...] with StatusCode: 0x800C0005.
One option to fix it is to use the loopack exemption utility developed by Eric Lawrence. It's natively included in Fiddler 4 but can also be downloaded as a standalone software. To allow the authentication broker to communicate with the loopback interface, exempt the applications starting with microsoft.windows.authhost and save your changes:
If everything was properly configured, you should now see the login/consent page returned by your server.

PushSharp GCM "Authentication Failed"

I have been using PushSharp for Apple notifications for some time in both a web service and a windows service without any issues.
On adding the code for Google GCM, it works perfectly fine on my web service and a console app I converted the service to, but it fails miserably in the windows service even when run on the same server (Amazon EC2 Instance)
The following code gives an "Authentication Failed" error for the GCM notification and has no error for the Apple notification. However, If I run the same code in my web service or a console app on the same server, it works fine.
Dim push As PushBroker = New PushBroker
Try
AddHandler push.OnNotificationSent, AddressOf NotificationSent
AddHandler push.OnNotificationFailed, AddressOf NotificationFailed
Dim appleCert = File.ReadAllBytes("FILENAME")
push.RegisterAppleService(New ApplePushChannelSettings(False, appleCert, "PASSWORD"))
push.RegisterGcmService(New GcmPushChannelSettings("API_KEY"))
push.QueueNotification(New GcmNotification().ForDeviceRegistrationId("ANDROID-TOKEN").WithJson("{""alert"":""Hello World!"",""badge"":1,""sound"":""sound.caf""}"))
push.QueueNotification(New AppleNotification().ForDeviceToken("IOS-TOKEN").WithContentAvailable(1))
Catch ex As Exception
End Try
If I remove the line:
push.QueueNotification(New GcmNotification().ForDeviceRegistrationId("ANDROID-TOKEN").WithJson("{""alert"":""Hello World!"",""badge"":1,""sound"":""sound.caf""}"))
it works perfectly on both the windows service and the web service.
Can anyone see what I am doing wrong? It is not a firewall issue. I turned off the firewall and it still didn't work. I had a lot of other code and have distilled it down to the above code to make sure there were no hidden issues.
EDIT. I set up a console app copying the code from the windows service and used the Browser API Key instead of the Server API key.
This works perfectly on both my local machine and the server machine. However the windows service still gets the same error whichever API key I use.
UPDATE: Although the Windows Service is receiving the error, it does actually send two notifications and then no more. If I stop the service and start it again, I get another two notifications even though the notification error is still being returned.
I'm really stuck. I can just continuously run the console app for now, but its hardly perfect. Any help would be gratefully received.
I had a similar issue - everything worked fine in Visual Studio but on the production server AndroidGcm authentication failed.
I figured it was something to do with the IP list in the 'Key for server applications' so I tried regenerating one with the IP address of my server. This didn't work.
Eventually in response to one of the above comments and another thread elsewhere I logged onto the Google Play Developer Console from the server and created a new key, without specifying any IP addresses.
Using this key then fixed my problem

Why won't OAuth work on web server?

I have an ASP.Net web application running on Windows Server 2012, and need to make calls to social networking sites using oauth to generate some of the page content. Everything works on my development machine, but I can't even get a single response back ("unable to connect to the remote server" error).
I disabled the firewall to test that. No luck. I created a console application to test it that way. A simple HttpWebRequest will get the html for any page I throw at it, but not any oauth request. I've used different libraries to try to achieve this, including Linq2Twitter, Spring.Social, and HigLabo. All work locally, but not on the server. I've found nothing useful in the server event log.
Can anyone give me some clues what might be happening?
EDIT: Here's some code I'm using with the HigLabo library to try to retrieve the user timeline.
using HigLabo.Net.Twitter;
var cl = new TwitterClient(consumerKey, consumerSecret, accessToken, accessTokenSecret);
var rr = cl.GetHomeTimeline();
foreach (var r in rr)
{
//Console.WriteLine(r.CreatedAt + ":" + r.Text);
}
I'm aware that accessToken & accessTokenSecret aren't/shouldn't be necessary for a simple timeline read, but this is just to make sure it works first.
This turned out to be a firewall issue, as had been suspected. But not the server firewall. This was a problem with the ISP. They had an internal firewall that was blocking all traffic to/from the social network sites. They were able to resolve it quickly with a phonecall, but it was not a coding or configuration error on my part.

Resources