Solved

Windows Service in C#

Posted on 2010-08-13
6
550 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Docker-Compose to Simplify Multi-Container Builds

Our veteran DevOps Author takes you through how to build a multi-container environment, managed with a single utility in order to simplify your deployments.

 

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

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…

626 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