connectivity plugin

AlessandroCaliaroAlessandroCaliaro Alessandro CaliaroITMember ✭✭✭✭✭

@JamesMontemagno Hi!
I've a problem with your connectivity plugin.

I write this code:
if(CrossConnectivity.Current.IsConnected == false){
await DisplayAlert("Connessione", "Connessione non presente", "Ok");
return;
}
else if(CrossConnectivity.Current.IsReachable(entryIpServer.Text).Result == false) {
await DisplayAlert("Connessione", "Host non raggiungibile", "Ok");
return;

but I'm not able:
1- to set a breakpoint on the "if" line
2- the app "freeze"

do I have forget something?
do I initialize??
Thanks
Alessandro

«1

Posts

  • TektonTekton Terrance Wood USMember ✭✭✭
    edited March 2015

    @AlessandroCaliaro I think that if IsConnected == false, then IsReachable will always fail (and, I believe it's only meant to be used async). I've been using it like this:

    public async Task<bool> MyTask ()
    {
        // ...
        if (CrossConnectivity.Current.IsConnected) {
            bool isRemoteReachable = await CrossConnectivity.Current.IsReachable (Settings.ApiDomain).ConfigureAwait (false);
            if (isRemoteReachable) {
                // ...
            }
        }
        // ...
    }
    
  • AlessandroCaliaroAlessandroCaliaro Alessandro Caliaro ITMember ✭✭✭✭✭

    @Tekton Thanks for your answer.
    The IsConnected is "true" in my test so I think this is not the problem...

  • ChristophThielChristophThiel Christoph Thiel DEMember ✭✭

    if(CrossConnectivity.Current.IsConnected == false) { await DisplayAlert("Connessione", "Connessione non presente", "Ok"); return; } else // CrossConnectivity.Current.IsConnected is true. { // Now you will check if your server is reachable. if(CrossConnectivity.Current.IsReachable(entryIpServer.Text).Result == false) { await DisplayAlert("Connessione", "Host non raggiungibile", "Ok"); return; } }

    Should work!

  • AlessandroCaliaroAlessandroCaliaro Alessandro Caliaro ITMember ✭✭✭✭✭

    I don't see differences between mine and yours code

  • JamesMontemagnoJamesMontemagno James Montemagno USXamarin Team, Developer Group Leader Xamurai

    The issue here is that you are mixing the TPL with async/await world when you do:

    if(CrossConnectivity.Current.IsReachable(entryIpServer.Text).Result == false) 
    

    update it to this call:

    var canReach = await CrossConnectivity.Current.IsReachable(entryIpServer.Text);
    if(canReach == false){
    } 
    
  • ChristophThielChristophThiel Christoph Thiel DEMember ✭✭

    Oh yeah, sorry, please forget my useless comment.

  • AlessandroCaliaroAlessandroCaliaro Alessandro Caliaro ITMember ✭✭✭✭✭

    @JamesMontemagno , do your update but I have again problems.
    The first is that I can't insert a breakpoint in

        if(CrossConnectivity.Current.IsConnected == false)
    

    The second is that the app continue to freeze

  • JamesMontemagnoJamesMontemagno James Montemagno USXamarin Team, Developer Group Leader Xamurai

    Did you set the proper permissions documented in the readme for each platform? https://github.com/jamesmontemagno/Xamarin.Plugins/blob/master/Connectivity/README.md

  • AlessandroCaliaroAlessandroCaliaro Alessandro Caliaro ITMember ✭✭✭✭✭

    yes

  • JamesMontemagnoJamesMontemagno James Montemagno USXamarin Team, Developer Group Leader Xamurai

    Is there any stack trace at all that is happening on? Is it android or iOS?

    Do you have a small repo that you could try with file->new and try that so I can look at the code. I have my main samples on the github page and have never had any issues. https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/TestProject/TestAppForms

  • AlessandroCaliaroAlessandroCaliaro Alessandro Caliaro ITMember ✭✭✭✭✭

    I'm trying your TestAppForms but I've a problem: I can't restore packages

    The 'Xam.Plugin.Contacts 1.0.0-alpha' package requires NuGet client version '2.8.3' or above, but the current NuGet version is '2.8.1.0'.

  • HolgerRousselle.4906HolgerRousselle.4906 Holger Rousselle DEMember ✭✭

    Package Manager Console Host Version 2.8.50926.663

  • AlessandroCaliaroAlessandroCaliaro Alessandro Caliaro ITMember ✭✭✭✭✭

    @HolgerRousselle.4906 Thanks. How can I update PMC?

  • JamesMontemagnoJamesMontemagno James Montemagno USXamarin Team, Developer Group Leader Xamurai

    I have updated the sample to the latest version that is set to 2.8.1. Sync and get again.

    I also have a smaller sample in: https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/Connectivity/Common/ConnectivityPlugin/samples

  • HolgerRousselle.4906HolgerRousselle.4906 Holger Rousselle DEMember ✭✭
    edited March 2015
  • AlessandroCaliaroAlessandroCaliaro Alessandro Caliaro ITMember ✭✭✭✭✭

    @JamesMontemagno thanks, not it works, after 1.0.2 update.
    The only strange thing is about breakpoints. If I put a breakpoint on

        if(CrossConnectivity.Current.IsConnected == false)
    

    it is moved on another line
    Xamarin Studio for Windows

  • JamesMontemagnoJamesMontemagno James Montemagno USXamarin Team, Developer Group Leader Xamurai

    I am not sure what is going on there...

    Perhaps you could do this:

    var connected = CrossConnectivity.Current.IsConnected;
    
    if(!connected)
    {
    }
    

    and put break points on the var and on the if?

  • AlessandroCaliaroAlessandroCaliaro Alessandro Caliaro ITMember ✭✭✭✭✭

    you can take a look here

    http://screencast.com/t/b0FvpbBDsEDp

    in debug mode, I can set breakpoint only ouside the buttonLogin.Clicked event
    if debug is not running, I can set breakpoint also inside the Clicked event, but when I run the debug, these breakpoints disappeare

    Can be a async await problem? in other situation I can debug async await routines

  • Sajjad.SarkoobiSajjad.Sarkoobi armin design USMember

    hi all
    could you please give me a code that I can use with connectivity plugin to see if my site isrechable or not?
    I've tried many methods with this plugin but always its going to crash my simulator!!
    thanks all

  • AlessandroCaliaroAlessandroCaliaro Alessandro Caliaro ITMember ✭✭✭✭✭

    @SajjadSarkoobi if(Connectivity.Plugin.CrossConnectivity.Current.IsConnected){

    Have you inserted the plugin also in Android Project?

  • Sajjad.SarkoobiSajjad.Sarkoobi armin design USMember

    @AlessandroCaliaro
    is connected works fine. :smile:
    but i have problem with IsReachable..

    string host = "www.google.com"; bool rechable =CrossConnectivity.Current.IsReachable (host,1000).Result;

    this doesn't work !! and in my xamarin android player it crash and freez my program.

    also if i use this code:
    var canReach = await CrossConnectivity.Current.IsReachable(host); if(canReach == false){ }

    I have an error in "await" ... and if i delete "await" it crash and freez again.!! :neutral:

    also I have tried this:

    public async Task<bool> IsReachable(string host,int msTimeout = 5000) { bool ping = await CrossConnectivity.Current.IsReachable (host); return ping; }
    how can i use "IsReachable" ??
    thanks

  • TektonTekton Terrance Wood USMember ✭✭✭

    @SajjadSarkoobi IsReachable is for local hosts. IsRemoteReachable is for remote hosts.

  • Sajjad.SarkoobiSajjad.Sarkoobi armin design USMember

    @AlessandroCaliaro
    Thanks alot,, I miss to use async in button click event
    button.Click+= async (object sender, EventArgs e) => {

    @Tekton
    thanks
    ya I miss this important part too.

    sorry I'm new in this way of coding :smile:

  • FredyWengerFredyWenger Fredy Wenger CHInsider ✭✭✭✭✭

    @SajjadSarkoobi:
    If a user has really helped you with an answer (Allessandro, Tekton), you should like his work (mouse to the right corner if the helping message and the click on the Like icon) :wink:

  • Sajjad.SarkoobiSajjad.Sarkoobi armin design USMember

    hi all
    I use this code:
    if (CrossConnectivity.Current.IsConnected==true){ bool connect=await CrossConnectivity.Current.IsRemoteReachable("www.google.com",80,5000); if (connect==true) { var intent=new Intent(this,typeof(Tab_Host)); StartActivity (intent); }else{ Toast.MakeText(this,"Cannot Connect to Server!",ToastLength.Long).Show(); } }else{ Toast.MakeText(this,"Check your Internet Connection",ToastLength.Long).Show(); } };
    in Debugging mode every things run perfect, but in release mode and when I install my program in many different type of devices Ver. (2.3.3, 4.0.3 , 4.1.1) all of them just returned "Cannot Connect to Server!"
    it means that "IsRemoteReachable" returned False in release simulation and hard devices.?
    I'm using trial mode of xamarin now!
    any help ? thanks

  • TektonTekton Terrance Wood USMember ✭✭✭
    edited May 2015

    @SajjadSarkoobi Maybe look at your assembly linking settings in the Android project? You might also try using a label to see the value of certain variables, or something like that (in Release mode).

  • SweeHengSweeHeng Swee Heng Cheah USMember
    edited June 2015

    @JamesMontemagno Strange thing... The IsRemoteReachable call never stops running... not returning anything...
    Here's my implementation using DependencyService.

    public async Task<bool> CheckRemoteReachability()
        {
            try
            {
                IsRemoteReachable = await CrossConnectivity.Current.IsRemoteReachable("www.google.com", 999, 1000);
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return IsRemoteReachable;
        }
    
  • AndrewMobileAndrewMobile Andrei N USMember ✭✭✭✭

    @SweeHeng what platform

  • SweeHengSweeHeng Swee Heng Cheah USMember

    @AndreiNitescu It's for Android platform. Any idea why this can happen?

  • AndrewMobileAndrewMobile Andrei N USMember ✭✭✭✭
    edited June 2015

    This is the source of the ConnectivityImplementation for Android:
    https://github.com/jamesmontemagno/Xamarin.Plugins/blob/master/Connectivity/Connectivity/Connectivity.Plugin.Android/ConnectivityImplementation.cs

    return await Task.Run(async () =>
          {
            try
            {
              var sockaddr = new InetSocketAddress(host, port);
              using (var sock = new Socket())
              {
    
                  await sock.ConnectAsync(sockaddr, msTimeout);
                  return true;
    
              }
            }
            catch (Exception ex)
            {
              Debug.WriteLine("Unable to reach: " + host + " Error: " + ex);
              return false;
            }
          });
    

    as you can see ConnectAsync uses the timeout (you use 1000) so it shouldn't be an issue

    Are you sure the issue is not somewhere else in your code?

    Note that the way you throw exceptions should better be this:
    catch(Exception) { throw ; }
    to preserve call stack

  • AshleyJacksonAshleyJackson Ashley Jackson GBMember ✭✭

    I am having this exact same issue issue in the Android part of my Xamarin Forms Project.

                if (CrossConnectivity.Current.IsConnected)
                {
                    try
                    {
                        bool connect = await CrossConnectivity.Current.IsRemoteReachable("www.google.com", 80, 5000);
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
    

    Is connected returns true, but IsRemoteReachable nevers returns a response. This works fine from the IOS app in the Forms project.

    Did you get a resolution to this?

    Cheers Ash.

  • andreacurtiandreacurti andrea curti ITUniversity ✭✭

    Hi @JamesMontemagno

    I'm working with your plugin to figure out if our company intranet is reachable.
    The intranet is only reachable if i'm inside the company network, or if i use a mobile phone with the company apn configured.

    I tried this code:

    App.NetworkWorks = await CrossConnectivity.Current.IsRemoteReachable (App.SPSiteUrl,80,5000).ConfigureAwait (false);

    where App.SPSiteUrl is the Intranet address. The strange thing is that the result is always true, even if the host is not reachable.

    what's wrong with my approach?

  • JamesMontemagnoJamesMontemagno James Montemagno USXamarin Team, Developer Group Leader Xamurai

    Have you tried just IsReachable? Can you open a browser and hit the site url? You could also try the code in the project that it is calling.

  • DavidRihaDavidRiha David Riha USMember ✭✭

    @SweeHeng I have the exactly same problem, did you solve it somehow? Or found some workaround?

  • DavidRihaDavidRiha David Riha USMember ✭✭
    edited January 2016

    Ok, I solved it.

    new InetSocketAddress(host, port) was causing the deadlock.

    instead of calling
    await CrossConnectivity.Current.IsRemoteReachable(host);

    I am now calling

    await IsRemoteReachable(host);

    which I redefined this way:

    private static async Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000)
            {
                if (string.IsNullOrEmpty(host))
                    throw new ArgumentNullException("host");
    
                if (!CrossConnectivity.Current.IsConnected)
                    return false;
    
                host = host.Replace("http://www.", string.Empty).
                  Replace("http://", string.Empty).
                  Replace("https://www.", string.Empty).
                  Replace("https://", string.Empty);
    
                return await Task.Run(async () =>
                {
                    try
                    {
                        InetSocketAddress sockaddr = await RunBlockingFuncOnOtherThread(() => new InetSocketAddress(host, port), msTimeout);
                        if (sockaddr == null)
                            return false;
    
                        using (var sock = new Socket())
                        {
                            await sock.ConnectAsync(sockaddr, msTimeout);
                            return true;
                        }
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                });
            }
    
        public static async Task<T> RunBlockingFuncOnOtherThread<T>(Func<T> function, int msTimeout)
        {
            var tcs = new TaskCompletionSource<T>();
            new System.Threading.Thread(async () =>
            {
                T result = function.Invoke();
                if (!tcs.Task.IsCompleted)
                    tcs.TrySetResult(result);
            }).Start();
    
            Task.Run(async () =>
            {
                await Task.Delay(msTimeout);
                if (!tcs.Task.IsCompleted)
                    tcs.TrySetResult(default(T));
            });
    
            return await tcs.Task;
        }
    
  • JamesMontemagnoJamesMontemagno James Montemagno USXamarin Team, Developer Group Leader Xamurai

    @DavidRiha, I do take pull requests on the plugins and love community contributions. It is much better than just letting it linger here in the forums :)

  • RonaldKasperRonaldKasper Ronald Kasper ATMember ✭✭

    @JamesMontemagno I've now spent some time to get your plugin running. Am I missing something?

    I just tried

    var googleReachable=await CrossConnectivity.Current.IsRemoteReachable("http://www.google.com");
    

    but the result is always "false".

    In my testenvironment I want to connect to a web API with the url http://localhost:54503/ which is available in the webbrowser but your plugin always returns false.

    None of these calls return true:

    var reachable1=await CrossConnectivity.Current.IsReachable("http://localhost:54503");
    var reachable1=await CrossConnectivity.Current.IsReachable("http://10.0.2.2:54503");
    

    Your plugin would be a perfect solution for my pcl that's why I hope you could give me a clue.
    Thank you!

  • JamesMontemagnoJamesMontemagno James Montemagno USXamarin Team, Developer Group Leader Xamurai
    edited February 2016

    You can't add the / at the end, which is why it if failing.

    However, if you are on a simulator it usually can't reach out to a local host unless you have loop back on.

    You should try simply "google.com"

  • **See mine: ** I have downloaded Xam.Plugin.Connectivity to packages.

    MainActivity.cs :

    Add Connectivity NameSpace : using Plugin.Connectivity;

    namespace SampleTest
    {
    [Activity (Label = "Alpha Numeric Call App", MainLauncher = true, Icon = "@mipmap/icon")]

    public class MainActivity : Activity
    {
        protected override void OnCreate (Bundle savedInstanceState)
        {
            Xamarin.Insights.Initialize (XamarinInsights.ApiKey, this);
            base.OnCreate (savedInstanceState);
            // Set our view from the "main" layout resource
    
            SetContentView (Resource.Layout.Main);
    
            if (CrossConnectivity.Current.IsConnected) {
                Toast.MakeText (this, "Connection Available", ToastLength.Short).Show ();               
            } else {
                Toast.MakeText (this, "Connection Not Available", ToastLength.Short).Show ();
                Console.WriteLine ("check network settings"); 
            }
        }
    }
    

    }

«1
Sign In or Register to comment.