Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created a windows service for monitoring the data usage of the internet connection of a modem (adapter) that is connected to my computer.

How do I assign the path file and the adapter value dynamically in the below mentioned code snippet, or atleast during the msi installation of the windows service.
Kindly help me out.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

using System.IO;
using System.Threading;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using Microsoft.Win32;

namespace SampleService
{
    public partial class SampleWinService : ServiceBase
    {

        #region Variable and Constants

        private Timer service_timer;
        NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
        NetworkInterface adapter;
        long start_received_bytes;
        long start_sent_bytes;
        long end_received_bytes;
        long end_sent_bytes;

        string start_time, end_time;
        private DateTime _startTime = DateTime.MinValue;

        private bool _isNetworkOnline;
        bool flag_c;

        string empty_line = "===============================================================";
        string path_file = @"C:\\Documents and Settings\\users\\Desktop\\Test Services.txt";

        #endregion

        // How do I input the file path, as it differs from system to system

        public SampleWinService()
        {
            InitializeComponent();                 
        }

        protected void timerTicker(object sender)
        {
            if (IsConnectedToInternet() == true && flag_c == false)
            {
                mark_values("initial");
                flag_c = true;
            }
            else if (IsConnectedToInternet() == true && flag_c == true)
            {
                mark_values("final");
            }
            else if (IsConnectedToInternet() == false && flag_c == true)
            {
                writetoFile();
                flag_c = false;
            }
        }

        protected void mark_values(string todo)
        {
            if (todo == "initial")
            {
                _startTime = DateTime.Now;
                start_received_bytes = adapter.GetIPv4Statistics().BytesReceived;
                start_sent_bytes = adapter.GetIPv4Statistics().BytesSent;
            }
            else
            {
                end_received_bytes = adapter.GetIPv4Statistics().BytesReceived;
                end_sent_bytes = adapter.GetIPv4Statistics().BytesSent;
            }
        }

        protected long cal_bytes(long value)
        {
            long temp_val;
            temp_val = (value / 1048576 * 100000) / 100000;
            return temp_val;
        }

        protected void writetoFile()
        {
            var timeSinceStartTime = DateTime.Now - _startTime;
            timeSinceStartTime = new TimeSpan(timeSinceStartTime.Hours,
                                              timeSinceStartTime.Minutes,
                                              timeSinceStartTime.Seconds);

            if (System.IO.File.Exists(path_file))
            {
                System.IO.File.AppendAllText(path_file, 
                    empty_line + Environment.NewLine + 
                    "Connection established: " + start_time + " Ended: " + end_time + Environment.NewLine +
                    "Total Time: " + timeSinceStartTime + Environment.NewLine +
                    "Received Start: " + start_received_bytes.ToString() + " (in MB): " + cal_bytes(start_received_bytes).ToString() + Environment.NewLine +
                    "Sent Start: " + start_sent_bytes.ToString() + " (in MB): " + cal_bytes(start_sent_bytes).ToString() + Environment.NewLine + 
                    "Received End: " + end_received_bytes.ToString() + " (in MB): " + cal_bytes(end_received_bytes).ToString() + Environment.NewLine + 
                    "Sent End: " + end_sent_bytes.ToString() + " (in MB): " + cal_bytes(end_sent_bytes).ToString() + Environment.NewLine);
            }
        }

        #region Internet Connection Status

        [System.Runtime.InteropServices.DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
        public static bool IsConnectedToInternet()
        {
            int Desc;
            return InternetGetConnectedState(out Desc, 0);
        }

        protected void NetworkChange_NetworkAvailabilityChanged(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e)
        {
            _isNetworkOnline = e.IsAvailable;
        }

        #endregion

        protected override void OnStart(string[] args)
        {
            try
            {
                // how do I assign the adpter dynamicaly or atleast during the installation of the services
                    adapter = fNetworkInterfaces[0];
                
                service_timer = new Timer(new TimerCallback(timerTicker));
                service_timer.Change(29999, 30000);                  
            }
            catch (Exception ex)
            {
                Console.WriteLine(" Start Error: {0}", ex.Message.ToString());
            }
        }

        protected override void OnStop()
        {
            
        }

    }
}
Posted
Updated 15-Oct-12 23:27pm
v3

1 solution

This is normally the type of thing you would read in from a .config file. As you have figured out, you cannot display a UI from your windows service, so you have two real options. The first option is to have a post installation step in your setup wizard, where the user enters this information and it's written into the config file. As we don't know what your installer is, you're going to have to look up the steps for setting this up in the installer you are using (it's normally fairly trivial to do).

The second method is to supply a Tray Notification option, with a context menu offering the user the chance to configure the service.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900