Solved

Windows Service in C#

Posted on 2010-08-13
6
533 Views
Last Modified: 2013-11-07
Hi,

I have a windows service. Now when ever the network connection is available or network connection changed status is broadcasted in the system.  My service has to pick up this command and must be started from paused state. I am planning to use the oncustomcommand function to achieve this. Please, do let me know if any one has answer. Also, I am new to developing application using windows service. Let me whether this can be achieved.
0
Comment
Question by:rakshihegde
6 Comments
 
LVL 8

Expert Comment

by:Yiogi
ID: 33434023
To be honest I don't know how the network connection status change will be broadcast.

I'd suggest to always have the service running and have the service itself check network status. You can use Thread.Sleep(1000) to sleep for a second and check every second for example. CPU usage will be minimal if that's what you are concerned with because essentially you will be doing a simple check every second that shouldn't take over a millisecond and then go to idle mode for a second.

Sorry that I can't help more. If you have any feedback on how the network connection status change is broadcast then I can read that any maybe help you some more.

Windows services are pretty simple to develop, it's not harder than developing any windows application.
0
 
LVL 4

Expert Comment

by:avarmaavarma
ID: 33434059
There's a built-in event in the .NET framework called NetworkAvailabilityChanged. You can use this event to check if you lost connectivity (using e.IsAvailable - where e is the eventargs). See the example below. The example is a stand alone console app - the same code can just go into the OnStart event of a regular windows service class.




 using System;
    using System.Net.NetworkInformation;

    class MainClass
    {

        private static void NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
        {
            if (e.IsAvailable)
            {
                Console.WriteLine("Network Available");
            }
            else
            {
                Console.WriteLine("Network Unavailable");
            }
        }

        static void Main(string[] args)
        {
            NetworkChange.NetworkAvailabilityChanged += NetworkAvailabilityChanged;
        }
    }

Open in new window

0
 
LVL 4

Expert Comment

by:avarmaavarma
ID: 33434101
Attached is the complete code for a windows service using the event described above.
using System; 
using System.Collections;
using System.Net.NetworkInformation;
using System.ComponentModel; 
using System.Configuration; 
using System.Data; 
using System.Web.Services; 
using System.Diagnostics; 
using System.ServiceProcess; 

namespace WindowsService1
{
 
    public class NetworkAvailabilityService : System.ServiceProcess.ServiceBase 
    { 
    /// <summary> 
    /// Required designer variable. 
    /// </summary> 
    private System.ComponentModel.Container components;
    public NetworkAvailabilityService() 
    { 
    // This call is required by the WinForms Component Designer. InitializeComponent(); 
    // TODO: Add any initialization after the InitComponent call 
    } 
    // The main entry point for the process 
    static void Main() 
    { 
    System.ServiceProcess.ServiceBase[] ServicesToRun; 
    // More than one user Service may run within the same process. To add 
    // another service to this process, change the following line to 
    // create a second service object. For example, 
    // 
    // ServicesToRun = New System.ServiceProcess.ServiceBase[] {new WinService1(), new ySecondUserService()}; 
    // 
    ServicesToRun = new System.ServiceProcess.ServiceBase[] { new NetworkAvailabilityService() }; 
    System.ServiceProcess.ServiceBase.Run(ServicesToRun); 
    } 
    /// <summary> 
    /// Required method for Designer support - do not modify 
    /// the contents of this method with the code editor. 
    /// </summary> 
    private void InitializeComponent() 
    { 
    components = new System.ComponentModel.Container(); 
    this.ServiceName = "WinService1"; 
    } 
    /// <summary> 
    /// Set things in motion so your service can do its work. 
    /// </summary> 
    protected override void OnStart(string[] args) 
    { 
        // TODO: Add code here to start your service. 
        NetworkChange.NetworkAvailabilityChanged += NetworkAvailabilityChanged;
    }

    private static void NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
    {
        if (e.IsAvailable)
        {
            Console.WriteLine("Network Available");
        }
        else
        {
            Console.WriteLine("Network Unavailable");
        }
    }

    /// <summary> 
    /// Stop this service. 
    /// </summary> 
    protected override void OnStop() 
    { 
        // TODO: Add code here to perform any tear-down necessary to stop your service. 
    } 
    } 
}

Open in new window

0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

Author Comment

by:rakshihegde
ID: 33454228
Thanks for the Reply. I have one more question. I implemented this method but it triggeres only ones. But, it has to trigger continously. There fore, I implemented a timer where every 10 seconds it monitors the availability of the network and singanls the service to do some operation.

Please, do let me know whether this would be the best way to achieve it.
0
 
LVL 15

Expert Comment

by:angus_young_acdc
ID: 33454443
Yes a timer can do that, just have the timer elapsed event trigger your poll of the network.  

Also, just to make things more configurable add an application config file, and then you can edit the time without having to recompile your code :)
0
 
LVL 4

Accepted Solution

by:
avarmaavarma earned 500 total points
ID: 33457992
Yes - using a timer is a good idea. Here is the code that allows you to do that
// Put this declaration at the class level - i.e. just below
private System.Timers.Timer MonitorTimer;


// This can go in the OnStart
 MonitorTimer = new System.Timers.Timer(15000);
                MonitorTimer.Enabled = true;

// Here is the modified NetworkAvailability Changed handler

void NetworkAvailabilityChanged(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e)
        {
            if (e.IsAvailable)
            {
                if (!MonitorTimer.Enabled)
                {
                    MonitorTimer.Start();
                }
            }
            else
            {
                MonitorTimer.Stop();
            }
        }

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

775 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question