Quantcast
Channel: The Microsoft MVP Award Program Blog
Viewing all articles
Browse latest Browse all 788

Detecting Network Connection in Windows Store Apps

$
0
0

Editor’s note: The following post was written by ASP.NET MVP Lohith Nagaraj

 

Detecting Network Connection in Windows Store Apps

 

Overview:

 

If you developing a Windows Store Apps, it’s a possible likelihood that you rely on some sort of service to either get data or store data. This means that you will probably at the mercy of the Internet connectivity on the device. As a best practice you are supposed to make sure the device is connected to Internet and if not gracefully handle the situation. In this blog post we will take a look at how to achieve this

Accessing Network Information:

Windows API for Windows Store Apps provide NetworkInformation class under Windows.Networking.Connectivitynamespace.  NetworkInformationclass, is a sealed class and provides access to network connection information on the local machine. As any other class, this provides the following methods for use:

·         GetConnectionProfiles– List of profiles for connections (active or otherwise) on the local machine

·         GetHostNames– List of host names associated with local machine

·         GetInternetConnectionProfile– Connection profile associated with the internet connection currently used on machine

·         GetLanIndentifiers– Array of LAN identifiers

·         GetProxyConfigurationAsync– Proxy configuration for connection

·         GetSortedEndPointPairs– Sorted list of EndpointPair objects

So detecting whether we have Internet connection or not is a 2 step process. They are:

1.      Use NetworkInformation.GetInternetConnectionProfile to retrieve the connection profile

2.      Use the ConnectionProfile to retrieve the network connectivity level i.e. Internet Access or Local Access or Constrained Internet Access

We will go through above steps one by one

1.      Getting Internet Connection Profile:

First step in detecting internet connectivity is to get the connection profile. We will use the   NetworkInformationclass, GetInternetConnectionProfile method to get the profile. The signature of the method is shown below:

 


public static ConnectionProfile GetInternetConnectionProfile()

 

This method will get the connection profile associated with the Internet connection currently used by the local machine. When invoked, this method will return an instance of ConnectionProfile. It doesn’t take any parameter. Here is the code to use this method:


ConnectionProfile InternetConnectionProfile =

                    NetworkInformation.GetInternetConnectionProfile(); 

2.     Network Connectivity Level from Connection Profile

In this step we look at what is ConnectionProfile and how does it provide network connectivity level. ConnectionProfile class represents a single network connection established on a device. This class will help us to determine the current connectivity level, track data usage or identify network adapter used to maintain connection. This is also a sealed class and contains many methods to help us with the current connection. We are interested in a particular method named GetNetworkConnectivityLevel. It does not take any input and returns a enum of type NetworkConnectivityLevel. Here is the method signature of GetNetworkConnectivityLevel:



public NetworkConnectivityLevel GetNetworkConnectivityLevel()

 

NetworkConnectivityLevel is a enum which provides information on the level of connectivity we have i.e. No connection, local access, internet access or constrained internet access. Here is the code snippet of this enum decompiled from the metadata:

 

 


public enum NetworkConnectivityLevel

    {

        // Summary:

        //     No connectivity.

        None = 0,

       //

        // Summary:

        //     Local network access only.

        LocalAccess = 1,

       //

        // Summary:

        //     Limited internet access. This value indicates captive portal

connectivity,

        //     where local access to a web portal is provided, but access to

the Internet

        //     requires that specific credentials are provided via the portal.

This level

        //     of connectivity is generally encountered when using connections

hosted in

        //     public locations (e.g. coffee shops and book stores).

        ConstrainedInternetAccess = 2,

       //

        // Summary:

        //     Local and Internet access.

        InternetAccess = 3,

  }

 

 As you can see, this enum will let us know if we have internet connection or not.

 

As a practice, I have created a small Boolean function and named it as “ConnectedToInternet” – this will return a Boolean i.e. true if connected to internet else false. And then I call it every time I need to make an outbound call. Here is the code snippet for this scenario:

 

 

private bool ConnectedToInternet()

{

           ConnectionProfile InternetConnectionProfile =

                    NetworkInformation.GetInternetConnectionProfile();

 

            if (InternetConnectionProfile == null)

            {

                return false;

            }

 

           var level =

InternetConnectionProfile.GetNetworkConnectivityLevel();

 

            return level == NetworkConnectivityLevel.InternetAccess;

}



private async void GetData(object sender, RoutedEventArgs e)

{

            if (!ConnectedToInternet())

            {

                await new MessageDialog("Not connected to Internet, check your   

connection",

                    "Currency Converter").ShowAsync();

                return;

            }

           //Your logic goes here

}

      Summary:

Through this post, I just wanted to touch upon the fact that network detection is a best practice and improves the user experience in your app. In order to detect if the internet connectivity is available or not we saw how we can make use of the windows networking connectivity namespace and with just 2 steps perform the necessary check. Hope this post was useful and will help you out in your endeavors with store apps. Till next time, happy coding.

 

About the author

me_new

Lohith has a decade of industry experience primarily in service based companies. He is well versed with Windows and Web based application development using .NET platform. Currently Lohith works in the capacity of Developer Evangelist for Telerik and takes care of evangelism in South India. He is also an active member and one of the leads for Bangalore DotNet User Group. He is an active speaker in local communities. He enjoys listening to Bryan Adams and watching Friends any time. Follow him on Twitter

About MVP Mondays

The MVP Monday Series is created by Melissa Travers. In this series we work to provide readers with a guest post from an MVP every Monday. Melissa is a Community Program Manager, formerly known as MVP Lead, for Messaging and Collaboration (Exchange, Lync, Office 365 and SharePoint) and Microsoft Dynamics in the US. She began her career at Microsoft as an Exchange Support Engineer and has been working with the technical community in some capacity for almost a decade. In her spare time she enjoys going to the gym, shopping for handbags, watching period and fantasy dramas, and spending time with her children and miniature Dachshund. Melissa lives in North Carolina and works out of the Microsoft Charlotte office.


Viewing all articles
Browse latest Browse all 788

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>