Windows服务。 搜索系统错误并将其显示在WinForm C#中

在本文中,我们将研究如何从头开始创建将与Windows服务一起使用的应用程序,并在WinForm(C#)中显示系统错误。

本文概述:

  • 服务创建
  • 事件查看器
  • 服务编号
  • 检查服务(手动启动服务)
  • WinForm映射

服务创建


打开Visual Studio。 下一步文件→新建→项目→(Windows桌面)→Windows服务(.Net Framework)→确定。

接下来,您需要创建一个安装程序。 在打开的窗口中,单击人民币,然后选择“添加安装程序”。 您将创建“ ProjectInstaller.cs [Design]”,然后需要转到“ F7”代码或人民币“ View Code”。 您需要找到“ InitializeComponent();”行,将光标放在其上并按“ F12”,然后需要添加以下行:

this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem; //       this.serviceInstaller1.Description = "Show me system error."; //       this.serviceInstaller1.DisplayName = "GetSystemError"; //        

但是您只需要按以下顺序和位置添加这些行。 否则,安装服务时将出现错误。



事件查看器


这是验证我们程序正确运行所必需的。

Event Viewer-用于查看每台装有Windows的计算机上的事件日志的程序。 在计算机上运行的每个程序在停止之前都会在事件日志中发布通知。 对系统的任何访问,安全性更改,操作系统的调整,硬件故障和驱动程序故障-所有这些均进入事件日志。 Event Viewer扫描文本日志文件,将它们组合并放置在界面中。

怎么打开呢? -开始→事件查看器(搜索中)→“查看事件日志”。

接下来,“自定义视图”→“管理事件”。 在这里,我们可以看到所有错误,警告和有关它们的信息。

日志共有3种类型:应用程序(应用程序),系统(系统)和安全性(安全性)。 我们只需要一个系统(System)。

服务编号


我们找到带有服务名称的.cs文件,我将其命名为“ Service1.cs”,将其打开。 该文件必须具有2个覆盖的方法:

  • OnStart(字符串[] args)-服务启动时执行,
  • OnStop()-服务停止时执行。

还有其他几种方法,但是我们现在不需要它们了。 您可以自己找到它们。

我们获得的数据将存储在更新的文本文件中,因此我们添加了

 using System.IO; 

将代码添加到OnStart方法(字符串[] args):

 EventLog myLog; //       string filepath = AppDomain.CurrentDomain.BaseDirectory + @"\ServiceLog.txt";; //    List<string> list; //    protected override void OnStart(string[] args) { myLog = new EventLog(); myLog.Log = "System"; //     - (Application),    (System). myLog.Source = "System Error"; for (int index = myLog.Entries.Count - 1; index > 0; index--) //         { var errEntry = myLog.Entries[index]; \\     if (errEntry.EntryType == EventLogEntryType.Error) \\    { //     var appName = errEntry.Source; list = new List<string>(); list.Add("Entry Type: " + Convert.ToString(errEntry.EntryType)); list.Add("Event log: " + (string)myLog.Log); list.Add("Machine Name: " + (string)errEntry.MachineName); list.Add("App Name: " + (string)errEntry.Source); list.Add("Message: " + (string)errEntry.Message); list.Add("Time Written: " + errEntry.TimeWritten.ToString()); list.Add("-*-"); WriteToFile(list); //    } } } public void WriteToFile(List<string> list) //   { using (StreamWriter sw = File.AppendText(filepath)) { for (int i = 0; i < list.Count; i++) sw.WriteLine(list[i]); } } 

接下来,您需要收集解决方案“解决方案”->“重建解决方案”。 成功组装后,可以检查操作。

检查服务(手动启动服务)


Windows服务无法作为常规应用程序启动。 您只能以管理员身份通过命令行运行。

以管理员身份运行命令行。 输入以下命令:

 cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 InstallUtil.exe \  .exe (InstallUtil.exe C:\Users\\source\repos\WindowsService1\WindowsService1 \bin\Debug\WindowsService1.exe)    : InstallUtil.exe -u \  .exe 

接下来,按Win + R键。 输入“ Services.msc”。 我们在列表中找到我们的服务,单击它,然后单击“开始”。 成功启动后,将在系统错误列表所在的代码中指定的路径处生成文件。
验证后不要忘记删除服务。

WinForm映射


要在控制台中显示,如果您尝试的话,可以找到文章,但是我没有找到要在WinForm中显示的文章,所以这里是。 默认情况下,将创建应用程序类型的服务项目。 要通过控制台显示,必须在设置中更改此参数,WinForm才能保持原样。 接下来,您需要将表单添加到项目中。 “ WindowsService1”→RMB→添加→Windows Form→添加。 并进行以下设计。 接下来,更改文件“ Program.cs”。

使用添加:

 using System.Windows.Forms; using System.Security.Principal; using System.ComponentModel; using System.Diagnostics; 

并更改Main方法:

 static void Main(string[] args) { WindowsPrincipal windowsPricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool hasAdministrativeRight = windowsPricipal.IsInRole(WindowsBuiltInRole.Administrator); if (hasAdministrativeRight == false) //    { ProcessStartInfo processInfo = new ProcessStartInfo(); //   processInfo.Verb = "runas"; //       processInfo.FileName = Application.ExecutablePath; try { Process.Start(processInfo); //   } catch (Win32Exception){} Application.Exit(); } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1(args)); //  } } 

添加一个新类“ SystemError”。 (“ WindowsService1”-> RMB-> Add-> Class-> Add)。 在这里,我们将存储错误数据。 更改它:

 public string EntryType{ get; set; } public string EventLog{ get; set; } public string MachineName { get; set; } public string AppName { get; set; } public string Message { get; set; } public string TimeWritten { get; set; } 

进一步在“ Service1.cs”中,我们添加了启动服务的方法“ RunFromForm(string [] args)”。

 public void RunFromForm(string[] args) { OnStart(args); OnStop(); } 

添加一个新类“ GetListErrors”。 (“ WindowsService1”-> RMB-> Add-> Class-> Add)。 在这里,我们将从文件中获取数据。 使用添加:

 using System.IO; 

更改它:

 string filepath = AppDomain.CurrentDomain.BaseDirectory + @"\ServiceLog.txt"; SystemError systemError; public List<SystemError> listSysErrs; public void ReadFile() //          { systemError = new SystemError(); listSysErrs = new List<SystemError>(); using (StreamReader sr = new StreamReader(filepath)) { string line; while ((line = sr.ReadLine()) != null) { if (line.Contains("-*-")) { listSysErrs.Add(systemError); systemError = new SystemError(); //       } if (line.Contains("Entry Type")) { systemError.EntryType = line.Substring(12); } else if (line.Contains("Event log")) { systemError.EventLog = line.Substring(11); } else if (line.Contains("Machine Name")) { systemError.MachineName = line.Substring(14); } else if (line.Contains("App Name")) { systemError.AppName = line.Substring(10); } else if (line.Contains("Message")) { systemError.Message = line.Substring(9); } else if (line.Contains("Time Written")) { systemError.TimeWritten = line.Substring(14); } } } } 

接下来,更改形式为“ Form1.cs”的代码。 使用添加:

 using System.ServiceProcess; using System.Diagnostics; 

更改它:

 Service1 service = new Service1(); List<SystemError> listSysErrs; string[] args; public Form1(string[] args) { InitializeComponent(); this.args = args; if (Environment.UserInteractive)//          { service.RunFromForm(args); //  GetListErrors getListErrors = new GetListErrors(); getListErrors.ReadFile(); //      listSysErrs = getListErrors.listSysErrs; FillDataGridView(); //    } else { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { service }; ServiceBase.Run(ServicesToRun); } } public void FillDataGridView() //     { foreach (SystemError item in listSysErrs) { dataGridView1.Rows.Add(item.AppName, item.Message); } } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) //                { SystemError sys = listSysErrs[dataGridView1.CurrentRow.Index]; label1.Text = "Entry Type: " + sys.EntryType + "\nEvent log: " + sys.EventLog + "\nMachine Name: " + sys.MachineName + "\nApp Name: " + sys.AppName + "\n\nMessage: " + FormatMessage(sys.Message) + "\n\nTime Written: " + sys.TimeWritten; } private string FormatMessage(string msg) //       ,                 { string retMsg = ""; int count = 75; if (msg.Length > count - 9) { retMsg += msg.Substring(0, count - 9) + "\n"; msg = msg.Substring(count - 9); } while (msg.Length > count) { retMsg += msg.Substring(0, count) + "\n"; msg = msg.Substring(count); } retMsg += msg + "\n"; return retMsg; } private void button1_Click(object sender, EventArgs e) //          { if (Environment.UserInteractive) { while (dataGridView1.Rows.Count != 0) { dataGridView1.Rows.Remove(dataGridView1.Rows[dataGridView1.Rows.Count - 1]); } service.RunFromForm(args); GetListErrors getListErrors = new GetListErrors(); getListErrors.ReedFile(); listSysErrs = getListErrors.listSysErrs; FillDataGridView(); } else { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { service }; ServiceBase.Run(ServicesToRun); } } private void button2_Click(object sender, EventArgs e) { Process.Start(AppDomain.CurrentDomain.BaseDirectory); //  } 

现在,您可以将服务作为常规应用程序启动。 结果如下:

Source: https://habr.com/ru/post/zh-CN452688/


All Articles