Xamarin HttpClient.GetStringAsync not working on Xamarin.Droid - c#

I'm really new in Xamarin development, and I just tried Xamarin.Forms to Develop Android & iOS App with shared Code, and what I'm trying to do here is to get data from API with Plugin.RestClient NuGet package.
Here's my MainViewModel.
public MainViewModel(){
InitializeDataAsync();
}
public async Task InitializeDataAsync(){
var employeeServices = new EmployeeServices();
EmployeesList = await employeeServices.getEmployeesAsync();
}
And here's my Services
public async Task<List<Employee>> getEmployeesAsync(){
RestClient<Employee> restClient = new RestClient<Employee>();
var employeeList = await restClient.GetAsync("http://localhost:3000/employee");
return employeeList;
}
And this is my RestClient
public async Task<List<T>> GetAsync(string WebServiceUrl){
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceUrl);
Debug.WriteLine(WebServiceUrl);
Debug.WriteLine(json);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
The code works fine on my iPhone Emulator. I can see my Debug for the url and json response. But on my Android Emulator there's nothing on the list. I can't even find my Debug for url and json response, I already checked my Application Output and my Device Log (I used Xamarin Studio for Mac btw).
I also already add internet permission on my Android Manifest.
What should I do?

You can only access localhost on your local machine. You need to change localhost to the IP address of the machine on which your api is hosted.
So the api endpoint for
http://localhost:3000/employee
should be something like
http://192.168.0.5:3000/employee

If you are getting a timed out error then it's probably because "localhost" to the Android OS means the phone itself, which is probably not where you're not running the web server. There are some special IP addresses you can use while testing with Android emulators to reach the host OS:
The Google emulators allow you to reach the host OS from 10.0.2.2.
The Microsoft Android emulator allows you to reach the host OS from 169.254.80.80.
You could try changing your URL based on the type of emulator you are using. Alternatively, you can plugin your workstations IP address instead, but this is less desirable because it can change.
If this doesn't allow you to reach the server then you may consider looking at any firewalls to see if your traffic is being blocked.

Related

Xamarin Android - VpnService is blocking all apps

An app I'm designing uses the VpnService, along with the VpnService.Builder, classes to generate a VPN in order to block traffic from specific apps. According to the documentation over at developer.android.com, all apps should be allowed through the VPN until Builder.AddAllowedApplication or Builder.AddDisallowedApplication is called.
When my VPN service starts up, for some reason, all apps are being disallowed which is strange. As soon as I disconnect from the VPN, all apps become available again. I need to to allow all, unless otherwise specified (which is what the documentation says should be happening). I start the VPN by calling the following:
private string _sTag = typeof(VpnService).Name;
private VpnServiceBinder _objBinder;
private ParcelFileDescriptor _objVpnInterface = null;
private PendingIntent _objPendingIntent = null;
...
if (_objVpnInterface == null)
{
Builder objVpnBuilder = new Builder(this);
objVpnBuilder.AddAddress("10.0.0.2", 32);
objVpnBuilder.AddRoute("0.0.0.0", 0);
// Form the interface
_objVpnInterface = objVpnBuilder.SetSession("Squelch").SetConfigureIntent(_objPendingIntent).Establish();
// Disallow instagram as a test
objVpnBuilder.AddDisallowedApplication("com.instagram.android");
// Set flag
_bVpnIsRunning = true;
}
So in the above instance, instagram should be the only blocked app, but all traffic appears to be blocked (can't use the chrome app, facebook, etc). Is there something I am missing in regards to this? Should I be specifying something before/after establishing the interface? Any help or direction would be greatly appreciated!
Note: In case it matters, I am targeting android 6.0 and higher. I can provide more source if required.
addDisallowedApplication:
By default, all applications are allowed access, except for those denied through this method. Denied applications will use networking as if the VPN wasn't running.
AddDisallowedApplication excludes the application from your VPNService and allows it to continue to use the "non-VPN" networking stack.
addAllowedApplication:
Adds an application that's allowed to access the VPN connection
Note: You can use an allowed or disallowed list, but not both at the same time.
So lets say we want to "block" any Chrome package from accessing the normal networking stack and redirect any Chrome apps from accessing the network via our "blocking" VPN, we can add all Chrome app package names to our VPNService implementation.
Note: there are 4(?) different Chrome apps, alpha, beta, etc.... so lets just block any package that has the name chrome in it, not really ideal, but for an example it works.
using (var pm = Application.Context.PackageManager)
{
var packageList = pm.GetInstalledPackages(0);
foreach (var package in packageList)
{
if (package.PackageName.Contains("chrome"))
{
Log.Debug(TAG, package.PackageName);
builder.AddAllowedApplication(package.PackageName);
}
}
}
After you .Establish() the VPN connection, all Chrome applications networking will be redirected to your VPNService and thus blocked.

Why will this code relying on RestSharp run fine in my application when run on Windows 1709 but not 1703

I had someone build an application that calls home to confirm the user is in good standing on start-up. When the application is installed on a machine running Windows 1709 I can see the call to the api endpoint when the application starts. However, when I install on Windows 1703 the application does not ever call home (that is the server shows no contact attempt from the ip address where the installation is occurring). I have tried to Install an older .Net (4.5.2) but I get a message in Windows that the installation is blocked because a newer version exists on the machine.
The application installs 106.2.1.1
Here is a block of code - I have anonymized the token and the API endpoint
class RestRoutines
{
public bool testToken(string token)
{
bool passed = false;
var client = new RestClient("https://api.myanonymousapi.com/v1/user-tasks/");
client.AddDefaultHeader("Authorization", token); // "Token validToken");
var response = client.Execute(new RestRequest());
if (response.StatusDescription == "OK")
passed = true;
return passed;
}
}
Is there a dependency we are missing or is something wrong with the code above that causes it to fail in the earlier version of Windows?

Deployed on Azure bot does not response

I start investigating BotFramework and encountered one annoying issue.
Created "Hello world" bot.
Here if the code
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
// return our reply to the user
Activity reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters");
await connector.Conversations.ReplyToActivityAsync(reply);
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
It works fine locally
Deployed it on Azure.
Set correct BotId, MicrosoftAppId and MicrosoftAppPassword parameters in web.config.
URL with my bot is http://funnyskypebot20171026010946.azurewebsites.net and it looks it works
But when i try to "communicate" with bit via Bot Framework Channel Emulator i do not receive any messages back ...
What could be wrong ? Please advise.
I assume you already followed the steps in https://learn.microsoft.com/en-us/bot-framework/deploy-dotnet-bot-visual-studio for deployment to Azure.
Have you seen this https://learn.microsoft.com/en-us/bot-framework/debug-bots-emulator with regards to debugging remotely using ngrok?
If you are using Visual Studio, on the toolbar, you can click on 'View -> Server Explorer'. Under 'Azure -> App Service', you should see your resource group there. Under your resource group, you should see your app service. Right-click and select 'Attach Debugger' so that you can view the output ('View -> Output') and debug your deployed app service.
Internal server error generally means there is some sort of issue with your code. Try debugging locally using ngrok. You can change your endpoint in the dev portal to the one that ngrok generates when you use this command ngrok http 3979 -host-header="localhost:3979" change to the port your bot runs on.
More info:
Blog Post
Blog Post

Receive WNS push notfication on Windows phone silverlight 8.1

I have windows phone 8.1 silverlight application where I want to receive Notfications using the new framework, WNS.
I have in the package.appxmanifest: <identity name="4657xxxxxxx" publisher="CN=xxxxx" version="1.0.0.0"/> and added it to the Mobile Service Hub.
For this I have removed old references to MPNS usings, and added the following for WNS:
using Windows.UI.Notifications;
using Windows.Networking.PushNotifications;
using Windows.UI.StartScreen;
This resulted in a new way of getting the channelURI:
public static PushNotificationChannel CurrentChannel { get; private set; }
public async static Task<bool> UploadChannel()
{
bool newChannel = false;
var channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
var settings = Windows.Storage.ApplicationData.Current.LocalSettings.Values;
object oldChannel;
settings.TryGetValue("channelURI", out oldChannel);
if ((oldChannel as PushNotificationChannel).Uri != CurrentChannel.Uri)
{
settings.Add("channelURI", CurrentChannel);
newChannel = true;
}
try
{
await App.MobileService.GetPush().RegisterNativeAsync(channel.Uri);
}
catch (Exception exception)
{
CurrentChannel.Close();
HandleRegisterException(exception);
}
CurrentChannel.PushNotificationReceived += CurrentChannel_PushNotificationReceived;
return newChannel;
}
private static void HandleRegisterException(Exception exception)
{
MessageBox.Show("error - retry pushchannel");
}
Additionally I removed the ID_CAP_PushNotification based on microsofts update info
I do not get a channel I get an error:
The application does not have the cloud notification capability. (Exception from HRESULT: 0x803E0110)
solution
Searched for the error and found this link, This can be solved as stated in the answer below by accessing package.appxmanifest and enable Internet (Client & Server).
ERROR 2
Then it the UploadChannel()function should work. However the Register API call await App.MobileService.GetPush().RegisterNativeAsync(channel.Uri); results in an error on the server:
Message='Could not register with the 'mpns' platform. Error received: 'Unsupported channel uri: 'https://db3.notify.windows.com . . . .
The error makes sense but I have no idea on how to solve it.
Ekstra
On the server I can subscribe with the URI, and receive notifications. But not on the client. Is this how it should be or?
On Client side:
Ideally, to use WNS, you should remove all references to MPNS from WMAppManifest.xml and add the info provided by Windows Store to your package.appxmanifest.
I understand that you are migrating from WP8 to WP8.1. So in your package.appxmanifest, edit the code so that it looks like this:
<Identity Name="4657xxxxxxx" Publisher="CN=xxxxx" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="xxxx" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
Note: The 0s in the PhonePublisherId are intentional. I have no idea why, but the app wouldn't work when I did not provide them as such.
You are doing the channel uri request right:
PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
string channelUri = channel.Uri;
You should also set the Internet (Client & Server) capability in Package.appxmanifest to be checked.
To receive notifications on the client, you should intercept the received notification as described here:
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj709907.aspx
On Server Side:
The error "Unsupported Channel URI" occurs because you are using the MPNS methods to process the URI in your Azure server.
Refer here for the proper way to do it using WNS: http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-windows-universal-dotnet-get-started-push/
Adding internetClient capability should resolve this error.
Creating a notification channel results in an WPN_E_CLOUD_INCAPABLE error
Cause: Your app has not declared the Internet capability in its app manifest (package.appxmanifest).
Fix: Ensure that your app manifest has declared Internet capability. In the Visual Studio manifest editor, you will find this option under the Capabilities tab as Internet (Client).
The .NET client SDK for Azure Mobile doesn't currently support using WNS in Windows Phone 8.1 Silverlight applications. You have to use MPN or change your project to a NON-silverlight project type.
Reference (see Elio's response): https://social.msdn.microsoft.com/Forums/azure/en-US/1aa29977-a26d-4054-89b2-c853cbd35c18/wns-for-windows-phone-silverlight-81-apps-with-azure-mobile-services?forum=azuremobile
I'm not sure if they'll update it to support this as Silveright for 8.1 is primarily for backwards compat with existing apps and not many of them were using Mobile Services as it is newer.
In my case, select the ARM platform in my project settings did the trick. I was in "Any CPU".

How to consume java REST webservice in windows phone 8?

I am trying to consume Java REST Webservice in windows phone 8.But it is always giving 404 (page not found) exception (system.net.http.httpexception).That means not able to connect to webservice.
Following is the client code which i used for consuming webservice.
try
{
HttpClient http = new HttpClient();
String result = await http.GetStringAsync("http://192.168.0.56:8078/sample/page/name");
MessageBox.Show(result);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
Please help.Thanks in advance.
Issue solved.Emulator was not able to connect to internet,which was the problem.I tried in windows phone and its working fine.Thanks #akshay2000.
Check your Network Adapters and Verify that there are Hyper-V in their names or 'v' prefixes on the Adapter names, if there are you should check if they are enabled, and enable them if disabled.
If you have nothing like that you should repair the sdk, and that will fix the issue.

Categories