Internet Watcher in .NET 3.5


Introduction

This is a Windows service developed in C# targeting the .NET Framework 3.5 using VS 2010 (You need .NET Framework 3.5 installed in your system if you want to use this:)). This service will start when the computer starts and keep monitoring the internet connection at the regular interval (can be set in the config file, default is one second). I will add an entry to the Xml file each time internet connected and disconnected (not each time it checks for internet connection state).

Potential Users

I assume this service is useful for those who have internet connection with a time based plan (i.e. fixed price for fixed time per month and extra price exceeding the fixed time) rather than size based (fixed price for fixed download size). So they can know how much time they have on internet per month and expect or avoid extra amount from the bill.

Design of this service

This is a very simple service designed with few classes and one interface. Below is the class diagram.
ClassDiagram1.png

IStorage is a simple interface offering two methods:

 

void Connected(DateTime when);

void Disconnected(DateTime when);

 

The purpose of this interface is to enable the user to change the storage to database or any other storage mechanism rather than in an xml file as I used. 

 

The class "XmlStorage"

 

is implemented this interface and update connection details such as date, start time, end time and elapsed time into the xml file.

 

This class is then used in the "InternetWatcherService" class. If you want to store the data into the database then create a new class, implement the interface and use it in the "InternetWatcherService".

 

The class "InternetWatcherService"

 

This is the service class which keeps monitoring the internet connection. Internet connection is checked using the code below.


[DllImport("wininet.dll")]

private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);

/// <summary>

/// Returns whether Internet is connected

/// </summary>

/// <returns>bool</returns>

static bool InternetConnected

{

    get

    {

        int Description = 0;

        return InternetGetConnectedState(out Description, 0);

    }

}

 

On start event:

 

protected override void OnStart(string[] args)

{

    int interval = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalTimeInMS"]);

    timer = new Timer(Execute, null, 0, interval);

}

 

Execute method:

 

void Execute(object state)

{

    if (InternetConnected)

    {

        if (!ConnectionNotified)

        {

            try

            {

                store = new XmlStorage();

                store.Connected(DateTime.Now);

                WriteToEventLog("Internet connected", EventLogEntryType.Information);

            }

            catch (Exception ex) { WriteToEventLog(ex.Message, EventLogEntryType.Error); }

            ConnectionNotified = true;

            DisconnectionNotified = false;

        }

        return;

    }

    if (!DisconnectionNotified)

    {

        try

        {

            store = new XmlStorage();

            store.Disconnected(DateTime.Now);

            WriteToEventLog("Internet disconnected", EventLogEntryType.Information);

        }

        catch (Exception ex) { WriteToEventLog(ex.Message, EventLogEntryType.Error); }

        DisconnectionNotified = true;

        ConnectionNotified = false;

    }

}

 

WriteToEventLog method:

private static void WriteToEventLog(string message, EventLogEntryType eventLogEntryType)

{

    string sSource;

    string sLog;

    sSource = ServiceTitle;

    sLog = "Application";

    try

    {

        if (!EventLog.SourceExists(sSource))

            EventLog.CreateEventSource(sSource, sLog);

        EventLog.WriteEntry(sSource, message, eventLogEntryType);

    }

    catch { }

}

 

App.Config file:

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <appSettings>

    <!--

    Enter the time interval in milli seconds to check internet connection state

    Example: enter 2000 for 2 seconds

    -->

    <add key="IntervalTimeInMS" value="2000"/>

  </appSettings>

</configuration>


Setting up the Service:

You have two attachments.

1.    Download Service Setup

2.    Download Source C#.

Use the first attachment if you just want to make it work and happy with xml file as a storage system. Here are the steps to follow after extracting the zip.


1.    Open InternetConnectionWatcher.exe.config file and update the key IntervalTimeInMS to say how frequently to check for internet connection. 

2.    Install the windows service by using the installutil tool. Open the command prompt and the change the directory to the folder where the .NET Framework is installed. Typically the path will be "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727". Then issue the following command.

installutil -i "[extractedlocation]\InternetConnectionWatcher.exe"

Note: un installation is as simple as installation; just change the switch -i to -u
 You can see this is installed as a Windows service. You must start the service now but not again after that since it is installed to automatically starts when the computer starts.


InterWat1.gif

And you see the information updated in xml:

InterWat2.gif

Working with code:

If you want to store the data in other mediums such as database not the xml file, you can do so by creating your own class implementing the "IStorage" interface. Please see the "
Design of this service:" section above for more details.

Conclusion:

This is my first article and I hope this service may be useful for at least few people. I feel there should be a nice GUI application which displays the data in the screen and gives an alert to the user soon before the fixed time is reached. I will add it here if I have time and developed one in the near futureJ

Thank you so much staying thus far and I love to see the feedbacks.

Up Next
    Ebook Download
    View all
    Learn
    View all