Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Windows Service in C#

Posted on 2010-08-13
6
Medium Priority
?
552 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
Not sure which OpenStack Certification to get?

So you’ve realized you might want to get certified in OpenStack, but you’re not sure what the benefits might be or even which one you should take. You know there are several certification courses you can choose from, but how do you know which one is right for you?

 

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 2000 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
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…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

670 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