Windows Service在onStart()期间进行输入 [英] Windows Service with input during onStart()

查看:86
本文介绍了Windows Service在onStart()期间进行输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Windows服务,用于监视连接到我的计算机的调制解调器(适配器)的Internet连接的数据使用情况.

如何在下面提到的代码片段中动态分配路径文件和适配器值,或者在Windows服务的msi安装期间至少分配动态文件和适配器值.
请帮帮我.

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.

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()
        {
            
        }

    }
}

推荐答案

这通常是您将从.config文件中读取的内容.如您所知,您无法从Windows服务中显示UI,因此有两个实际选项.第一种选择是在安装向导中进行安装后的步骤,用户在其中输入此信息并将其写入配置文件.由于我们不知道您的安装程序是什么,因此您将必须查找要在正在使用的安装程序中进行设置的步骤(通常很简单).

第二种方法是提供纸盘通知"选项,并通过上下文菜单为用户提供配置服务的机会.
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.


这篇关于Windows Service在onStart()期间进行输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆