Solved

Windows Service in C#

Posted on 2010-08-13
6
520 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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

IP addresses can be stored in a database in any of several ways.  These ways may vary based on the volume of the data.  I was dealing with quite a large amount of data for user authentication purpose, and needed a way to minimize the storage.   …
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

706 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now