c# - Windows 服务给出错误 - System.Security.SecurityException

标签 c# windows-services

感谢阅读我的帖子,我正在编写 Windows 服务,当我尝试启动它时,我在 EventViewer 上收到此错误:

Application: SerivicioBIOHAcademico.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Security.SecurityException
Stack:
   at System.Diagnostics.EventLog.FindSourceRegistration(System.String, System.String, Boolean, Boolean)
   at System.Diagnostics.EventLog.SourceExists(System.String, System.String, Boolean)
   at System.Diagnostics.EventLog.SourceExists(System.String)
   at SerivicioBIOHAcademico.BIOHAcad..ctor()
   at SerivicioBIOHAcademico.Program.Main()

这是我的服务应用程序 (C#) 中的一些代码

public partial class BIOHAcad : ServiceBase
    {
        Timer timer1 = new Timer();
        private readonly string WDcon = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.DBGriauleConnectionString"].ConnectionString;
        private readonly string UJGH = ConfigurationManager.ConnectionStrings["HorariosConnection"].ConnectionString;

        public BIOHAcad()
        {
            InitializeComponent();
            if (!System.Diagnostics.EventLog.SourceExists("Fuentes-BIO-H-Academico"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                   "Fuentes-BIO-H-Academico", "Logs-BIO-H-Academico");
            }
            eventLog1.Source = "Fuentes-BIO-H-Academico";
            eventLog1.Log = "Logs-BIO-H-Academico";
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                eventLog1.WriteEntry("Iniciando Servicio BIO-H Academico");
                timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
                timer1.Interval = 1000;
                timer1.Enabled = true;
                timer1.Start();
            }
            catch (Exception e)
            {
                eventLog1.WriteEntry(e.ToString());
            } 
        }

        private void timer1_Elapsed(object sender, EventArgs e)
        {
            try
            {
                Buscar_Horarios(DateTime.Now);
            }
            catch (Exception ex)
            {
                eventLog1.WriteEntry(ex.ToString());
            }
        }

        private void Buscar_Horarios(DateTime fecha)
        {
            bool conectarse = Conectarse_BD();
            if (conectarse == true)
            {
                DateTime corte = fecha.AddMinutes(((-1) * Holgura_Academica()));
                string dia = Funciones.ObtenerDiaSemana2(fecha);
                string hora = Funciones.ObtenerHora(fecha);
                string cortedia = Funciones.ObtenerHora(corte);
                //Llamo la conexion SQL
                SqlConnection Wdcon_usuario = new SqlConnection(UJGH);
                SqlCommand usuario = new SqlCommand();
                SqlDataReader usuarioDR = null;

                //Instancio la conexion SQL
                usuario.Connection = Wdcon_usuario;

                //Registro el Query SQL
                usuario.CommandText = "SELECT * FROM Vista_Horarios_Docentes WHERE (HRAFIN = @horafin) AND (HRADIA = @dia)";
                usuario.Parameters.AddWithValue("@horafin", hora);
                usuario.Parameters.AddWithValue("@dia", cortedia);

                //Abro la conexion
                Wdcon_usuario.Open();

                //Ejecuto la consulta
                usuarioDR = usuario.ExecuteReader();

                //Empiezo el ciclo
                while (usuarioDR.Read())
                {
                    if (usuarioDR["HRARES"].ToString() != "")
                    {
                        if (Validar_Docente(Convert.ToInt64(usuarioDR["HRARES"].ToString())) == true)
                        {
                            DateTime inicio1 = (DateTime)usuarioDR["HRAINI"];
                            DateTime fecha2 = inicio1.AddMinutes((-1) * Holgura_Academica());
                            string inicio = Funciones.ObtenerHora(fecha2);
                            Int64 docente = Convert.ToInt64(usuarioDR["HRARES"].ToString());
                            if (SalioCorrectamente(docente, inicio, cortedia) == true)
                            {
                                //Calculo las horas que dio clases
                                CalcularHoras(docente, inicio, cortedia);
                            }
                            else
                            {
                                //Denegar la persona
                                Insertar_Denegado(docente, DateTime.Now, Convert.ToDateTime(inicio), Convert.ToDateTime(cortedia));
                            }
                        }
                    }
                }
                //Cierro la conexion

                Wdcon_usuario.Close();
            }
        }
        .
        .
        .
      }

希望你能帮我解决这个问题,在此先感谢。

最佳答案

我修复了它,似乎错误是因为我从另一个服务名称中获得了相同的日志名,我更改了它,现在它似乎可以正常工作(假设它开始了)

我使用了另一个博客的这个来解决错误并找到问题所在

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Diagnostics;

namespace SerivicioBIOHAcademico
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            try
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new BIOHAcad() 
                };
                ServiceBase.Run(ServicesToRun);
            }
            catch(Exception ex)
            {
                string SourceName = "WindowsService.ExceptionLog";
                if (!EventLog.SourceExists(SourceName))
                {
                    EventLog.CreateEventSource(SourceName, "Application");
                }

                EventLog eventLog = new EventLog();
                eventLog.Source = SourceName;
                string message = string.Format("Exception: {0} \n\nStack: {1}", ex.Message, ex.StackTrace);
                eventLog.WriteEntry(message, EventLogEntryType.Error);
            }
        }
    }
}

它给了我我需要的错误

关于c# - Windows 服务给出错误 - System.Security.SecurityException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9619738/

相关文章:

SVNserve 给出错误 1053 服务没有响应启动或控制请求

c# - Dotnet Core Windows 服务中的多个托管服务

c# - 如何在请求结束时释放资源并在 ASP.NET 5/Core 中处理注入(inject)的服务?

c# - 在C#和WPF中学习自动化测试的资源

c# - 如何使用功能区 xml 将图像添加到按钮?

c# - 从 Windows 服务创建文件/文件夹时的最佳实践

winforms - Windows 服务的运行时调试技巧?

c# - 查找未使用/不必要的 assemblyBinding 重定向

c# - codeDom中的switch语句(跳表样式)

delphi - 如何重新启动用 Delphi 编写的 Windows 服务应用程序?