Ejemplo n.º 1
1
      static public ImageProcessingResult Process(string imageName, IBinaryRepository binaryRepository)
      {
         var log = new EventLog("Application")
         {
            Source = "Tadmap"
         };

         log.WriteEntry("Processing image:" + imageName, EventLogEntryType.Information);

         Stream binary = binaryRepository.GetBinary(imageName);

         if (binary == null)
         {
            log.WriteEntry("No binary found:" + imageName, EventLogEntryType.Warning);
            return new ImageProcessingResult { Key = imageName, Result = ImageProcessingResult.ResultType.Failed }; // Image not available in the queue yet.
         }

         // If I have an image I should renew the message.

         IImageSet imageSet = new ImageSet1(imageName);

         int zoomLevels;
         int tileSize;
         imageSet.Create(binary, binaryRepository, out zoomLevels, out tileSize);
         log.WriteEntry("Processing finished.", EventLogEntryType.Information);

         return new ImageProcessingResult
         {
            Key = imageName,
            Result = ImageProcessingResult.ResultType.Complete,
            ZoomLevel = zoomLevels,
            TileSize = tileSize
         };
      }
        /// <summary>
        /// Create log in Event log
        /// </summary>
        /// <param name="message">The message to be logged into the event log</param>
        /// <param name="logType">contains information, warning and error</param>
        private void Log(string message, EventLogEntryType logType)
        {
            System.Diagnostics.EventLog SQLEventLog = new System.Diagnostics.EventLog();

            try
            {
                if (!System.Diagnostics.EventLog.SourceExists(_logSource))
                {
                    this.CreateLog(_logSource);
                }


                SQLEventLog.Source = _logSource;
                SQLEventLog.WriteEntry(Convert.ToString(_logName) + ": " + Convert.ToString(message), logType);
            }
            catch (Exception ex)
            {
                SQLEventLog.Source = _logSource;
                SQLEventLog.WriteEntry(Convert.ToString("INFORMATION: ")
                                       + Convert.ToString(ex.Message),
                                       EventLogEntryType.Error);
            }
            finally
            {
                SQLEventLog.Dispose();
                SQLEventLog = null;
            }
        }
Ejemplo n.º 3
0
        protected override void OnStart(string[] args)
        {
            LMeventLog.WriteEntry("Redirector Service Started", EventLogEntryType.Information, eventId++);
            // Set up a timer that triggers every minute.
            timer           = new System.Timers.Timer();
            timer.Interval  = 60000;            // 1 minute
            timer.AutoReset = true;             // request rerun when ready
            timer.Elapsed  += new System.Timers.ElapsedEventHandler(this.OnTimer);
            timer.Start();

            // Create output folder if it does not exist
            try
            {
                Directory.CreateDirectory(Properties.Settings.Default.WebLogPath);
            }
            catch (Exception e)
            {
                LMeventLog.WriteEntry("Error creating path: " + e.Message, EventLogEntryType.Error, eventId++);
            }

            // Run web server
            RedirectorWebServer.Start(LMeventLog, eventId);

            LMeventLog.WriteEntry("Web Server Started", EventLogEntryType.Information, eventId++);
        }
Ejemplo n.º 4
0
        protected override void OnStart(string[] args)
        {
            // Atualiza o status do serciço para "Inicialização pendente"
            ServiceStatus serviceStatus = new ServiceStatus();

            serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
            serviceStatus.dwWaitHint     = 100000;

            SetServiceStatus(this.ServiceHandle, ref serviceStatus);
            // ---

            // Cria um registro no Log de eventos
            eventLog1.WriteEntry("Starting ZPL network printer.");

            // Cria o timer para processamento em 1 minuto
            timer          = new System.Timers.Timer();
            timer.Interval = 60000; // 60 seconds
            timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
            timer.Start();
            // ---

            // Atualiza o status do serciço para "Iniciado"
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);
            // ---
        }
        /// <summary>
        /// Function happens when event MessageRecieved invokes.
        /// </summary>
        /// <param name="sender">the object that invoked the event </param>
        /// <param name="args">argumnets </param>
        public void onMessage(object sender, MessageRecievedEventArgs args)
        {
            MessageTypeEnum status  = args.Status;
            string          message = args.Message;

            switch (status)
            {
            case (MessageTypeEnum.INFO):
                eventLog1.WriteEntry(message, EventLogEntryType.Information);
                break;

            case (MessageTypeEnum.FAIL):
                eventLog1.WriteEntry(message, EventLogEntryType.FailureAudit);
                break;

            case (MessageTypeEnum.WARNING):
                eventLog1.WriteEntry(message, EventLogEntryType.Warning);
                break;
            }
            string[] argv = { status.ToString(), message };
            bool     result;
            string   messagee = this.controller.ExecuteCommand((int)CommandEnum.CommandEnum.LogCommand, argv, out result);
            //write log to all clients.
            //  this.server.writeAll(messagee);
        }
Ejemplo n.º 6
0
        protected override void OnStart(string[] args)
        {
            var eventLog = new EventLog {Source = "Application"};
            eventLog.WriteEntry(_environment.ApplicationName + "- Application Base Path: " + _environment.ApplicationBasePath, EventLogEntryType.Information);

            try
            {
                InitializeConfiguration();
                Debug.WriteLine("Initializing Service: {ServiceName}", _serviceSettings.ServiceName);
                InitializeContainer();
                InitializeLogging();

                Log.Information("Starting Service: {ServiceName}", _serviceSettings.ServiceName);

                if (StartAction == null)
                {
                    throw new NotImplementedException("A StartAction must be defined in your 'Program' static constructor.");
                }
                StartAction(args);
                Log.Information("Service: {ServiceName} was started.", _serviceSettings.ServiceName);
            }
            catch (Exception ex)
            {
                if (!Environment.UserInteractive)
                {
                    //In case logging is hosed, make sure this goes to the event log
                    eventLog.WriteEntry("An error occurred starting the service. " + ex, EventLogEntryType.Error);
                }

                Log.Error(ex, "Service failed to start {ServiceName}", _serviceSettings.ServiceName);
                throw;
            }
        }
Ejemplo n.º 7
0
        protected override void OnStart(string[] args)
        {
            // Update the service state to Start Pending.
            ServiceStatus serviceStatus = new ServiceStatus();

            serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
            serviceStatus.dwWaitHint     = 100000;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);

            // Update the service state to Running.
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);

            eventLog1.WriteEntry("In OnStart");
            // Set up a timer to trigger every minute.
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 10000; // 10 seconds
            timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
            timer.Start();

            //Process.Start("calc.exe");
            //Form1 myForm = new Form1();
            //myForm.Show();
            //MessageBox.Show("BalloonTip is running");
        }
Ejemplo n.º 8
0
 public void WriteEventLogEntry(string Message)
 {
     if (_eventLog != null)
     {
         _eventLog.WriteEntry(Message);
     }
 }
        protected override void OnStart(string[] args)
        {
            if (!EventLog.SourceExists("SSISIncomingDirectoryWatcher", "."))
            {
                EventLog.CreateEventSource("SSISIncomingDirectoryWatcher", "Application");
            }

            Lg = new EventLog("Application", ".", "SSISIncomingDirectoryWatcher");
            Lg.WriteEntry("Service started at " + DateTime.Now, EventLogEntryType.Information);

            try
            {

                tw = File.CreateText(logFilePath);
                tw.WriteLine("Service started at {0}", DateTime.Now);
                readInConfigValues();
                Watcher = new FileSystemWatcher();
                Watcher.Path = dirToWatch;
                Watcher.IncludeSubdirectories = false;
                Watcher.Created += new FileSystemEventHandler(watcherChange);
                Watcher.EnableRaisingEvents = true;
            }
            catch (Exception ex)
            {
                Lg.WriteEntry(ex.Message, EventLogEntryType.Error);
            }
            finally
            {
                tw.Close();
            }
        }
Ejemplo n.º 10
0
 public SyslogSender(El2SlConfig config, EventLog eventLog, EventLog localLog)
 {
     _enUS = new CultureInfo("en-US");
     _localLog = localLog;
     _config   = config;
     _eventLog = eventLog;
     _encoding = new UTF8Encoding();
     _eventLog.EnableRaisingEvents = true;
     _eventLog.EntryWritten += eventLog_EntryWritten;
     _udpClient = new UdpClient();
     _udpClient.DontFragment = false;
     _udpClient.Connect(_config.Host, _config.Port);
     try
     {
         if (_udpClient.Client.Connected)
         {
             _localLog.WriteEntry(
                 string.Format("el2slservice connected to syslog for send events of {0}",_eventLog.LogDisplayName),
                 EventLogEntryType.Information);
         }
     }
     catch (SocketException se)
     {
         _localLog.WriteEntry("el2slservice can not connect to syslog. Reason: " + se.Message, EventLogEntryType.Error);
     }
 }
Ejemplo n.º 11
0
        public static void Start(System.Diagnostics.EventLog _LMeventLog, int _eventId)
        {
            LMeventLog = _LMeventLog;
            eventId    = _eventId++;

            // In this Redirector server we define two web endpoints
            try
            {
                // This is used by the Notify Driver to receive requests from the driver
                string MyDriverURL = WebProtocol + "://" + WebHostName + ":" + DriverWebPort.ToString() + "/NotifyRequest/";
                wsd = new WebServer(DriverSendResponse, MyDriverURL);
                wsd.Run();
                LMeventLog.WriteEntry("Redirector to driver webserver on: " + MyDriverURL, EventLogEntryType.Information, eventId++);

                // This is used by the Twilio Service to receive responses
                string MyTwilioURL = WebProtocol + "://" + WebHostName + ":" + TwilioWebPort.ToString() + "/TwilioRequest/";
                wst = new WebServer(TwilioSendResponse, MyTwilioURL);
                wst.Run();
                LMeventLog.WriteEntry("Redirector to Twilio webserver on: " + MyTwilioURL, EventLogEntryType.Information, eventId++);
            }
            catch (Exception e)
            {
                LMeventLog.WriteEntry("Failure. Error starting webserver " + e.Message, EventLogEntryType.Error, eventId++);
            }
        }
Ejemplo n.º 12
0
        public void WriteToEventLog(string strLogName, string strSource, string strErrDetail, int level)
        {
            try
            {
                if (!EventLog.SourceExists(strSource))
                    this.CreateLog(strSource, strLogName);

                using (EventLog SQLEventLog = new EventLog())
                {
                    SQLEventLog.Source = strSource;

                    if (level == 1)
                        SQLEventLog.WriteEntry(String.Format("[{0}] \t {1} ", DateTime.Now.ToString(), Convert.ToString(strErrDetail)), EventLogEntryType.Error);
                    else if (level == 2)
                        SQLEventLog.WriteEntry(String.Format("[{0}] \t {1} ", DateTime.Now.ToString(), Convert.ToString(strErrDetail)), EventLogEntryType.Information);

                }
            }
            catch (Exception ex)
            {
                using (EventLog SQLEventLog = new EventLog())
                {
                    SQLEventLog.Source = strSource;
                    SQLEventLog.WriteEntry(String.Format("[{0}] \t {1} ", DateTime.Now.ToString(), Convert.ToString(ex.Message)),
                    EventLogEntryType.Information);
                }
            }
        }
Ejemplo n.º 13
0
 public override void Write(object TraceInfo)
 {
     try
       {
     if (!(TraceInfo is LogInfo))
       throw new TraceListenerException(TraceInfo, "Use 'Write(object)' override and pass 'TraceInfo' instance");
     LogInfo info = TraceInfo as LogInfo;
     this.Output(info);
     if (info.Type != LogType.Execption && info.Type != LogType.HandlerExecutionError)
       return;
     if (!EventLog.SourceExists(((object) info.Type).ToString()))
       EventLog.CreateEventSource(((object) info.Type).ToString(), "TradePlatform.MT4");
     EventLog eventLog = new EventLog();
     eventLog.Source = ((object) info.Type).ToString();
     if (info.Exception != null)
     {
       string message = string.Empty;
       for (; info.Exception != null; info.Exception = info.Exception.InnerException)
     message = message + (object) info.Exception + "\n\n";
       eventLog.WriteEntry(message, EventLogEntryType.Error);
     }
     else
       eventLog.WriteEntry(info.Message, EventLogEntryType.Error);
       }
       catch
       {
       }
 }
        public UCSD_PORTAL_USER()
        {
            this.ServiceName = "UCSD_PORTAL_USER";
            this.AutoLog     = false;

            InitializeComponent();

            eventLog1 = new System.Diagnostics.EventLog();
            if (!System.Diagnostics.EventLog.SourceExists("UCSD_USER_PORTAL"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                    "UCSD_USER_PORTAL", "UCSD_USER_PORTAL_LOG");
            }
            eventLog1.Source = "UCSD_USER_PORTAL";
            eventLog1.Log    = "UCSD_USER_PORTAL_LOG";

            UCSDSettings t = new UCSDSettings();

            eventLog1.WriteEntry("Created UCSD Setting object");
            if (!File.Exists("C:\\MVPORTAL_plugin\\MVPortal_PlugIn_config.XML"))
            {
                t.Serialize("C:\\MVPORTAL_plugin\\MVPortal_PlugIn_config.XML", t);
            }
            UCSDSettings t2 = t.Deserialize("C:\\MVPORTAL_plugin\\MVPortal_PlugIn_config.XML");

            eventLog1.WriteEntry("Created UCSD Setting object - from file");
        }
Ejemplo n.º 15
0
        protected override void OnStart(string[] args)
        {
            WebServiceHost host = new WebServiceHost(Type.GetType(ConfigurationManager.AppSettings["ServiceTypeName"]));

            host.Open();

            Message.SendEmail(ConfigurationManager.AppSettings["BugReportMail"], ConfigurationManager.AppSettings["ServiceName"], "The service has been started");
            eventLog1.WriteEntry(ConfigurationManager.AppSettings["ServiceName"] + " started");
        }
Ejemplo n.º 16
0
 protected override void OnStart(string[] args)
 {
     eventLog1.WriteEntry("In OnStart");
     isRunning = true;
     th        = new Thread(StartUDP);
     th2       = new Thread(StartTCP);
     th.Start();
     th2.Start();
 }
Ejemplo n.º 17
0
        //private void InitializeComponent()
        //{
        //    this.ServiceName = "LogChipper"; 
        //    this.CanHandleSessionChangeEvent = false;
        //    this.CanPauseAndContinue = false;
        //    this.CanShutdown = true;
        //    this.CanStop = Properties.Settings.Default.svcCanStop;
        //}

        protected override void OnStart(string[] args)
        {
            // prep for writing to local event log
            string eventLogName = Properties.Settings.Default.eventLogName;
            string eventLogSource = Properties.Settings.Default.eventLogSource;
            string machineName = ".";
            // warning: Event Log Source must have already been created during the installation
            eventLogger = new EventLog(eventLogName, machineName, eventLogSource);
            eventLogger.WriteEntry("LogChipper syslog forwarding service has started.", EventLogEntryType.Information, 0);

            // prep for posting to remote syslog
            bool useTCP = Properties.Settings.Default.syslogProtocol.ToUpper().Contains("TCP");
            syslogForwarder = new Syslog.Client(
                (string)Properties.Settings.Default.syslogServer,
                (int)Properties.Settings.Default.syslogPort,
                useTCP,
                (int)Syslog.Facility.Syslog,
                (int)Syslog.Level.Information);
            syslogForwarder.Send("[LogChipper syslog forwarding service has started.]");

            // prep to tail the local log file
            //fileName = Properties.Settings.Default.logFilePath;
            if (!File.Exists(fileName))
            {
                eventLogger.WriteEntry("Cannot locate target log file; exiting service.", EventLogEntryType.Error, 404);
                this.Stop();
                Environment.Exit(404); // not very graceful, but prevents more error messages from continuing OnStart after OnStop

                // TODO: handle missing target file more gracefully
                //    bool found = false;
                //
                //    // re-test every minute for 15 minutes
                //    for (int i = 0; i < 15; i++)
                //    {
                //        eventLogger.WriteEntry("Target log file not found; please check the configuration.", EventLogEntryType.Warning, 2);
                //        System.Threading.Thread.Sleep(60 * 1000);
                //        if (File.Exists(fileName))
                //        {
                //            found = true;
                //            break;
                //        }
                //    }
                //    if (!found)
                //    {
                //        eventLogger.WriteEntry("Target log file still doesn't exist; exiting service.", EventLogEntryType.Error, 404);
                //        Environment.Exit(1); // TODO: correct way to exit?
                //    }
            }

            // spin your thread
            if ((workerThread == null) || ((workerThread.ThreadState & 
                (System.Threading.ThreadState.Unstarted | System.Threading.ThreadState.Stopped)) != 0))
            {
                workerThread = new Thread(new ThreadStart(ServiceWorkerMethod));
                workerThread.Start();
            }
        }
Ejemplo n.º 18
0
        public static void i(string logMessage)
        {
            Debug.WriteLine(logMessage);

            if (evt != null)
            {
                evt.WriteEntry(logMessage);
            }
        }
Ejemplo n.º 19
0
        public ActiveDirHandler()
        {
            ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
            this.eventLog1.Log    = "MyNewLog";
            this.eventLog1.Source = "MySource";
            ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();

            Domain = "10.11.1.206";
            eventLog1.WriteEntry("ActiveDirHandler Constructor");
        }
Ejemplo n.º 20
0
        protected override void OnStart(string[] args)
        {
            evtLog.WriteEntry("In OnStart" + ver);


            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 10000;             // 60 seconds
            timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
            timer.Start();
        }
Ejemplo n.º 21
0
        public void TraspasaDocumentos()
        {
            List<IOperacion> lstsrvmiddle = null;
            int nRt = 0;
            ILog oLog = null;
            string sAux = string.Empty;

            EventLog ELog = new EventLog("Application", ".", _sSourceEvLog);
            String sBasePath = System.AppDomain.CurrentDomain.BaseDirectory;
            try
            {
                oLog = new ooLogSrv();
                ELog.WriteEntry(string.Format("Antes de config spring, base path: {0}", sBasePath));

                    try
                    {
                        _appContext = new XmlApplicationContext(Path.Combine(sBasePath, "di.config.xml"));
                    }
                    catch (Exception ex)
                    {
                        oLog.LogException(ex);
                    }
                    ELog.WriteEntry(string.Format("Despues de config spring"));
                    lstsrvmiddle = (List<IOperacion>)_appContext.GetObject("pluginComponentesTraspasoDoc");
                    oLog.LogInfo(string.Format("Application started at  {0}", DateTime.Now));
                    nRt = 0;

                    ELog.WriteEntry(string.Format("Application started at '{0}'", DateTime.Now));

                    try
                    {
                        foreach (IOperacion srvOp in lstsrvmiddle)
                        {
                            srvOp.oLog = oLog;
                            nRt = srvOp.lTraspasar();
                            oLog.LogInfo(string.Format("Application finish procesing of '{0}' registers of  type {1} at '{2}'", nRt, srvOp.GetType().Name, DateTime.Now));
                        }
                    }
                    catch (Exception ex)
                    {
                        oLog.LogException(ex);
                    }

            }
            catch (Exception ex)
            {
                ELog.WriteEntry(string.Format("Excepcion: {0}", ex));
                oLog.LogException(ex);
            }
            finally
            {
                oLog.LogInfo(string.Format("Servicio finaliza ejecucion a las '{0}'", DateTime.Now));
                Thread.CurrentThread.Abort(); //se finaliza el thread
            }
        }
Ejemplo n.º 22
0
 public void WriteEventLogEntry(string Message)
 {
     if (_eventLog != null)
     {
         _eventLog.WriteEntry(Message);
     }
     else
     {
         throw new Exception("Unable to write to event log : not initialized. \r\nMessage to write:\r\n" + Message);
     }
 }
Ejemplo n.º 23
0
        static void Write(string logtype, string logText,
                          [CallerFilePath] string fileName     = "",
                          [CallerMemberName] string methodName = "",
                          [CallerLineNumber] int lineNumber    = 0)
        {
            if (WindowEventLogName == "None")
            {
                return;
            }

            //if (System.Diagnostics.EventLog.Exists("Init"))
            //{
            //    System.Diagnostics.EventLog.Delete("Init");
            //}

            string logmsg = string.Format("[{0}|{1}|{2}]: {3}", fileName, methodName, lineNumber, logText);

            // Create an instance of EventLog
            System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();

            // Check if the event source exists. If not create it.
            if (!System.Diagnostics.EventLog.SourceExists(WindowEventLogSourceName))
            {
                System.Diagnostics.EventLog.CreateEventSource(WindowEventLogSourceName, WindowEventLogName);
            }

            // Set the source name for writing log entries.
            eventLog.Source = WindowEventLogSourceName;

            // Create an event ID to add to the event log
            int eventID = 7;

            switch (logtype)
            {
            case "error":
                // Write an entry to the event log.
                eventLog.WriteEntry(logmsg, System.Diagnostics.EventLogEntryType.Error, eventID);
                break;

            case "warn":
                // Write an entry to the event log.
                eventLog.WriteEntry(logmsg, System.Diagnostics.EventLogEntryType.Warning, eventID);
                break;

            case "info":
                // Write an entry to the event log.
                eventLog.WriteEntry(logmsg, System.Diagnostics.EventLogEntryType.Information, eventID);
                break;
            }


            // Close the Event Log
            eventLog.Close();
        }
Ejemplo n.º 24
0
 public void WriteEventLogEntry(string Message)
 {
     if (_eventLog != null)
     {
         _eventLog.WriteEntry(Message);
     }
     else
     {
         this.WriteLogEntry(Message);                 // write into file
     }
 }
Ejemplo n.º 25
0
 void ILogHnd.OnMsg(int errno, string msg)
 {
     if (MsgInEventLogSchreiben)
     {
         string descr = string.Format("Info: {0}", msg);
         log.WriteEntry(descr, System.Diagnostics.EventLogEntryType.Information);
     }
 }
Ejemplo n.º 26
0
        protected override void OnStart(string[] args)
        {
            string strLog = "###OnStart###";

            base.OnStart(args);
            mdlControladoraWindowsServices.clsManagerWSSiscoMensagem objManagerSiscoMensagem = clsManagerSiscoMensagem();
            if (objManagerSiscoMensagem != null)
            {
                objManagerSiscoMensagem.bStart();
            }
            m_elSiscoMensagem.WriteEntry(strLog);
        }
Ejemplo n.º 27
0
        public static void WriteToEventLog(string strLogName, string strSource, string strErrDetail, string type, string methodsClass)
        {
            System.Diagnostics.EventLog SQLEventLog = new System.Diagnostics.EventLog();
            int EventID = 0;

            try
            {
                if (!System.Diagnostics.EventLog.SourceExists(strLogName))
                {
                    CreateLog(strLogName);
                }

                SQLEventLog.Log = strLogName;

                if (!string.IsNullOrEmpty(methodsClass))
                {
                    SQLEventLog.Source = methodsClass;
                }
                else
                {
                    SQLEventLog.Source = strLogName;
                }

                if (type == "Information")
                {
                    SQLEventLog.WriteEntry(Convert.ToString(strSource) + Environment.NewLine
                                           + Convert.ToString(strErrDetail), EventLogEntryType.Information, EventID);
                }
                else
                {
                    SQLEventLog.WriteEntry(Convert.ToString(strSource) + Environment.NewLine
                                           + Convert.ToString(strErrDetail), EventLogEntryType.Error, EventID);
                }
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(methodsClass))
                {
                    SQLEventLog.Source = methodsClass;
                }
                else
                {
                    SQLEventLog.Source = "EpicorERPLogException";
                }
                SQLEventLog.WriteEntry(Convert.ToString("INFORMATION: ") + Environment.NewLine
                                       + Convert.ToString(ex.Message), EventLogEntryType.Error);
            }
            finally
            {
                SQLEventLog.Dispose();
                SQLEventLog = null;
            }
        }
Ejemplo n.º 28
0
        protected override void OnStart(string[] args)
        {
            myEventLog.WriteEntry("Service Starting");
            baseTimer          = new System.Timers.Timer();
            baseTimer.Interval = 1000;
            baseTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
            baseTimer.Start();
            myEventLog.WriteEntry("Service Started");

            thisFarm = new ComputeFarm.ComputeFarm(myEventLog);
            thisFarm.Init();
        }
Ejemplo n.º 29
0
        public Boolean CreateCSVfile(string fileName, System.Diagnostics.EventLog eventLog1)
        {
            try
            {
                STARTUPINFO         si = new STARTUPINFO();
                PROCESS_INFORMATION pi = new PROCESS_INFORMATION();

                if (fileName.Contains("INV"))
                {
                    System.Diagnostics.Process.Start(BatFileName, "INV");
                }
                if (fileName.Contains("ISU"))
                {
                    System.Diagnostics.Process.Start(BatFileName, "ISU");
                }
                if (fileName.Contains("MXQ"))
                {
                    eventLog1.WriteEntry("In CreateCSVfile - Before BAT File");
                    //System.Diagnostics.Process ttt = System.Diagnostics.Process.Start(BatFileName, "MXQ");
                    if (CreateProcess(BatFileName + " MXQ", null, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref si, out pi))
                    {
                        eventLog1.WriteEntry("In CreateCSVfile - After BAT File : Success");
                    }
                    else
                    {
                        eventLog1.WriteEntry("In CreateCSVfile - After BAT File : Faild");
                    }
                }
                if (fileName.Contains("NOP"))
                {
                    System.Diagnostics.Process.Start(BatFileName, "NOP");
                }
                if (fileName.Contains("ORD"))
                {
                    System.Diagnostics.Process.Start(BatFileName, "ORD");
                }
                if (fileName.Contains("QOH"))
                {
                    System.Diagnostics.Process.Start(BatFileName, "QOH");
                }
                if (fileName.Contains("TRN"))
                {
                    System.Diagnostics.Process.Start(BatFileName, "TRN");
                }
                return(true);
            }
            catch (Exception ex)
            {
                eventLog1.WriteEntry("In CreateCSVfile - " + ex.Message);
                return(false);
            }
        }
Ejemplo n.º 30
0
 public void Watch()
 {
     eventLog1.WriteEntry("In Watch");
     watcher.Path         = directoryToWatch;
     watcher.NotifyFilter = NotifyFilters.LastAccess |
                            NotifyFilters.LastWrite |
                            NotifyFilters.FileName |
                            NotifyFilters.DirectoryName;
     watcher.Filter              = "*.*";
     watcher.Changed            += new FileSystemEventHandler(OnChanged);
     watcher.Created            += new FileSystemEventHandler(OnChanged);
     watcher.EnableRaisingEvents = true;
 }
Ejemplo n.º 31
0
        protected override void OnStart(string[] args)
        {
            try
            {
                System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
                appLog.Source = "Gestão escolar";

                if (args.Length > 0)
                {
                    try
                    {
                        System.Configuration.Configuration config = ConfigurationManager.
                                                                    OpenExeConfiguration(ConfigurationUserLevel.None);

                        if (config == null)
                        {
                            appLog.WriteEntry("config null");
                        }

                        config.AppSettings.Settings.Remove("porta");

                        // Primeiro argumento é a porta.
                        config.AppSettings.Settings.Add("porta", args[0]);

                        config.Save(ConfigurationSaveMode.Modified);
                    }
                    catch (Exception ex)
                    {
                        appLog.WriteEntry("Erro ao alterar o config: " + ex.Message);
                    }
                }

                string porta = ConfigurationManager.AppSettings.Get("porta");

                if (!string.IsNullOrEmpty(porta))
                {
                    appLog.WriteEntry("Iniciando serviço na porta: " + porta);
                    scheduler = new GestaoEscolarScheduler(porta);
                }
                else
                {
                    scheduler = new GestaoEscolarScheduler();
                }

                scheduler.Start();
            }
            catch (Exception ex)
            {
                Util.GravarErro(ex, scheduler.Sis_ID);
            }
        }
Ejemplo n.º 32
0
        void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            #region 事件日志操作
            //不允许向Security里写数据

            #region 写到Application里
            {
                if (!EventLog.SourceExists("CrazyIIS_Application"))
                {
                    EventLog.CreateEventSource("CrazyIIS_Application", "Application");
                }

                EventLog log = new EventLog();
                log.Source = "CrazyIIS_Application";
                log.WriteEntry("柳永法提醒您,这是:CrazyIIS_Application", EventLogEntryType.FailureAudit);
                log.WriteEntry("柳永法提醒您,这是:CrazyIIS_Application", EventLogEntryType.Information);
                log.WriteEntry("柳永法提醒您,这是:CrazyIIS_Application", EventLogEntryType.Warning);
            }
            #endregion

            #region 写到System里
            {
                if (!EventLog.SourceExists("CrazyIIS_System"))
                {
                    EventLog.CreateEventSource("CrazyIIS_System", "System");
                }

                EventLog log = new EventLog();
                log.Source = "CrazyIIS_System";
                log.WriteEntry("柳永法提醒您,这是:CrazyIIS_System", EventLogEntryType.FailureAudit);
                log.WriteEntry("柳永法提醒您,这是:CrazyIIS_System", EventLogEntryType.Information);
                log.WriteEntry("柳永法提醒您,这是:CrazyIIS_System", EventLogEntryType.Warning);
            }
            #endregion

            // EventLog.Delete("我的软件");
            // EventLog.DeleteEventSource("CrazyIIS");

            if (!EventLog.SourceExists("CrazyIIS"))
            {
                EventLog.CreateEventSource("CrazyIIS", "我的软件");
            }

            EventLog myLog = new EventLog();
            myLog.Source = "CrazyIIS";
            myLog.WriteEntry("CrazyIIS", EventLogEntryType.Error, 12345, 22222);
            myLog.WriteEntry("CrazyIIS", EventLogEntryType.FailureAudit, 12345, 22222);
            #endregion
        }
Ejemplo n.º 33
0
 protected override void OnStart(string[] args)
 {
     try {
         initService();
     }catch (Exception e) {
         eventLog1.WriteEntry(e.Message);
     }
 }
Ejemplo n.º 34
0
        protected override void OnStart(string[] args)
        {
            if (childThread.IsAlive)
            {
                return;
            }

            eventLog1.WriteEntry("In OnStart of FPP");


            ThreadStart childref = new ThreadStart(MyThread);

            childThread = new Thread(childref);
            childThread.Start();
        }
        void ILogHnd.OnLog(string userId, ILogInfo info)
        {
            try
            {
                switch (info.LogType)
                {
                case EnumLogType.Error:
                {
                    string descr = string.Format("Err: user= {0:s}: {1} / {2}", info.LogDate, userId, info.Message);
                    Debug.Fail("SysteEventLogHnd: " + descr);
                    log.WriteEntry(descr, System.Diagnostics.EventLogEntryType.Error);
                }


                break;

                case EnumLogType.Message:
                    if (MsgInEventLogSchreiben)
                    {
                        string descr = string.Format("Msg: user= {0:s}: {1} / {2}", info.LogDate, userId, info.Message);
                        Debug.WriteLine("SysteEventLogHnd: " + descr);
                        log.WriteEntry(descr, System.Diagnostics.EventLogEntryType.Information);
                    }
                    break;

                case EnumLogType.Status:
                    if (StatusInEventLogSchreiben)
                    {
                        string descr = string.Format("Sta: user= {0}: {1} / {2}", info.LogDate, userId, info.Message);
                        Debug.WriteLine("SysteEventLogHnd: " + descr);
                        log.WriteEntry(descr, System.Diagnostics.EventLogEntryType.Information);
                    }
                    break;

                default:
                {
                    string descr = string.Format("Unbekannter Logtyp: user= {0:s}: {1} / {2}", info.LogDate, userId, info.Message);
                    log.WriteEntry(descr, System.Diagnostics.EventLogEntryType.Error);
                    Debug.Fail("SysteEventLogHnd: " + descr);
                }
                break;
                }
            }
            catch (Exception ex)
            {
                SelfDeregisterILogHnd();
            }
        }
Ejemplo n.º 36
0
        public override void Write(LogEntry entry)
        {
            EventLogEntryType type;

            switch (entry.Level)
            {
                case Level.Debug:
                case Level.Trace:
                case Level.Info:
                    type = EventLogEntryType.Information;
                    break;
                case Level.Warn:
                    type = EventLogEntryType.Warning;
                    break;
                case Level.Error:
                case Level.Fatal:
                    type = EventLogEntryType.Error;
                    break;
                default:
                    type = EventLogEntryType.Information;
                    break;
            }

            using (var eventLog = new EventLog { Source = EventLogSource ?? entry.Source })
            {
                var fmt = EntryFormatter ?? entry.Logger.LogManager.GetFormatter<string>();
                var msg = fmt.Convert(entry);
                eventLog.WriteEntry(msg, type);
            }
        }
Ejemplo n.º 37
0
        public static void LogEventInfo(string info)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                string sourceName = @"Medalsoft";
                string logName = @"WF";

                if (EventLog.SourceExists(sourceName))
                {

                    string oldLogName = EventLog.LogNameFromSourceName(sourceName, System.Environment.MachineName);
                    if (!oldLogName.Equals(logName))
                    {
                        EventLog.Delete(oldLogName);
                    }
                }

                if (!EventLog.Exists(logName))
                {
                    EventLog.CreateEventSource(sourceName, logName);
                }

                EventLog myLog = new EventLog();
                myLog.Source = sourceName;
                myLog.Log = logName;

                myLog.WriteEntry(info, EventLogEntryType.Information);

            });
        }
Ejemplo n.º 38
0
        static void Main(string[] args)
        {
            //
            // New-EventLog -source "MySource" -logname "MyLog" (cf. https://technet.microsoft.com/en-us/library/hh849768.aspx)
            // Run eventvwr
            // Remove-EventLog -logname "MyLog" (cf. https://technet.microsoft.com/en-us/library/hh849786.aspx)
            //


            WriteLine("Option A");
            var eventLog = new EventLog() {Source = "Application"};
            eventLog.WriteEntry("Message Option A");

            WriteLine("Option B");
            var eventLogB = new EventLog() {Source = "MyLog", EnableRaisingEvents = true};
            var eventInstanceB = new EventInstance(0, 1);
            eventLogB.WriteEvent(eventInstanceB, "Message Option B");

            WriteLine("Option C");
            var eventLogC = new EventLog() {Source = "MyLog"};
            eventLogC.WriteEntry("Message Option C", EventLogEntryType.Error);

            WriteLine("Option D");
            var eventLogD = new EventLog() {Source = "MySource", EnableRaisingEvents = true};
            eventLogD.WriteEntry("Message Option D", EventLogEntryType.Error);

            WriteLine("Done.");
            ReadLine();
        }
Ejemplo n.º 39
0
        public static void SetWindowsEventLog_UAC()
        {
            if ((Config.Settings.EventLog_WriteTo_WindowsApplicationLog == true) || (Config.Settings.ErrorLog_WriteTo_WindowsApplicationLog == true))
            {
                // check first if its possible to write to even log without being admin
                try
                {
                    DateTime now = DateTime.Now;
                    System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();

                    // Set the source name for writing log entries.
                    eventLog.Source = "BlobIM";

                    // Create an event ID to add to the event log
                    int eventID = 111;

                    // Write an entry to the event log.
                    eventLog.WriteEntry("Permission Check" + " - " + now + " \r\n This entry is created when BIM is started to verify if it has permissions to write to windows event log.",
                                        System.Diagnostics.EventLogEntryType.Information,
                                        eventID);

                    // Close the Event Log
                    eventLog.Close();
                }
                catch (Exception e)
                {
                    System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
                    bool administrativeMode = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);

                    if (!administrativeMode)
                    {
                        MessageBox.Show("Administrative Permissions Required \n You have selected in the BIM Configuration to have BIM Log Events to the Windows Event Log. \n It does not appear it is possible with the current user, BIM will now request Administrative Permissions to do so. ");
                        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                        startInfo.Verb     = "runas";
                        startInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
                        try
                        {
                            System.Diagnostics.Process.Start(startInfo);
                            Application.Exit();
                            Environment.Exit(0);
                        }
                        catch (Exception ex)
                        {
                            Alerting.ErrorLogging.WriteTo_Log("Failed Running as Administrator", ex.ToString());
                            return;
                        }
                        return;
                    }
                    else
                    {
                        System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();
                        // Check if the event source exists. If not create it.
                        if (!System.Diagnostics.EventLog.SourceExists("BlobIM"))
                        {
                            System.Diagnostics.EventLog.CreateEventSource("BlobIM", "Application");
                        }
                    }
                }
            }
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Démarrage du service.
        /// </summary>
        ///
        protected override void OnStart(string[] args)
        {
            //eventLog1.WriteEntry("started !");

            elapsed = 0;
            Process theProcess = new Process();

            theProcess.StartInfo.UseShellExecute  = true;
            theProcess.StartInfo.WorkingDirectory = Environment.GetEnvironmentVariable("DRQUEUE_BIN");
            theProcess.StartInfo.FileName         = "cygserver.exe"; //theProcess.StartInfo.WorkingDirectory + "\\cygserver.exe";
            theProcess.Start();
            eventLog1.WriteEntry(theProcess.StartInfo.FileName + " started !");

            //try
            //{
            //Process []findProcess;
            //do
            //{
            //findProcess = Process.GetProcessesByName("cygserver");
            //}
            //while (findProcess.Length < 1);
            timer1.Start();
            //}
            //catch (System.ServiceProcess.TimeoutException)
            //{
            //}
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Writes the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="execption">The execption.</param>
        /// <param name="eventLogType">Type of the event log.</param>
        private void Write(object message, Exception execption, EventLogEntryType eventLogType)
        {
            StringBuilder sb = new StringBuilder();

            System.Diagnostics.EventLog eventLogger = new System.Diagnostics.EventLog();
            if (!System.Diagnostics.EventLog.SourceExists(eventLogSource))
            {
                System.Diagnostics.EventLog.CreateEventSource(eventLogSource, eventLogName);
            }

            sb.Append(message).Append(NEW_LINE);
            while (execption != null)
            {
                sb.Append("Message: ").Append(execption.Message).Append(NEW_LINE)
                .Append("Source: ").Append(execption.Source).Append(NEW_LINE)
                .Append("Target site: ").Append(execption.TargetSite).Append(NEW_LINE)
                .Append("Stack trace: ").Append(execption.StackTrace).Append(NEW_LINE);

                // Walk the InnerException tree
                execption = execption.InnerException;
            }

            eventLogger.Source = eventLogName;
            eventLogger.WriteEntry(String.Format(ERROR_MSG, eventLogSource, sb), eventLogType);
        }
Ejemplo n.º 42
0
        public sigConfigServer(String[] args)
        {
            // Initialise variables and check commandline arguments for values (for manual specific logging)
            InitializeComponent();
            this.AutoLog = false;
            sigConfigServerServiceLog = new System.Diagnostics.EventLog();
            string logSource = "sigConfigServerSource";
            string logName = "sigConfigServerLog";

            if (args.Count() > 0)
            {
                logSource = args[0];
            }
            if (args.Count() > 1)
            {
                logSource = args[1];
            }

            if (!System.Diagnostics.EventLog.SourceExists(logSource))
            {
                System.Diagnostics.EventLog.CreateEventSource(logSource, logName);
            }

            sigConfigServerServiceLog.Source = logSource;
            sigConfigServerServiceLog.Log = logName;

            // Logging
            sigConfigServerServiceLog.WriteEntry("Roswell Email Signature Sync service (server mode) created.");

            this.OnStart();
        }
Ejemplo n.º 43
0
 // 把错误信息写到日志文件里
 public void WriteErrorLog(string strText,
     EventLogEntryType type = EventLogEntryType.Error)
 {
     EventLog Log = new EventLog();
     Log.Source = "dp2ZServer";
     Log.WriteEntry(strText, EventLogEntryType.Error);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="WindowsEventLogBackgroundErrorLogger"/> class.
        /// </summary>
        public WindowsEventLogBackgroundErrorLogger()
        {
            _logAction = new Lazy<Action<BackgroundErrorLog>>(() =>
            {
                try
                {
                    if (!EventLog.SourceExists(Source))
                    {
                        EventLog.CreateEventSource(Source, LogName);
                    }

                    var eventLog = new EventLog(LogName)
                    {
                        Source = Source,
                    };

                    var eventLogEntryType = EventLogEntryType;

                    return log => eventLog.WriteEntry(log.Format(), eventLogEntryType);
                }
                catch
                {
                    return log => {};
                }
            });
        }
Ejemplo n.º 45
0
        static void Main()
        {
            try
            {
                var program = new Program();

                program.WaitToSendAMessage();

                program.SendAMessage();
            }
            catch (Exception exception)
            {
                var assemblyName = typeof(Program).AssemblyQualifiedName;

                if (!EventLog.SourceExists(assemblyName))
                    EventLog.CreateEventSource(assemblyName, "Application");

                var log = new EventLog { Source = assemblyName };
                log.WriteEntry(string.Format("{0}", exception), EventLogEntryType.Error);
            }
            finally
            {
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
        }
 static void Main(string[] args)
 {
     EventLog myLog = new EventLog("Application");
     myLog.Source = "My Application";
     myLog.WriteEntry("Could not connect", EventLogEntryType.Error, 1001, 1);
     Console.ReadKey();
 }
Ejemplo n.º 47
0
        private static void WriteLog(TraceLevel level, String messageText)
        {
            try
            {
                EventLogEntryType LogEntryType;
                switch (level)
                {
                    case TraceLevel.Error:
                        LogEntryType = EventLogEntryType.Error;
                        break;
                    default:
                        LogEntryType = EventLogEntryType.Error;
                        break;
                }
                String LogName = "Application";
                if (!EventLog.SourceExists(LogName))
                {
                    EventLog.CreateEventSource(LogName, "BIZ");
                }

                EventLog eventLog = new EventLog(LogName, ".", LogName);//��־���ԵĻ���
                eventLog.WriteEntry(messageText, LogEntryType);
            }
            catch
            {
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Writes the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="execption">The execption.</param>
        /// <param name="eventLogType">Type of the event log.</param>
        private void Write(object message, Exception execption, EventLogEntryType eventLogType)
        {
            StringBuilder sb = new StringBuilder();

            System.Diagnostics.EventLog eventLogger = new System.Diagnostics.EventLog();
            if (!System.Diagnostics.EventLog.SourceExists(eventLogSource))
            {
                System.Diagnostics.EventLog.CreateEventSource(eventLogSource, eventLogName);
            }

            sb.Append(message).Append(NEW_LINE);
            while (execption != null)
            {
                sb.Append("Message: ").Append(execption.Message).Append(NEW_LINE)
                .Append("Source: ").Append(execption.Source).Append(NEW_LINE)
                .Append("Target site: ").Append(execption.TargetSite).Append(NEW_LINE)
                .Append("Stack trace: ").Append(execption.StackTrace).Append(NEW_LINE);

                // Walk the InnerException tree
                execption = execption.InnerException;
            }

            eventLogger.Source = eventLogSource;
            eventLogger.WriteEntry(String.Format(ERROR_MSG, eventLogName, sb), eventLogType);
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Writes the log entry.
        /// </summary>
        /// <param name="entry">Log entry.</param>
        public void WriteLogEntry(LogEntry entry)
        {
            if (entry == null)
                return;

            var eventType = EventLogEntryType.Information;

            // create category
            try
            {
                if (!EventLog.SourceExists(entry.Source))
                    EventLog.CreateEventSource(entry.Source, EventLogName);
            }
            catch
            {
                entry.Source = DiagnosticsResourceHelper.DefaultEventSource;
            }

            // get event type
            var enumAsString = entry.Type.ToString();
            if (Enum.IsDefined(typeof(EventLogEntryType), enumAsString))
                eventType = (EventLogEntryType)Enum.Parse(typeof(EventLogEntryType), enumAsString);

            // log the entry
            var log = new EventLog();
            log.Source = entry.Source;
            log.Log = EventLogName;
            log.WriteEntry(string.Concat(entry.Message, Environment.NewLine, entry.StackTrace), eventType);
        }
        public void Init(HttpApplication context)
        {
            //注册对于全局错误的记录
            context.Error += OnError;

            #region 记录UnhandledException

            //使用Double-Check机制保证在多线程并发下只注册一次UnhandledException处理事件
            if (!hasInitilized)
            {
                lock (syncRoot)
                {
                    if (!hasInitilized)
                    {
                        //1. 按照.net的习惯,依然首先将该内容写入到系统的EventLog中
                        string webenginePath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "webengine.dll");
                        //通过webengine.dll来查找asp.net的版本,eventlog的名称由asp.net+版本构成
                        if (!File.Exists(webenginePath))
                        {
                            throw new Exception(String.Format(CultureInfo.InvariantCulture, "Failed to locate webengine.dll at '{0}'.  This module requires .NET Framework 2.0.", webenginePath));
                        }

                        FileVersionInfo ver = FileVersionInfo.GetVersionInfo(webenginePath);
                        eventSourceName = string.Format(CultureInfo.InvariantCulture, "ASP.NET {0}.{1}.{2}.0", ver.FileMajorPart, ver.FileMinorPart, ver.FileBuildPart);

                        if (!EventLog.SourceExists(eventSourceName))
                        {
                            throw new Exception(String.Format(CultureInfo.InvariantCulture, "There is no EventLog source named '{0}'. This module requires .NET Framework 2.0.", eventSourceName));
                        }

                        //在出现问题后将内容记录下来
                        AppDomain.CurrentDomain.UnhandledException += (o, e) =>
                                                                          {
                                                                              if (Interlocked.Exchange(ref unhandledExceptionCount, 1) != 0)
                                                                                  return;

                                                                              string appId = (string)AppDomain.CurrentDomain.GetData(".appId");
                                                                              appId = appId ?? "No-appId";

                                                                              Exception currException;
                                                                              StringBuilder sb = new StringBuilder();
                                                                              sb.AppendLine(appId);
                                                                              for (currException = (Exception)e.ExceptionObject; currException != null; currException = currException.InnerException)
                                                                              {
                                                                                  sb.AppendFormat("{0}\n\r", currException.ToString());
                                                                                  _log.Error(currException);
                                                                              }

                                                                              EventLog eventLog = new EventLog { Source = eventSourceName };
                                                                              eventLog.WriteEntry(sb.ToString(), EventLogEntryType.Error);
                                                                          };

                        //初始化后设置该值为true保证不再继续注册事件
                        hasInitilized = true;
                    }
                }
            }

            #endregion
        }
Ejemplo n.º 51
0
        public ExceptionEvent()
        {
            sSource = "dotNETSampleApp";
            sLog = "Application";
            sEvent = "Sample Event";
            // Create the source, if it does not already exist.
               if (!EventLog.SourceExists(sSource))
            {
                //An event log source should not be created and immediately used.
                //There is a latency time to enable the source, it should be created
                //prior to executing the application that uses the source.
                //Execute this sample a second time to use the new source.
                EventLog.CreateEventSource(sSource, sLog);
                Console.WriteLine("CreatedEventSource");
                Console.WriteLine("Exiting, execute the application a second time to use the source.");
                // The source is created.  Exit the application to allow it to be registered.
                return;
            }

            // Create an EventLog instance and assign its source.
            EventLog myLog = new EventLog();
            myLog.Source = sSource;

            // Write an informational entry to the event log.
            myLog.WriteEntry("Writing to event log.");
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            EventLog log = new EventLog("EventLog Log");
            log.Source = "LoggingApp";            
            log.WriteEntry("LoggingApp Started", EventLogEntryType.Information, 1001);

        }
Ejemplo n.º 53
0
        void OnUnhandledException(object o, UnhandledExceptionEventArgs e) {
            // Let this occur one time for each AppDomain.
            if (Interlocked.Exchange(ref _unhandledExceptionCount, 1) != 0)
                return;

            StringBuilder message = new StringBuilder("\r\n\r\nUnhandledException logged by UnhandledExceptionModule.dll:\r\n\r\nappId=");

            string appId = (string) AppDomain.CurrentDomain.GetData(".appId");
            if (appId != null) {
                message.Append(appId);
            }
            

            Exception currentException = null;
            for (currentException = (Exception)e.ExceptionObject; currentException != null; currentException = currentException.InnerException) {
                message.AppendFormat("\r\n\r\ntype={0}\r\n\r\nmessage={1}\r\n\r\nstack=\r\n{2}\r\n\r\n",
                                     currentException.GetType().FullName, 
                                     currentException.Message,
                                     currentException.StackTrace);
            }           

            EventLog Log = new EventLog();
            Log.Source = _sourceName;
            Log.WriteEntry(message.ToString(), EventLogEntryType.Error);
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Logs an error to the Windows event log
        /// </summary>
        /// <param name="eventLog">The event log</param>
        /// <param name="source">The source of the error</param>
        /// <param name="errorMessage">The error message</param>
        public static void LogError(string eventLog, string source, string errorMessage)
        {
            // Thread abort can occur because of cleanup code and we do not need to log this
            if (!errorMessage.Contains("Thread was being aborted"))
            {
                try
                {
                    // Create an EventLog instance and assign its source.
                    EventLog log = new EventLog(eventLog);
                    log.Source = source;
                    log.WriteEntry(errorMessage, EventLogEntryType.Error);
                    log.Dispose();
                    log = null;
                }
                catch
                {
                    // We do not want to stop processing if we cannot log to the event log,
                    // we also do not want to re-throw an exception, because this will just cause an infinite loop
                }

                try
                {
                    // Email the error to Support
                    EmailError(errorMessage);
                }
                catch
                {
                    // We do not want to stop processing if we cannot log to the event log,
                    // we also do not want to re-throw an exception, because this will just cause an infinite loop
                }
            }
        }
Ejemplo n.º 55
0
        public static void WriteLog(string message, EventLogEntryType type)
        {
            //WindowsIdentity winId = (WindowsIdentity)System.Security.Principal.WindowsIdentity.GetCurrent();
            //WindowsImpersonationContext ctx = null;
            try
            {
                // Start impersonating
                //ctx = winId.Impersonate();
                // Now impersonating
                // Access resources using the identity of the authenticated user
                System.Diagnostics.EventLog appLog =
             new System.Diagnostics.EventLog();
                appLog.Source = "PMM Presentation";
                appLog.WriteEntry(message, type);
            }

            // Prevent exceptions from propagating
            catch
            {
            }
            //finally
            //{
            //    // Revert impersonation
            //    if (ctx != null)
            //        ctx.Undo();
            //}
        }
        static void Main()
        {
            if (!EventLog.SourceExists("SelfMailer"))
            {
                EventLog.CreateEventSource("SelfMailer", "Mes applications");
            }
            EventLog eventLog = new EventLog("Mes applications", ".", "SelfMailer");
            eventLog.WriteEntry("Mon message", EventLogEntryType.Warning);

            BooleanSwitch booleanSwitch = new BooleanSwitch("BooleanSwitch", "Commutateur booléen.");
            TraceSwitch traceSwitch = new TraceSwitch("TraceSwitch", "Commutateur complexe.");

            TextWriterTraceListener textListener = new TextWriterTraceListener(@".\Trace.txt");
            Trace.Listeners.Add(textListener);

            Trace.AutoFlush = true;
            Trace.WriteLineIf(booleanSwitch.Enabled, "Démarrage de l'application SelfMailer");

            Project = new Library.Project();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Forms.Main());

            Trace.WriteLineIf(traceSwitch.TraceInfo, "Arrêt de l'application SelfMailer");
        }
 void fsw_Changed(object sender, FileSystemEventArgs e)
 {
     string s;
     if (e.ChangeType == WatcherChangeTypes.Changed)
     {
         using(TextReader tr = new StreamReader(e.FullPath))
         { 
             while(tr.Peek() > -1)
             {
                 s = tr.ReadLine();
                 if (s.Contains("Teste"))
                 {
                     if (s.Contains("No"))
                     {
                         System.Diagnostics.EventLog eve = new EventLog("ConfigAcess");
                         eve.Source = "Service";
                         eve.WriteEntry("Seurity Changed", EventLogEntryType.Warning);            
                     }
                     else
                     {
                         System.Diagnostics.EventLog eve = new EventLog("ConfigAcess");
                         eve.Source = "Service";
                         eve.WriteEntry("Changed config file", EventLogEntryType.Information);            
                     }
                 }
             }
         }
     }
     
     //throw new NotImplementedException();
 }
Ejemplo n.º 58
0
        private void LogEvent(string sText, eloglevel loglevel)
        {
            EventLogEntryType EventType;

            switch (loglevel)
            {
            case eloglevel.error:
                EventType = EventLogEntryType.Error;
                break;

            case eloglevel.warn:
                EventType = EventLogEntryType.Warning;
                break;

            case eloglevel.info:
                EventType = EventLogEntryType.Information;
                break;

            default:
                EventType = EventLogEntryType.Information;
                break;
            }
            //open and write to event log.
            System.Diagnostics.EventLog oEV = new System.Diagnostics.EventLog();
            oEV.Source = m_ProcessName;
            oEV.WriteEntry(sText, EventType);
            oEV.Close();
        }
Ejemplo n.º 59
0
        private void TicketEvolutionServiceProjectInstallerAfterInstall(object sender, InstallEventArgs e)
        {
            var controller = new ServiceController(WindowServiceInstaller.ServiceName);
            try
            {
                controller.Start();
            }
            catch (Exception ex)
            {
                try
                {
                    var source = WindowServiceInstaller.ServiceName;
                    var log = WindowServiceInstaller.DisplayName;
                    if (!EventLog.SourceExists(source))
                        EventLog.CreateEventSource(source, log);

                    var eLog = new EventLog { Source = source };

                    eLog.WriteEntry(@"The service could not be started. Please start the service manually. Error: " + ex.Message, EventLogEntryType.Error);
                }
                catch
                {

                }

            }
        }
Ejemplo n.º 60
-1
        // Handle the UI exceptions by showing a dialog box, and asking the user whether
        // or not they wish to abort execution.
        // NOTE: This exception cannot be kept from terminating the application - it can only
        // log the event, and inform the user about it.
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                var ex = (Exception)e.ExceptionObject;
                const string errorMsg = "An error occurred in Subtitle Edit. Please contact the adminstrator with the following information:\n\n";

                // Since we can't prevent the app from terminating, log this to the event log.
                if (!EventLog.SourceExists("ThreadException"))
                {
                    EventLog.CreateEventSource("ThreadException", "Application");
                }

                // Create an EventLog instance and assign its source.
                using (var eventLog = new EventLog { Source = "ThreadException" })
                {
                    eventLog.WriteEntry(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);
                }
            }
            catch (Exception exc)
            {
                try
                {
                    MessageBox.Show("Fatal Non-UI Error in Subtitle Edit", "Fatal Non-UI Error. Could not write the error to the event log. Reason: " + exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                finally
                {
                    Application.Exit();
                }
            }
        }