这项服务有什么问题吗? [英] Is there anything wrong with this service?

查看:75
本文介绍了这项服务有什么问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

安装后每当我运行Windows服务时,程序都会响应并显示一条错误消息.它会说它什么也不能运行.代码如下:



Whenever I run a windows service after installation, the program will respond with a error message. It will says it has nothing to run. The code is below :



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Runtime.InteropServices;
using System.Configuration.Install;
using System.ComponentModel;
using System.Management;
using System.IO;
using System.Text.RegularExpressions;

namespace NetworkCardConfigService
{
    public partial class NetworkCardConfigService : ServiceBase
    {
        public NetworkCardConfigService()
        {
            InitializeComponent();

        }




        protected override void OnStart(string[] args)
        {

            base.OnStart(args);


            //TODO: place your start code here

            // Open file MAC.TXT
            // read from file or write to file
            System.IO.FileStream myStream = new FileStream("C:\\MAC.txt", FileMode.Open);

            System.IO.StreamReader myStreamReader = new StreamReader(myStream);

            string fileContent = myStreamReader.ReadToEnd();

            myStreamReader.Close();

            string[] Lines = fileContent.Split(''\n'');

            String[] Field;

            ParamHost[] PH;


            PH = new ParamHost[Lines.Length]; // to do 

            int PH_Number = 0;


            foreach (string Line in Lines)
            {

                if (Line != "" && Line != "\r")
                {
                    Console.WriteLine("line :" + Line);

                    Field = Line.Split('';'');

                    Console.WriteLine("MAC {0}; hostname{1}; IP: {2}", Field[0], Field[1], Field[2]);

                    PH[PH_Number].MAC = Field[0];
                    PH[PH_Number].hostname = Field[1];
                    PH[PH_Number].IP = Field[2];

                    /*
                                        for (int i = 0; i < Field.Length; i++)
                                        {
                                        Console.WriteLine(Field[i]);
                                        }*/
                    PH_Number++;


                    //foreach (String i in Field)
                    //{

                    //  Console.WriteLine(Field[i]);


                    //}
                    //PH_Number++;







                }

                // Console.WriteLine("{0}", fileContent);

                myStreamReader.Close();

                //Console.WriteLine(PH[0].MAC);

                ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");


                ManagementObjectCollection objMOC = objMC.GetInstances();


                string gw;
                string myIpString;
                char[] delim;
                string[] myIpArray;
                string myGateWayString;



                foreach (ManagementObject objMO in objMOC)
                {

                    if (!(bool)objMO["ipEnabled"])
                        continue;
                    //Console.WriteLine(objMO["Caption"] + "," + objMO["ServiceName"] + "," + objMO["MACAddress"]);

                    string MAC_card = objMO["MACAddress"].ToString();

                    for (int index = 0; index < PH_Number; index++)
                    {
                        string MAC_File = PH[index].MAC.ToString();

                        //Console.WriteLine("jkjkjk :" + MAC_card + MAC_File);

                        if (MAC_card.Equals(MAC_File))
                        {
                            Console.WriteLine("good card to configure ! ! " + MAC_File);
                            Console.WriteLine("hostname " + PH[index].hostname);
                            Console.WriteLine("IP " + PH[index].IP);
                            // Set nic parameters
                            // to do

                            //string gw = PH[index].IP;


                            gw = PH[index].IP;

                            //PH[index].IP = x.y.z.w -> gw= x.y.z.1

                            // to do   gw = .1



                            //assuming myLocalIP is the IPAddress object you are using from the IPAddress array you will have been playing with before...
                            myIpString = gw.ToString(); //to return nice "255.255.255.255" notation to work with
                            delim = new char[1]; //set the delimiter you want to split your IP string by - so ''.''
                            delim[0] = ''.''; //set the delimiter you want to split your IP string by - so ''.''
                            myIpArray = myIpString.Split(delim); //actually split the IP up
                            myIpArray[3] = "1";
                            myGateWayString = myIpArray[0] + "." + myIpArray[1] + "." + myIpArray[2] + "." + myIpArray[3]; //to reconstruct your gateway string
                            //IPAddress myGatewayObject = IPAddress.Parse(myGateWayString); //To construct your gateway IPAddress object to work with!



                            //setParmIP(PH[index].hostname, PH[index].IP, "255.255.255.0", gw, "147.215.1.4", "147.215.1.20", "147.215.1.136");




                            setParmIP(PH[index].hostname, PH[index].IP, "255.255.255.0", gw, "147.215.1.4", "147.215.1.20", "147.215.1.136");




                            Console.ReadKey();
                        }
                    }
                }
            }


        }

        protected override void OnStop()
        {



            {
                base.OnStop();




                //TODO: clean up any variables and stop any threads
            }
        }

        // Configue NIC

        public static void setParmIP(string ComputerName, string IPAddress, string SubnetMask, string Gateway, string DNS_primary, string DNS_secondary, string WINS_Server)
        {

            ManagementClass objMC = new ManagementClass(
                "Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection objMOC = objMC.GetInstances();

            foreach (ManagementObject objMO in objMOC)
            {

                if (!(bool)objMO["IPEnabled"])
                    continue;



                try
                {
                    ManagementBaseObject objNewIP = null;
                    ManagementBaseObject objSetIP = null;
                    ManagementBaseObject objNewGate = null;
                    ManagementBaseObject objNewDNS = null;
                    ManagementBaseObject objNewWINS = null;


                    objNewIP = objMO.GetMethodParameters("EnableStatic");
                    objNewGate = objMO.GetMethodParameters("SetGateways");




                    //Set DefaultGateway
                    objNewGate["DefaultIPGateway"] = new string[] { Gateway };
                    objNewGate["GatewayCostMetric"] = new int[] { 1 };


                    //Set IPAddress and Subnet Mask
                    objNewIP["IPAddress"] = new string[] { IPAddress };

                    objNewIP["SubnetMask"] = new string[] { SubnetMask };

                    objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
                    objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);
                    //Set DNS server
                    objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
                    objNewDNS["DNSServerSearchOrder"] = new string[] { DNS_primary, DNS_secondary };
                    objSetIP = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDNS, null);

                    //Set WINS server
                    objNewWINS = objMO.GetMethodParameters("SetWINSServer");
                    //objNewWINS["WINSPrimaryServer"] = new string[] {WINS_Server}; // not working
                    objNewWINS.SetPropertyValue("WINSPrimaryServer", WINS_Server);
                    objNewWINS.SetPropertyValue("WINSSecondaryServer", "");

                    objSetIP = objMO.InvokeMethod("SetWINSServer", objNewWINS, null);

                    // Set hostname to do
                    string compName = System.Windows.Forms.SystemInformation.ComputerName.ToString();
                    WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_ComputerSystem");
                    ManagementObjectSearcher search = new ManagementObjectSearcher(query);
                    object[] name = { ComputerName };
                    foreach (ManagementObject mo in search.Get())
                    {
                        mo.InvokeMethod("Rename", name);
                    }


                    Console.WriteLine(
                                    "Updated IPAddress, SubnetMask , Default Gateway ,DNS, Wins and Hostname !");


                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to Set IP : " + ex.Message);

                    //read the ASCII value of the char typed and cast it to a char value
                    //   char ch = (char)Console.Read();

                    // read the ASCII value of the char typed

                    //           int asciiCode = Console.Read();

                    // read the input data until a return or new line is read
                    // this allows the user to type away until they press enter/return
                    // this method will return you information one line at a time... hence the name! :)

                }

            }
        }





        public struct ParamHost
        {
            public string MAC, hostname, IP;

            public ParamHost(string MAC, string hostname, string IP)
            {
                this.MAC = MAC;
                this.hostname = hostname;
                this.IP = IP;
            }
        }

        [RunInstaller(true)]
        public class MyWindowsServiceInstaller : Installer
        {
            public MyWindowsServiceInstaller()
            {
                var processInstaller = new ServiceProcessInstaller();
                var serviceInstaller = new ServiceInstaller();

                //set the privileges
                processInstaller.Account = ServiceAccount.LocalSystem;

                serviceInstaller.DisplayName = "NetworkCardConfigService";
                serviceInstaller.StartType = ServiceStartMode.Automatic;

                //must be the same as what was set in Program''s constructor
                serviceInstaller.ServiceName = "NetworkCardConfigService";

                this.Installers.Add(processInstaller);
                this.Installers.Add(serviceInstaller);
            }
        }
    }
}

推荐答案

所有工作都是在OnStart中执行和完成的,因此不需要将其作为服务.对于服务OnStart,应该启动一个执行定期工作的后台线程,但是此处的操作看起来像是一次完成的事情.如果OnStart实际上没有启动任何内容,则服务管理器将产生您所看到的消息.

此外,服务与用户之间没有交互,因此Console.ReadKeyConsole.WriteLine不会很有帮助.

[评论回应]
OnStart不应该做任何工作,它要做的就是启动一个后台线程.线程的目的是运行并继续工作,直到调用OnStop方法为止.调用OnStop时,线程应退出,以便服务可以关闭.
[/评论回应]

[回应2]
Windows服务不是Windows启动时运行的程序.服务是需要从Windows启动,在后台运行并在Windows关闭时关闭的应用程序.

如果您只需要Windows启动时运行一次的应用程序,则不需要服务.您只需要一个从适当位置链接到的普通应用程序(控制台或GUI,没关系).

有几种方法可以使您的应用在启动时运行,我知道的两种最典型的方法是编辑 ^ ]或在用户启动"文件夹中为您的应用添加快捷方式.

如果您的应用程序需要半周期运行(例如每6或12个小时运行一次),则Windows有一个任务计划程序,可以在需要时启动该应用程序.
[/RESPONSE 2]
All of the work is performed and completed in OnStart so there''s no need for this to be a service. For a service OnStart should kick off a background thread that does periodic work but the actions here look like a once and done thing. If OnStart doesn''t actually start anything then the service manager will produce the message you''re seeing.

Also, services have no interaction with the user so Console.ReadKey and Console.WriteLine won''t be very helpful.

[COMMENT RESPONSE]
OnStart should not do any work, all it should do is start a background thread. The purpose of the thread is to run and keep doing work until the OnStop method is called. When OnStop is called the thread should exit so the service can close.
[/COMMENT RESPONSE]

[RESPONSE 2]
Windows Services aren''t programs that run when Windows starts. Services are applications that need to start with windows, run in the background and close when Windows shuts down.

If all you need is an app that runs once when Windows starts, then you don''t need a Service. All you need is a normal application (Console or GUI, it doesn''t matter) that is linked to from the proper place.

There are several ways to make your app run on startup, the two most typical that I know of are to edit the registry[^] or to put a shortcut to your app in the users "Startup" folder.

If your app needs to run semi-periodically, say every 6 or 12 hours, then Windows has a Task Scheduler that can launch an app when it needs it.
[/RESPONSE 2]


获取新答案的时间.您现在有一个完全不同的问题,该问题将导致需要发布新帖子,注释系统当然不是为代码转储而构建的.

无论如何,这是调试服务的一种快速而肮脏的方法:在Visual Studio .NET下调试Windows服务 [ ^ ]
这应该可以帮助您找到异常并插入适当的边界检查代码.
Time for a new answer. You now have an entirely different question which would have warranted a new post, the commenting system certainly wasn''t built for code dumps.

Regardless, here''s the quick and dirty way to debug a service: Debugging Windows Services under Visual Studio .NET[^]
That should help you find the exception and insert appropriate bounds checking code.


这篇关于这项服务有什么问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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