Accessing Webapi on Localhost on Dev Machine from Android Emulator - xamarin

This may well be a duplicate question, but no answer from an existing question has solved my problem.
I have a WebAPI end point running on my dev machine. I've configured it to run on
.UseUrls("http://localhost:57971", "http://10.0.2.2:57971", "http://192.168.44.1:57971", "http://192.168.1.48:57971", "http://*:57971")
where:
192.168.44.1 is Desktop Adapter #2 on the emulator Networks settings tab
10.0.2.2 is the special address for the Android emulator, as set out in Google's doco (possibly not relevant to Xamarin) and
192.168.1.48 is my local IP address for my dev machine.
I have created a firewall rule permitting connections on TCP port 57971.
I researched this pretty heavily and heeded instructions such as those set out here http://briannoyesblog.azurewebsites.net/2016/03/06/calling-localhost-web-apis-from-visual-studio-android-emulator/
I'm kinda out of ideas. The annoying thing is, it fails silently. There is no exception and the output just basically shows the different threads exiting with code 0. And the application keeps running i.e. the debugging session is not returning the IDE to a "code entry" state. This may suggest that something else its at play here.
The code looks pretty innocuous to me:
protected async Task<T> GetAsync<T>(string url)
where T : new()
{
HttpClient httpClient = CreateHttpClient();
T result;
try
{
var response = await httpClient.GetStringAsync(url);
result = await Task.Run(() => JsonConvert.DeserializeObject<T>(response));
}
catch
{
result = new T();
}
return result;
}
I'm using Visual Studio 2015.
I'm using the Visual Studio emulator https://www.visualstudio.com/vs/msft-android-emulator/
Any idea how I can get wheels on the ground on this thing?
Is there a way to Ping my machine from the emulator?
Thanks

I got this working by using 169.254.80.80 i.e. I added it to the list of urls which the API serves and called that ip address from the Xamarin app.
So, in Program.cs became simple:
.UseUrls("http://localhost:57971", "http://169.254.80.80:57971")
I also had to add it to the bindings element ApplicationConfig file in the hidden .vs folder of the ASP.NET API solution. Not sure why it had to be 169.254.80.80, as that was Desktop Adapter #4.
That got it working.

Related

HttpClient->GetStringAsync() throws 0x000006F4 for https Uris

The code below works fine for me if I use an http URI, but fails for equivalent https alternative. It works fine when built and run on another machine or when I include it in another app.
GetStringAsync throws an exception: “Exception thrown at 0x770B5722 (KernelBase.dll) in .exe: 0x000006F4: A null reference pointer was passed to the stub. occurred”.
ThreadPool::RunAsync(ref new WorkItemHandler([this](IAsyncAction^ action)
{
HttpClient^ client = ref new HttpClient();
auto uri = ref new Uri(L"https://....");
auto t = create_task(client->GetStringAsync(uri));
t.then([](String^ response)
{
// response should be valid.
});
}));
Running netsh winsock reset to reset the network stack seems to fix the issue!
For me, network stack reset didn't help at all, even device reboot didn't help, but your own answer have pointed me in the right direction: it wasn't my code who suddendly went mad, it was Windows. So what actually helped in my case is starting app without debugger (that is, from Start menu) - after that app continues to work fine when started from Visual Studio. It have happened a few times now, and I can confirm that it always helps.

Wifi WPS client start in Windows 10 in script or code

I can not find how to start WPS client in Windows 10 from command prompt or powershell. When I used Linux, everything was really ease with wla_supplicant (wpa_cli wps_pbc). Is there something similar in Windows?
Does anyone know how to set up Wi-Fi network (over WPS) key without human input in Windows?
I also tried WCN (Windows Connect Now) from Microsoft as it implements WPS features. I got also samples from Windows SDK on WCN, but they could not get key by WPS (it faild). But if I use Windows user interface to connect wiothout PIN, everyting seems to be pretty fine.
I am sure that there is possibility to do that, it is very important to perform Wifi Protected Setup by button start from the command prompt or app (C++/C#) without human intrusion or input (once WPS is on air, Windows should automatically get the network key and connect then).
I don't know if it's too late to answer, just put what I know in here and hope it can help.
First, if your system has updated to 16299(Fall Creator Update), you can just simply use new wifi api from UWP.
Install newest Windows SDK, create a C# console project, target C# version to at least 7.1, then add two reference to the project.
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.16299.0\Windows.winmd
After all of that , code in below should work.
using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.WiFi;
class Program
{
static async Task Main(string[] args)
{
var dic = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
if (dic.Count > 0)
{
var adapter = await WiFiAdapter.FromIdAsync(dic[0].Id);
foreach (var an in adapter.NetworkReport.AvailableNetworks)
{
if (an.Ssid == "Ssid which you want to connect to.")
{
// Fouth parameter which is ssid can not be set to null even if we provided
// first one, or an exception will be thrown.
await adapter.ConnectAsync(an, WiFiReconnectionKind.Manual, null, "",
WiFiConnectionMethod.WpsPushButton);
}
}
}
}
}
Build and run the exe, then push your router's button, your pc will be connect to the router.
But if you can not update to 16299, WCN will be your only choice. You may already notice that if call IWCNDevic::Connect frist with push-button method, the WSC(Wifi Simple Configuration) session will fail. That's because WNC would not start a push-button session as a enrollee, but only as a registrar. That means you have to ensure that router's button has been pushed before you call IWCNDevic::Connect. The way to do that is using Native Wifi api to scan your router repeatedly, analyse the newest WSC information element from the scan result, confirm that Selected Registrar attribute has been set to true and Device Password Id attribute has been set to 4. After that, query the IWCNDevice and call Connect function will succeed. Then you can call IWCNDevice::GetNetworkProfile to get a profile that can use to connect to the router. Because it's too much of code, I will only list the main wifi api that will be used.
WlanEnuminterfaces: Use to get a available wifi interface.
WlanRegisterNotification: Use to register a callback to handle scan an connect results.
WlanScan: Use to scan a specified wifi BSS.
WlanGetNetworkBsslist: Use to get newest BSS information after scan.
WlanSetProfile: Use to save profile for a BSS.
WlanConnect: Use to connect to a BSS.
And about the WSC information element and it's attributes, you can find all the information from Wi-Fi Simple Configuration Technical Specification v2.0.5.
For Krisz. About timeout.
You can't cast IAsyncOperation to Task directly. The right way to do that is using AsTask method. And also, you should cancel ConnectAsync after timeout.
Sample code:
var t = adapter.ConnectAsync(an, WiFiReconnectionKind.Manual, null, "",
WiFiConnectionMethod.WpsPushButton).AsTask();
if (!t.Wait(10000))
t.AsAsyncOperation().Cancel();

Visual Studio android emulator httprequest fails

So I've been working on a xamarin PCL project targeting android and windows store app and I've had this issue for about two weeks now. One of the very first things this app does is to make an http request to a yahoo service when the user tries to search for something.
Now, on the windows store app project, this works just fine. However, whenever I'm debugging the android project, this fails miserably. It times out and I get a TaskAbortedException.
I've navigated with the browser within the android emulator to the restful service url and I do get a response in the browser but nothing when I make the http request. I have tried everything I could think of but no cigar. I have researched this for weeks now and I have yet to find an answer. It should be noted that I'm making the request within the PCL project with HttpClient.
Here's the code where this happens:
var queryUrl = string.Format(QUERY_URL_TEMPLATE, TickerSearch);
try
{
var requestTask = httpClient.GetStringAsync(queryUrl);
requestTask.ContinueWith(t =>
{
var responseDto = JsonConvert.DeserializeObject<TickerSearchResultDto>(t.Result);
TickerSearchResults = responseDto.ResultSet.Result;
});
}
catch (Exception ex)
{
}
Any help is greatly appreciated.

SignalR Hub method is not called

I have a SignalR hub and two clients (Windows and PCL for Android and iOS). Neither of the clients is able to call some methods on the server. This behaviour is quite odd, since the methods look very similar. Moreover, a colleague of mine is able to call methods I cannot call, and vice versa, does not invoke methods that I invoke with no problems.
Here is an example of a method, which works for me and does not work for my colleague:
public override async Task<bool> RefreshArray(User user, int waitMilis)
{
var cts = new CancellationTokenSource();
try
{
cts.CancelAfter(waitMilis);
await Proxy.Invoke("RefreshArray", user);
return true;
}
catch (Exception ex)
{
OnExceptionOccured(ex);
return false;
}
}
And a method which does not work for me, but works for my colleague:
public override async Task<bool> RequestInformation(User user, Product product, int waitMilis)
{
var cts = new CancellationTokenSource();
try
{
cts.CancelAfter(waitMilis);
await Proxy.Invoke("RequestInformation", user, product);
return true;
}
catch (Exception ex)
{
OnExceptionOccured(ex);
return false;
}
}
Yes, me and my colleague have exactly the same code. And no, there are no typos or different arguments. I have tried to get as much data from the client connection as possible, by setting _connection.TraceLevel = TraceLevels.All; However, I did not get any information on the invoked methods, just on the replies from the hub. When calling RefreshArray, I got exactly the data I requested. When calling RequestInformation, the debugger never even hit the breakpoint in the hub method and the _connection.Trace displayed only this: 11:22:45.6169660 - 7bc57897-489b-49a2-8459-3fcdb8fcf974 - SSE: OnMessage(Data: {})
Has anybody solved a similar issue? Is there a solution?
UPDATE 1
I just realized that I have encountered almost the same issue about a year ago (Possible SignalR bug in Xamarin Android). StackOverflow has also pointed me to a question with almost the same issue (SignalR on Xamarin.iOS - randomly not able to call Hub method), just related to iOS and Azure. However, I got the same proble even outside Xamarin, on Windows Phone 8.1 and and Windows 10 Universal App. Moreover, I am running the server just locally, so it is not an issue od Azure. Is it really possible, that a 2 years old bug has no solution?
UPDATE 2
I have just created a simple console application with SignalR.Client. In the console application every method worked just fine. Amazingly, also the Windows 10 Universal Application started to behave as expected - every hub method was invoked correctly. Windows Phone 8.1 also improved its behaviour (all hub methods invoked). However, every now and then the connection tried to reconnect periodically (for no apparent reason), leading to Connection started reconnecting before invocation result was received. error. The Android application still behaved as before.
So I tried to replicate my previous steps and created another console application, but this time with SignalR.Client.Portable library. To my dissapointment, there was no change in the Android application behaviour.
Next week we will start to test our application on iOS, so I really wonder what new oddities will we encounter.
I have managed to solve the problem (at least so it seems). As it turned out, there is some weird stuff going around, when an application receives an answer from SignalR hub. It seems as if the HubProxy was blocked for a certain period of time on Android, while it drops the connection and starts to reconnect periodically on Windows Phone, not waiting for an asnwer from the hub.
The implementation of RefreshArray on the hub was something like this:
public async Task RefreshArray(User user)
{
await Clients.Caller.SendArray(_globalArray);
await Clients.Caller.SendMoreInformation(_additionalInfo);
}
Because the method sent two methods as an answer, the client Proxy got stuck and each platform handled it in its own unexpected way. The reason why some methods were called on my computer and not on colleagues was, simply, because we had different position of breakpoints, which enabled the application to resolve at least some requests and responses.
The ultimate solution was to add some synchronization into the invokation of methods. Now my hub calls only await Clients.Caller.SendArray(_globalArray);. This is then handled on the client with a ArraySent(string[] array) event, which then subsequently invokes the SendMoreInformation() method on the hub.

Basic Node.js examples not working on Windows 7

I installed node.js from http://nodejs.org/#download, v0.6.6. I am using Windows 7 32-bit.
I've been going through various tuts online, and want to experiment while doing so, but I cannot seem to get node.js working. Node will run my .js file, but any request from the browser times out.
Here is a typical Hello World example that does not work:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337);
Pointing my browser at 127.0.0.1:1337 or localhost:1337 does not work. The request from the browser times out. I've also tried listen(1337,'0.0.0.0') and listen(1337,'127.0.0.1').
I know the server is running; if I CTRL+C and stop node, the browser immediately comes back with ERR_CONNECTION_RESET.
I also tried running the code in this gist, which will not work: https://gist.github.com/1339846. I end up with the console output "Listening!" and then nothing else.
Furthermore, I have tried different ports, and my firewall is off via
netsh firewall set opmode mode=disable
I tried with firewall totally disabled, and the service stopped. If I check connections using netstat -noa, I can see node has a bunch of connections opened for the browsers, all in state CLOSE_WAIT. So it looks like connections are happening, but node.js just isn't working.
The callback function that is supposed to be initiated by a request never executes - I sprinkled some console.log statements in various areas, and they all execute except any in the callback.
I uninstalled, re-installed, tried a couple previous builds, restarted my machine...nothing.
Any help is appreciated!
UPDATE: I have just about given up. I've tried everything I can think of, and it ended up being easier to run node.js in an instance of Ubuntu in VirtualBox than grasp at straws.
!!!!!! Same problem happened for me....
Here is a solution which I have yet to find anywhere:
Look in Windows Firewall with Advanced Security and see if Evented I/O for V8 JavaScript is blocked or appears two times.
If so unblock it and delete the duplicated entry. If you install/uninstall/install nodeJs, there will be 2 entries.
Also when node first runs the Window Firewall dialog opens asking if you want to allow node to have firewall access. If you press "No" or just close the window without asking, it will create Evented I/O for V8 JavaScript AND IT WILL BE BLOCKED.
I ran into the same problem and after reading through the documentation, I unexpectedly ran into what I believe is the solution. In my instance I was noticing that the incoming requests WERE being delivered to node, but the response was never having its 'end' event triggered. So altering incoming firewall rules in windows did not seem to be related to the problem.
So, http.createServer takes in a single argument - a function which should include a request and response parameter. The request parameter seemed to be where the problem lay. The request parameter is an instance of http.incomingMessage. This class only had like one event type, but it was itself also an implementation of Stream.Readable, which is where I found the 'end' event that wasn't triggered. Really for no other reason that to just test which was the first event not triggered, I just added a listener for another type of event ('readable'), and only added a console.log line to it which made the whole thing work.
So the code looks simply something like this:
var http = require("http");
http.createServer(function (request, response) {
console.log('request');
request.on('readable', function(){
console.log('request readable');
});
request.on("end", function () {
console.log('request end');
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
The above code works, whereas the earlier version below without a 'readable' event listener does not ever respond:
var http = require("http");
http.createServer(function (request, response) {
console.log('request');
request.on("end", function () {
console.log('request end');
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
I am not sure why this works except for a little clue in the documentation which reads:
In some cases, listening for a 'readable' event will cause some data
to be read into the internal buffer from the underlying system, if it
hadn't already.
I just tried it and it works for me. Make sure you are not blocking node with your firewall.
I am using Windows 7 32-bit.
What edition of Windows 7 are you using? Eg. Home Premium, Professional, Ultimate?
A thread on the npm github project mentions similar symptoms while installing nodejs modules using npm, and comments seem to narrow it down to being caused by Windows 7 Professional. It being 32/64-bit doesn't seem to matter.
I am having both the problem you describe, as well as the npm installation problem, and am running on Windows 7 Professional 64-bit.
Using XPMode (a workaround mentioned in the npm thread) has allowed me to workaround both of these issues. Although, I suppose this is just a more Windows-y version of your use of Ubuntu in VirtualBox.
Other workarounds tried without success:
Make/run a Debug build of v0.6.6
Make/run a Debug build of v0.6.5 (actually crashed in startup)
Set various Compatability Modes on the installed node.exe
Prepackaged Windows installer of v0.6.5
Go to "Control Panel\All Control Panel Items\Windows Firewall\Allowed
Programs"
Click Allow Programs
select nodejs from the list.
This fixed all the problems for me
I was having the same problem with this code (Http Server example from this link: http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/)
var http = require("http");
http.createServer(function (request, response) {
request.on("end", function () {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
I tried windows 7 64-bit version, windows XP virtual machine, ubuntu virtual machine ... nothing! It only worked after I commented the "request.on" line. Your example (which doesn't have this line) worked fine for me. I'm using the latest stable build from node.js (v0.10.18 for windows or linux). Hope this helps anyone having trouble with this.

Resources