示例#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
         };
      }
示例#2
0
        protected override void OnStart(string[] args)
        {
            ConfigurationManager.RefreshSection("AppSetings");

            string logSource = ConfigurationManager.AppSettings["LogSource"];
            string logName = ConfigurationManager.AppSettings["LogName"];

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

            log = new EventLog { Source = logSource };

            int port;
            if (!int.TryParse(ConfigurationManager.AppSettings["ListenPort"], out port))
            {
                port = 9999;
            }

            server = new DashboardServer(port, new PrivateDataSource());
            server.Log = new EventLogger { EventLog = log };

            server.Start();
        }
示例#3
0
 internal EventLogLogProvider(string shellId)
 {
     string str = this.SetupEventSource(shellId);
     this._eventLog = new EventLog();
     this._eventLog.Source = str;
     this._resourceManager = ResourceManagerCache.GetResourceManager(Assembly.GetExecutingAssembly(), "Logging");
 }
示例#4
0
        /// <summary>
        /// The constructor.
        /// </summary>
        /// <param name="source">The source name by which the application is registered on the local computer.</param>
        /// <param name="logName">The name of the log the source's entries are written to.</param>
        public EventViewerLogger(string source, string logName)
        {
            // Sanitize
            if (string.IsNullOrWhiteSpace(source))
            {
                throw new ArgumentException("cannot be null, empty, or white space", "source");
            }
            if (string.IsNullOrWhiteSpace(logName))
            {
                throw new ArgumentException("cannot be null, empty, or white space", "logName");
            }

            // Attempt to ensure that the event log source exists
            try
            {
                if (!EventLog.SourceExists(source))
                {
                    EventLog.CreateEventSource(source, logName);
                }
            }
            catch (SecurityException)
            {
                // Ignore it...
            }

            // Initialize the event log for logging
            _eventLog = new EventLog
            {
                Source = source,
                Log = logName
            };
        }
示例#5
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);
        }
示例#6
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string svcPath = Path.Combine(Environment.CurrentDirectory, "DS4ToolService.exe");

            ServiceController sc = new ServiceController(Constants.SERVICE_NAME, Environment.MachineName);
            ServiceControllerPermission scp = new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, Environment.MachineName, Constants.SERVICE_NAME);
            scp.Assert();
            sc.Refresh();
            ServiceInstaller si = new ServiceInstaller();

            if (si.DoesServiceExist(Constants.SERVICE_NAME))
            {
                if (sc.Status == ServiceControllerStatus.Running)
                    sc.Stop();

                sc.WaitForStatus(ServiceControllerStatus.Stopped);
                si.UnInstallService(Constants.SERVICE_NAME);
                MessageBox.Show("Service removed");
            }

            EventLog eventLog = new EventLog();
            eventLog.Source = Constants.SERVICE_NAME;
            eventLog.Log = "Application";
            if (!EventLog.SourceExists(eventLog.Source))
            {
                EventLog.DeleteEventSource(eventLog.Source, Environment.MachineName);
                MessageBox.Show("EventLog removed");
            }
        }
        private void InitializeComponent()
        {
            EventLogger = new EventLog();
            ((ISupportInitialize) (EventLogger)).BeginInit();

            ((ISupportInitialize) (EventLogger)).EndInit();
        }
        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();
            }
        }
示例#9
0
        private void AddWindowsEventLog(string message, EventLogEntryType logType = EventLogEntryType.Information, string moduleName = "", int codeErreur = 0, bool fromFileLogEvent = false)
        {
            EventLog evLog = new EventLog(Const.WINDOWS_LOG_NAME);

            message = string.Concat(message, "\r\n", "Module : ", moduleName);
            evLog.Source = Const.DEFAULT_APPLICATION_NAME;

            InitWindowsEventLog();

            try
            {
                evLog.WriteEntry(message, logType, codeErreur);
            }
            catch (Exception ex)
            {
                if (!fromFileLogEvent)
                {
                    AddFileEventLog("Impossible d'écrire dans le journal de log " + Log.Const.WINDOWS_LOG_NAME + ".\r\nLe journal doit être créé préalablement avec un compte Administrateur.\r\nMessage :\r\n" + message + "\r\nException : " + ex.Message, logType, moduleName, codeErreur, true);
                }
            }
            finally
            {
                evLog.Close();
            }
        }
示例#10
0
        public static EventLog CreateEventLog(string name)
        {
            string eventLogName = string.Empty;

            try
            {
                eventLogName = HostingEnvironment.ApplicationVirtualPath.Trim("/".ToCharArray());
                if (string.IsNullOrEmpty(eventLogName)) eventLogName = HostingEnvironment.SiteName;
            }
            catch
            {
                // not running under a hosted environment
            }

            if (string.IsNullOrEmpty(eventLogName)) eventLogName = name;
            if (string.IsNullOrEmpty(eventLogName)) eventLogName = "SnCore";

            if (! EventLog.SourceExists(eventLogName))
            {
                EventSourceCreationData data = new EventSourceCreationData(eventLogName, "Application");
                EventLog.CreateEventSource(data);
            }

            EventLog result  = new EventLog();
            result.Log = "Application";
            result.Source = eventLogName;
            return result;
        }
 public void CanGetCountFromEventLog()
 {
     using (EventLog eventLog = new EventLog("Application"))
     {
         Assert.IsTrue(eventLog.Entries.Count > 0);
     }
 }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            EventLog log = new EventLog("EventLog Log");
            log.Source = "LoggingApp";            
            log.WriteEntry("LoggingApp Started", EventLogEntryType.Information, 1001);

        }
示例#13
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
            {
            }
        }
示例#14
0
文件: WebQ.cs 项目: brigs/ConDep
        public WebQ(EventLog eventLog)
        {
            _eventLog = eventLog;

            Directory.CreateDirectory(DATA_FOLDER);
            Load();
        }
        /*
         * Method:  initEventLog()
         * 
         * Parameters: Void 
         * 
         * Returns: Void
         * 
         * Description: Initializes the application for logging events.
         */
        private void initEventLog()
        {
            string source = "CSVExportService";

            try
            {
                /*
                 * Create an event log source if one does not exist...
                 */
                if (!EventLog.SourceExists(source))
                {
                    EventLog.CreateEventSource(source, "Application");
                }
                else
                {
                    eventLog = new EventLog();
                    eventLog.Source = source;
                }
            }
            catch (Exception ex)
            {
                /*
                 * Do something with this exception...
                 */
            }

            return;
        }
        /// <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);
        }
示例#17
0
// <Snippet1>
    public void ShowOleDbException()
    {
        string          mySelectQuery = "SELECT column1 FROM table1";
        OleDbConnection myConnection  =
            new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DataSource=");
        OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);

        try
        {
            myCommand.Connection.Open();
        }
        catch (OleDbException e)
        {
            string errorMessages = "";

            for (int i = 0; i < e.Errors.Count; i++)
            {
                errorMessages += "Index #" + i + "\n" +
                                 "Message: " + e.Errors[i].Message + "\n" +
                                 "NativeError: " + e.Errors[i].NativeError + "\n" +
                                 "Source: " + e.Errors[i].Source + "\n" +
                                 "SQLState: " + e.Errors[i].SQLState + "\n";
            }

            System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
            log.Source = "My Application";
            log.WriteEntry(errorMessages);
            Console.WriteLine("An exception occurred. Please contact your system administrator.");
        }
    }
示例#18
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();
        }
示例#19
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);

            });
        }
        [Ignore]    // TODO remove with instrumentation
        public void LogHandlingError()
        {
            if (!EventLog.SourceExists(EventLogSource)) return;

            Exception ex = new Exception(exceptionMessage);
            ExceptionUtility.FormatExceptionHandlingExceptionMessage(policy, null, null, ex);

            StringBuilder message = new StringBuilder();
            StringWriter writer = null;
            try
            {
                writer = new StringWriter(message);
                TextExceptionFormatter formatter = new TextExceptionFormatter(writer, ex);
                formatter.Format();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }

            using (EventLog log = new EventLog(EventLogName))
            {
                EventLogEntry entry = log.Entries[log.Entries.Count - 1];

                Assert.AreEqual(EventLogEntryType.Error, entry.EntryType);
                Assert.AreEqual(EventLogSource, entry.Source);
            }
        }
示例#21
0
 public SendersManager()
 {
     new EventLogPermission(EventLogPermissionAccess.Administer, ".").Demand();
     _localLog = new EventLog("Application", ".", "el2slservice");
     _senders = new List<SyslogSender>();
     _config = new El2SlConfig();
 }
        protected override void OnStart(string[] args)
        {
            // Setup logging
            this.log = new EventLog("Application");
            if (!EventLog.SourceExists("DiskSpaceImage"))
            {
                EventLog.CreateEventSource("DiskSpaceImage", "Application");
            }
            this.log.Source = "DiskSpaceImage";

            // Log the parameters used
            this.log.WriteEntry("Image size is " + ConfigurationManager.AppSettings["ImageWidth"] + "px by " + ConfigurationManager.AppSettings["ImageHeight"] + "px", EventLogEntryType.Information);
            this.log.WriteEntry("Image style is " + ConfigurationManager.AppSettings["FontName"] + " " + ConfigurationManager.AppSettings["FontSize"] + "em " + ConfigurationManager.AppSettings["FontColour"], EventLogEntryType.Information);
            this.log.WriteEntry("Image path is " + ConfigurationManager.AppSettings["ImageName"], EventLogEntryType.Information);

            // Initialise the writer object
            this.writer = new DiskSpaceImageWriter(
                   Convert.ToInt16(ConfigurationManager.AppSettings["ImageWidth"]),
                   Convert.ToInt16(ConfigurationManager.AppSettings["ImageHeight"]),
                   ConfigurationManager.AppSettings["FontName"],
                   float.Parse(ConfigurationManager.AppSettings["FontSize"]),
                   ConfigurationManager.AppSettings["FontColour"],
                   ConfigurationManager.AppSettings["ImageName"],
                   Convert.ToBoolean(ConfigurationManager.AppSettings["ShowVolumeLabel"]));

            // Write out the image
            this.OnTimedEvent(null, null);

            // Setup a timer to fire every X milliseconds
            this.t = new Timer((Convert.ToDouble(ConfigurationManager.AppSettings["TimerInterval"])));
            this.log.WriteEntry("Refresh interval set to " + this.t.Interval + "ms", EventLogEntryType.Information);
            this.t.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            this.t.AutoReset = true;
            this.t.Start();
        }
 public TaskSchedulerManager(EventLog el)
 {
     scheduler = new TaskScheduler.TaskScheduler();
     scheduler.Connect(null, null, null, null);
     rootFolder = scheduler.GetFolder("\\");
     eventLog = el;
 }
示例#24
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();
            }
        }
示例#25
0
 void LoadServiceLog()
 {
     EventLog myLog = new EventLog();
     myLog.Log = "Application";
     foreach (EventLogEntry entry in myLog.Entries)
     {
         //EventLogEntryType枚举包括:
         //Error 错误事件。
         //FailureAudit 失败审核事件。
         //Information 信息事件。
         //SuccessAudit 成功审核事件。
         //Warning 警告事件。
         if (entry.Source == GlobalStaticObj_Server.DataServiceName || entry.Source == GlobalStaticObj_Server.FileServiceName || entry.Source == GlobalStaticObj_Server.FileTransferServiceName || entry.Source == GlobalStaticObj_Server.SessionServiceName)
         {
             if (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning || entry.EntryType == EventLogEntryType.Information)
             {
                 //result.Append("<font color='red'>" + log);
                 //result.Append(entry.EntryType.ToString() + "</font>");
                 //result.Append("<font color='blue'>(" + entry.TimeWritten.ToString() + ")</font>:");
                 //result.Append(entry.Message + "<br /><br />");
                 //txtServiceLog.AppendText("HXCSessionService" + " 发生时间:" + entry.TimeWritten.ToString() + "\r\n");
                 //txtServiceLog.AppendText(entry.Message + "\r\n");
                 SetTextBoxValue(entry.Source + " 发生时间:" + entry.TimeWritten.ToString() + "\r\n", txtServiceLog);
                 SetTextBoxValue(entry.Message + "\r\n", txtServiceLog);
             }
         }
     }
 }
    //log when item is added and removed from cache (low prority)
    private void Log(System.Diagnostics.EventLogEntryType eventLogEntryType, Uri url, string message)
    {
        string eventLog    = "WebEPRTR";
        string eventSource = "www.eprtr.ec.europa.eu";
        string infoMessage = "";

        Exception exception = Server.GetLastError();

        infoMessage  = "Message:\r\n" + message + "\r\n\r\n";
        infoMessage += "URL:\r\n" + url + "\r\n\r\n";


        //if (exception.InnerException != null)
        //    infoMessage += "InnerException:\r\n" + exception.StackTrace + "\r\n\r\n";

        // make sure the Eventlog Exists
        if (!System.Diagnostics.EventLog.SourceExists(eventSource))
        {
            System.Diagnostics.EventLog.CreateEventSource(eventSource, eventLog);
        }

        // make new log
        System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(eventLog);
        log.Source = eventSource;
        log.WriteEntry("ERROR: " + eventSource + "\r\n\r\n" + infoMessage, eventLogEntryType);
    }
        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");
        }
示例#28
0
 /// <summary>
 /// 建構子
 /// </summary>
 /// <param name="SetProcessFile">處理的檔案</param>
 /// <param name="SeteventLog1">事件檢示器物件</param>
 public ReportProcess(string SetProcessFile,
                      EventLog SeteventLog1
                      )
 {
     ProcessFile = SetProcessFile;
     eventLog1 = SeteventLog1;
 }
示例#29
0
 /// <summary>
 /// Creating an EventSource requires certain permissions, which by default a IIS AppPool user does not have.
 /// In this case just ignore security exceptions.
 /// In order to make this work, the eventsource needs to be created manually
 /// </summary>
 public Logger(string name, string source) {
   try {
     log = new EventLog();
     log.Source = source;
   }
   catch (Exception) { }
 }
        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
        }
示例#31
0
		public EventLogViewer(EventLog log_)
		{
			InitializeComponent();

			log = log_;
			gridSelectionChangedEventHandler = new EventHandler(dgEvents_SelectionChanged);
			localMachine = (log.MachineName == ".") || (log.MachineName == System.Net.Dns.GetHostName());
			this.Text = localMachine ? System.Net.Dns.GetHostName() : log.MachineName + " - [" +  log.LogDisplayName + "]";

			// Set up the grid properties for the visual event distinction
			VisualEventDistinctionType distinctionType = (VisualEventDistinctionType) System.Enum.Parse(typeof(VisualEventDistinctionType), Settings.Default.ColorMode);

			if (distinctionType == VisualEventDistinctionType.Colors)
			{
				dgEvents.RowsAdded +=new DataGridViewRowsAddedEventHandler(dgEvents_RowsAdded);

				// Remove the image column - we're only going to use colours
				dgEvents.Columns[0].Visible = false;
			}
			else
			{
				dgEvents.CellFormatting += new DataGridViewCellFormattingEventHandler(dgEvents_CellFormatting);
			}

			FillGrid();
		}		
示例#32
0
    /// <summary>
    /// 写入系统事件(在控制面板-事件查看,可以看到这些事件记录)。
    /// </summary>
    /// <param name="message">消息,也可以是带格式的文本。</param>
    /// <param name="args">如果message是一个格式串,args将参与格式。</param>
    /// <param name="logType">日志类型。</param>
    /// <param name="eventId">事件Id,有效值:1-65535。</param>
    /// <param name="category">子类Id,有效值:1-32767。</param>
    /// <param name="source">事件源,比如:测试程序。</param>
    /// <param name="logName">日志名称,一般为Application(应用程序)。</param>
    public static void WriteEventLog(string message, object[] args, System.Diagnostics.EventLogEntryType logType = System.Diagnostics.EventLogEntryType.Information, int eventId = -1, short category = -1, string source = null, string logName = "Application")
    {
        using (System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog()) {
            eventLog.Log = string.IsNullOrEmpty(logName) ? "Application" : logName;
            if (!string.IsNullOrEmpty(source))
            {
                eventLog.Source = source;
            }
            else
            {
                eventLog.Source = AppHelper.Assembly.FullName;
            }

            if (message != null && args != null && args.Length > 0)
            {
                message = string.Format(message, args);
            }
            if (eventId != -1)
            {
                if (category != -1)
                {
                    eventLog.WriteEntry(message, logType, eventId, category);
                }
                else
                {
                    eventLog.WriteEntry(message, logType, eventId);
                }
            }
            else
            {
                eventLog.WriteEntry(message, logType);
            }
        }
    }
示例#33
0
// <Snippet1>
    public void ShowOdbcException()
    {
        string         mySelectQuery = "SELECT column1 FROM table1";
        OdbcConnection myConnection  =
            new OdbcConnection("DRIVER={SQL Server};SERVER=MyServer;Trusted_connection=yes;DATABASE=northwind;");
        OdbcCommand myCommand = new OdbcCommand(mySelectQuery, myConnection);

        try
        {
            myCommand.Connection.Open();
        }
        catch (OdbcException e)
        {
            string errorMessages = "";

            for (int i = 0; i < e.Errors.Count; i++)
            {
                errorMessages += "Index #" + i + "\n" +
                                 "Message: " + e.Errors[i].Message + "\n" +
                                 "NativeError: " + e.Errors[i].NativeError.ToString() + "\n" +
                                 "Source: " + e.Errors[i].Source + "\n" +
                                 "SQL: " + e.Errors[i].SQLState + "\n";
            }

            System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
            log.Source = "My Application";
            log.WriteEntry(errorMessages);
            Console.WriteLine("An exception occurred. Please contact your system administrator.");
        }
    }
示例#34
0
    // We only want this method exposed to code
    // in the same assembly. However, we might need to
    // change the scope if this class were in another
    // assembly.

    internal void LogError()
    {
        System.Diagnostics.EventLog e;
        e        = new System.Diagnostics.EventLog("Application");
        e.Source = this.AppSource;
        e.WriteEntry(this.Message, System.Diagnostics.EventLogEntryType.Error);
        e.Dispose();
    }
示例#35
0
 //<Snippet2>
 public MyNewService()
 {
     InitializeComponent();
     eventLog1 = new System.Diagnostics.EventLog();
     if (!System.Diagnostics.EventLog.SourceExists("MySource"))
     {
         System.Diagnostics.EventLog.CreateEventSource(
             "MySource", "MyNewLog");
     }
     eventLog1.Source = "MySource";
     eventLog1.Log    = "MyNewLog";
 }
示例#36
0
	static void UnhandledExceptions(object sender, UnhandledExceptionEventArgs e)
	{		
		string source = "SOTest";
		if (!System.Diagnostics.EventLog.SourceExists(source))
		{
			System.Diagnostics.EventLog.CreateEventSource(source, "Application");
		}
		
		System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
		log.Source = source;
		log.WriteEntry(e.ExceptionObject.ToString(), System.Diagnostics.EventLogEntryType.Error);
	}
示例#37
0
    protected void _SendMailError(object sender, SendMailErrorEventArgs e)
    {
        Message1.Visible = true;
        Message1.Text    = "Could not send email to confirm password change.";

        // The MySamplesSite event source has already been created by an administrator.
        System.Diagnostics.EventLog myLog = new System.Diagnostics.EventLog();
        myLog.Source = "MySamplesSite";
        myLog.Log    = "Application";
        myLog.WriteEntry(
            "Sending mail via SMTP failed with the following error: " +
            e.Exception.Message.ToString(),
            System.Diagnostics.EventLogEntryType.Error);

        e.Handled = true;
    }
示例#38
0
 //<Snippet14>
 public UserService2()
 {
     eventLog1 = new System.Diagnostics.EventLog();
     // Turn off autologging
     //<Snippet17>
     this.AutoLog = false;
     //</Snippet17>
     // create an event source, specifying the name of a log that
     // does not currently exist to create a new, custom log
     if (!System.Diagnostics.EventLog.SourceExists("MySource"))
     {
         System.Diagnostics.EventLog.CreateEventSource(
             "MySource", "MyLog");
     }
     // configure the event log instance to use this source name
     eventLog1.Source = "MySource";
     eventLog1.Log    = "MyLog";
 }
示例#39
0
// <Snippet1>
    public void ShowOracleException()
    {
        OracleConnection myConnection =
            new OracleConnection("Data Source=Oracle8i;Integrated Security=yes");

        try
        {
            myConnection.Open();
        }
        catch (OracleException e)
        {
            string errorMessage = "Code: " + e.Code + "\n" +
                                  "Message: " + e.Message;

            System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
            log.Source = "My Application";
            log.WriteEntry(errorMessage);
            Console.WriteLine("An exception occurred. Please contact your system administrator.");
        }
    }
示例#40
0
// <Snippet1>
    public void ShowOdbcException()
    {
        string         mySelectQuery = "SELECT column1 FROM table1";
        OdbcConnection myConnection  =
            new OdbcConnection("DRIVER={SQL Server};SERVER=MyServer;Trusted_connection=yes;DATABASE=northwind;");
        OdbcCommand myCommand = new OdbcCommand(mySelectQuery, myConnection);

        try
        {
            myCommand.Connection.Open();
        }
        catch (OdbcException e)
        {
            string errorMessage = "Message: " + e.Message + "\n" +
                                  "Source: " + e.Source;

            System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
            log.Source = "My Application";
            log.WriteEntry(errorMessage);
            Console.WriteLine("An exception occurred. Please contact your system administrator.");
        }
    }
示例#41
0
        protected override void OnStart(string[] args)
        {
            try
            {
                WriteTestLog("");
                WriteTestLog("开始启动服务");
                //加载所有服务的基础类型;
                Type                     svcType     = null;
                ServiceHost              defaultHost = null;
                Configuration            conf        = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
                ServiceModelSectionGroup svcmod      = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");

                foreach (ServiceElement el in svcmod.Services.Services)
                {
                    string sSpaceName = el.Name.Remove(el.Name.LastIndexOf('.'));
                    WriteTestLog("启动服务......" + el.Name);

                    WriteTestLog("启动服务......" + el.Name + "  GetType");
                    svcType = Type.GetType(el.Name + "," + sSpaceName);
                    WriteTestLog("启动服务......" + el.Name + "  GetType OK");

                    WriteTestLog("启动服务......" + el.Name + "  GetHost");

                    defaultHost = new ServiceHost(svcType);
                    string           fullpath    = AppDomain.CurrentDomain.BaseDirectory + "hcSinri.pfx";
                    string           password    = "******";
                    X509Certificate2 certificate = new X509Certificate2(fullpath, password);
                    defaultHost.Credentials.ServiceCertificate.Certificate = certificate;

                    WriteTestLog("启动服务......" + el.Name + "  GetHost OK");


                    WriteTestLog("启动服务......" + el.Name + "  AddBehavior");
                    ServiceMetadataBehavior smb = defaultHost.Description.Behaviors.Find <ServiceMetadataBehavior>();
                    if (smb == null)
                    {
                        defaultHost.Description.Behaviors.Add(new ServiceMetadataBehavior());
                    }

                    //暴露出元数据,以便能够让SvcUtil.exe自动生成配置文件
                    defaultHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");

                    WriteTestLog("启动服务......" + el.Name + "  AddBehavior  OK");

                    WriteTestLog("启动服务......" + el.Name + "  Open");

                    if (defaultHost.State != CommunicationState.Opening)
                    {
                        defaultHost.Open();
                    }

                    WriteTestLog("启动服务......" + el.Name + "  Open  OK");
                    hosts.Add(el.Name, defaultHost);
                }
                //初始化服务端缓存数据

                WriteTestLog("启动服务......启动线程");
                thread.Start();
                WriteTestLog("启动服务......启动线程  OK");
            }
            catch (Exception e)
            {
                WriteTestLog("启动服务出错:" + e.Message);
                System.Diagnostics.EventLog evtlog = new System.Diagnostics.EventLog();
                evtlog.Log    = "Application";
                evtlog.Source = ConfigurationManager.AppSettings["ServiceName"] ?? "hcPlatWindowsServer";
                evtlog.WriteEntry(e.Message, EventLogEntryType.Error);
            }
        }
示例#42
0
        public void Execute(IJobExecutionContext context)
        {
            string fileLogPath = AppDomain.CurrentDomain.BaseDirectory + "log\\";
            string fileLogName = "TQuartz_" + DateTime.Now.ToLongDateString() + "_log.txt";

            DirectoryInfo Dir = new DirectoryInfo(fileLogPath);

            if (!Dir.Exists)
            {
                Dir.Create();
            }

            try
            {
                String FileName = fileLogPath + fileLogName;
                //FileInfo finfo = new FileInfo(FileName);

                StreamWriter strwriter = File.AppendText(FileName);
                strwriter.WriteLine("JosnJiang 的标示时间发生在: " + DateTime.Now.ToString());
                strwriter.Flush();
                strwriter.Close();
            }
            catch (Exception ex)
            {
                String Message = "发生错误:{0}";
                Message = String.Format(Message, ex.GetBaseException().Message + Environment.NewLine + ex.StackTrace);



                //寫入事件撿視器,方法一
                if (!EventLog.SourceExists("JosonJiang Applications"))
                {
                    EventLog.CreateEventSource("JosonJiang Applications", "JosonJiang");
                }
                System.Diagnostics.EventLog.WriteEntry("JosonJiang Applications", Message, System.Diagnostics.EventLogEntryType.Warning);


                Message = String.Format("{0}", ex.GetBaseException().Message);
                System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("JosonJiang");
                //  首先应判断日志来源是否存在,一个日志来源只能同时与一个事件绑定

                if (!EventLog.SourceExists("JosonJiang Application"))
                {
                    EventLog.CreateEventSource("JosonJiang Application", "JosonJiang");
                }
                try
                {
                    log.Source = "JosonJiang Application";
                    log.WriteEntry(Message, EventLogEntryType.FailureAudit);

                    //throw new System.IO.FileNotFoundException("readme.txt文件未找到");
                }
                catch (System.IO.FileNotFoundException exception)
                {
                    log.WriteEntry(exception.Message, EventLogEntryType.Error);
                }


                //FileInfo finfo = new FileInfo(fileLogPath + fileLogName);
                //using (FileStream fs = finfo.OpenWrite())
                //{
                //    //根据上面创建的文件流创建写数据流
                //    using (StreamWriter strwriter = new StreamWriter(fs))
                //    {
                //        //设置写数据流的起始位置为文件流的末尾
                //        strwriter.BaseStream.Seek(0, SeekOrigin.End);
                //        //写入相关记录信息
                //        strwriter.WriteLine("发生时间: " + ex.Message + DateTime.Now.ToString());
                //        strwriter.WriteLine("---------------------------------------------");
                //        strwriter.WriteLine();
                //        //清空缓冲区内容,并把缓冲区内容写入基础流
                //        strwriter.Flush();
                //        strwriter.Close();
                //        fs.Close();

                //    }
                //}
            }
        }
示例#43
0
        /// <summary>
        /// ITestStep.Execute() implementation
        /// </summary>
        /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
        public override void Execute(Context context)
        {
            if (DelayBeforeCheck > 0)
            {
                context.LogInfo("Waiting for {0} seconds before checking the event log.", DelayBeforeCheck);
                System.Threading.Thread.Sleep(DelayBeforeCheck * 1000);
            }

            DateTime cutOffTime = context.TestCaseStart;

            // Note: event log time is always truncated, so the cut off time also need sto be!
            cutOffTime = cutOffTime.Subtract(new TimeSpan(0, 0, 0, 0, context.TestCaseStart.Millisecond + 1));

            bool found = false;

            using (var log = new System.Diagnostics.EventLog(EventLog, Machine))
            {
                EventLogEntryCollection entries = log.Entries;

                context.LogInfo("Scanning {0} event log entries from log: '{1}' on machine: '{2}', cutOffTime: '{3}'.", entries.Count, EventLog, Machine, cutOffTime.ToString("HH:mm:ss.fff dd/MM/yyyy"));
                for (int i = entries.Count - 1; i >= 0; i--)
                {
                    EventLogEntry entry = entries[i];
                    if (0 > (DateTime.Compare(entry.TimeGenerated, cutOffTime)))
                    {
                        context.LogInfo("Scanning of event log stopped, event.TimeGenerated: {0}, cutOffTime: {1}", entry.TimeGenerated.ToString("HH:mm:ss.fff dd/MM/yyyy"), cutOffTime.ToString("HH:mm:ss.fff dd/MM/yyyy"));
                        break;
                    }

                    context.LogInfo("Checking entry, Source: {0}, EntryType: {1}, EventId: {2}", entry.Source, entry.EntryType, entry.InstanceId);

                    // Note: EventId is optional...
                    if (((entry.Source == Source) && (entry.EntryType == EntryType)) &&
                        (((EventId > 0) && (entry.InstanceId == EventId)) || (EventId == 0)))
                    {
                        foreach (string validationRegex in ValidationRegExs)
                        {
                            string matchPattern = validationRegex;
                            Match  match        = Regex.Match(entry.Message, matchPattern);

                            if (match.Success)
                            {
                                found = true;
                                context.LogInfo("Successfully matched event log entry generated at '{0}'.", entry.TimeGenerated);
                                context.LogData("Event log entry.", entry.Message);
                                break;
                            }
                        }
                    }

                    if (found)
                    {
                        break;
                    }
                }
            }

            // Check that its ok
            if (!FailIfFound && !found)
            {
                throw new ApplicationException("Failed to find expected event log entry.");
            }

            if (FailIfFound && found)
            {
                throw new ApplicationException("Found event log entry which should not be present.");
            }
        }
示例#44
0
 public WindowsEventLog(string logName, string machineName, string sourceName)
 {
     DiagnosticsEventLog = new System.Diagnostics.EventLog(logName, machineName, sourceName);
 }
示例#45
0
 public static void Error(int eventID, string text)
 {
     DiagELog.WriteEntry(SystemName, text, EventLogEntryType.Error, eventID);
 }
示例#46
0
 public static void Warning(int eventID, string text)
 {
     DiagELog.WriteEntry(SystemName, text, EventLogEntryType.Warning, eventID);
 }
        public TemplateServiceWrapper(string service, string serviceParams, string serviceExe)
        {
            try{
                eventLog1 = new System.Diagnostics.EventLog();
                ((System.ComponentModel.ISupportInitialize)(eventLog1)).BeginInit();
                eventLog1.Source = service;
                eventLog1.Log    = service + "_logs";
                ((System.ComponentModel.ISupportInitialize)(eventLog1)).EndInit();
                if (!System.Diagnostics.EventLog.SourceExists(service))
                {
                    System.Diagnostics.EventLog.CreateEventSource(service, service + "_logs");
                }

                this.CanStop             = true;
                this.CanPauseAndContinue = false;
                this.AutoLog             = true;



                serviceName     = service;
                exe             = serviceExe;
                parameterString = serviceParams;

                servScheduleTab = getDataFromStore(getServiceInformationScript.Replace("service_name_val", serviceName));
                string schID = string.IsNullOrEmpty(servScheduleTab.Rows[0]["schedule_run_id"].ToString())?"0":servScheduleTab.Rows[0]["schedule_run_id"].ToString();
                maxID = int.Parse(schID) + 1;


                if (servScheduleTab.Rows.Count > 0)
                {
                    string lastRunTime   = string.IsNullOrEmpty(servScheduleTab.Rows[0]["schedule_last_run_time"].ToString())?DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt"):servScheduleTab.Rows[0]["schedule_last_run_time"].ToString();
                    string nextRunTime   = string.IsNullOrEmpty(servScheduleTab.Rows[0]["schedule_next_run_time"].ToString())?servScheduleTab.Rows[0]["start_time"].ToString():servScheduleTab.Rows[0]["schedule_next_run_time"].ToString();
                    string repeatType    = "";
                    string frequencyType = "";
                    string frequencyText = "";
                    string repeatText    = "";
                    currentDateTime = DateTime.Now;
                    lastRunDateTime = lastRunTime.Contains("/")? Convert.ToDateTime(reformatDate(lastRunTime)):Convert.ToDateTime(reformatDate(lastRunTime));
                    nextRunDateTime = nextRunTime.Contains("/")? Convert.ToDateTime(reformatDate(nextRunTime)):Convert.ToDateTime(reformatDate(nextRunTime));
                    expectedRunTime = DateTime.Now;



                    foreach (DataRow row in servScheduleTab.Rows)
                    {
                        if (!string.IsNullOrEmpty(row["repeat_type"].ToString()) && row["repeat_type"].ToString() != "DISABLED")
                        {
                            repeatType    = row["repeat_type"].ToString();
                            repeatText    = string.IsNullOrEmpty(row["repeat_every"].ToString())?"0":row["repeat_every"].ToString();
                            lastRunTime   = string.IsNullOrEmpty(row["schedule_last_run_time"].ToString())?DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt"):row["schedule_last_run_time"].ToString();
                            nextRunTime   = string.IsNullOrEmpty(row["schedule_next_run_time"].ToString())?row["start_time"].ToString():row["schedule_next_run_time"].ToString();
                            frequencyText = string.IsNullOrEmpty(row["frequency"].ToString())?"0":row["frequency"].ToString();
                            frequencyType = row["frequency_type"].ToString();
                            int repeat = int.Parse(repeatText.Trim());
                            lastRunDateTime = lastRunTime.Contains("/")? Convert.ToDateTime(reformatDate(lastRunTime)):Convert.ToDateTime(reformatDate(lastRunTime));
                            nextRunDateTime = nextRunTime.Contains("/")? Convert.ToDateTime(reformatDate(nextRunTime)):Convert.ToDateTime(reformatDate(nextRunTime));
                            delay           = 0;
                            expectedRunTime = DateTime.Now;

                            if (string.IsNullOrEmpty(nextRunTime))
                            {
                                if (repeatType == "hour(s)")
                                {
                                    TimeSpan time = new TimeSpan(repeat, 0, 0);
                                    expectedRunTime = lastRunDateTime.Add(time);
                                    interval        = repeat * 60 * 60;
                                }
                                else if (repeatType == "minutes(s)")
                                {
                                    TimeSpan time = new TimeSpan(0, repeat, 0);
                                    expectedRunTime = lastRunDateTime.Add(time);
                                    interval        = repeat * 60;
                                }
                                else if (repeatType == "second(s)")
                                {
                                    TimeSpan time = new TimeSpan(0, 0, repeat);
                                    expectedRunTime = lastRunDateTime.Add(time);
                                    interval        = repeat;
                                }
                                writeToLog("expectedRunTime: " + expectedRunTime.ToString());
                                writeToLog("currentDateTime: " + currentDateTime.ToString());


                                if (currentDateTime > expectedRunTime)
                                {
                                    expectedRunTime = currentDateTime;
                                }
                                delay = (int)Math.Ceiling(decimal.Parse(expectedRunTime.Subtract(currentDateTime).TotalSeconds.ToString().Trim()));
                                writeToLog("delay: " + delay);
                            }
                            else
                            {
                                if (repeatType == "hour(s)")
                                {
                                    interval = repeat * 60 * 60;
                                }
                                else if (repeatType == "minutes(s)")
                                {
                                    interval = repeat * 60;
                                }
                                else if (repeatType == "second(s)")
                                {
                                    interval = repeat;
                                }

                                writeToLog("1. nextRunDateTime: " + nextRunDateTime.ToString());
                                writeToLog("2. currentDateTime: " + currentDateTime.ToString());

                                if (currentDateTime > nextRunDateTime)
                                {
                                    nextRunDateTime = currentDateTime;
                                }
                                writeToLog("Time Diff: " + nextRunDateTime.Subtract(currentDateTime).TotalSeconds.ToString().Trim());
                                delay = (int)Math.Ceiling(decimal.Parse(nextRunDateTime.Subtract(currentDateTime).TotalSeconds.ToString().Trim()));
                                writeToLog("delay: " + delay);
                            }
                        }
                        else if (!string.IsNullOrEmpty(row["frequency_type"].ToString()) && row["frequency_type"].ToString() != "DISABLED")
                        {
                            frequencyText = row["frequency"].ToString();
                            frequencyType = row["frequency_type"].ToString();
                            lastRunTime   = row["schedule_last_run_time"].ToString();
                            nextRunTime   = row["schedule_next_run_time"].ToString();


                            if (frequencyType == "daily")
                            {
                                interval = 24 * 60 * 60 / Int32.Parse(frequencyText);
                            }
                            else if (frequencyType == "weekly")
                            {
                                interval = 7 * 24 * 60 * 60 / Int32.Parse(frequencyText);
                            }
                            else if (frequencyType == "monthly")
                            {
                                interval = 30 * 24 * 60 * 60 / Int32.Parse(frequencyText);
                            }
                            else if (frequencyType == "yearly")
                            {
                                interval = 365 * 24 * 60 * 60 / Int32.Parse(frequencyText);
                            }

                            if (string.IsNullOrEmpty(nextRunTime))
                            {
                                delay = 0;
                            }
                            else
                            {
                                if (currentDateTime > nextRunDateTime)
                                {
                                    nextRunDateTime = currentDateTime;
                                }

                                delay = (int)Math.Ceiling(decimal.Parse(nextRunDateTime.Subtract(currentDateTime).TotalSeconds.ToString().Trim()));
                            }
                        }
                        else
                        {
                            writeToLog("Could not find a schedule for service: " + serviceName);
                        }
                    }

                    this.Start();
                }
            }catch (Exception e) {
                writeToLog(e.Message);
                writeToLog(e.StackTrace);
            }
        }
示例#48
0
        static void Main()
        {
            //Add by FJ for fix the USB reconnection failuer issue in Windows 10, 2016-08-19
            foreach (REGISTRY_MODULE_INFO device in Enum.GetValues(typeof(REGISTRY_MODULE_INFO)))
            {
                string      RegKeyPath = "SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_24E9&" + device + "\\000000000\\Device Parameters";
                RegistryKey Result     = Registry.LocalMachine.OpenSubKey(RegKeyPath);
                if (Result != null)
                {
                    string Regvalue = (string)Convert.ChangeType(Result.GetValue("EnhancedPowerManagementEnabled", null), typeof(string));
                    if (Regvalue != null)
                    {
                        Process p = new Process();
                        p.StartInfo.FileName  = "cmd.exe";
                        p.StartInfo.Arguments = "/c reg delete \"HKEY_LOCAL_MACHINE\\" + RegKeyPath + "\" /v \"EnhancedPowerManagementEnabled\" /f";
                        p.Start();
                        MessageBox.Show("Please replug the USB cable.");
                        return;
                    }
                }
            }
            //End by FJ for fix the USB reconnection failuer issue in Windows 10, 2016-08-19


            if (true == isOpen())
            {
                MessageBox.Show("Already Opened");
                return;
            }


            System.Threading.Thread.CurrentThread.Name = "MainGUIThread";
            System.Diagnostics.Debug.WriteLine(String.Format("{0} is threadID {1}", System.Threading.Thread.CurrentThread.Name, System.Threading.Thread.CurrentThread.ManagedThreadId));
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            try
            {
                string dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                string name     = RFID_Explorer.Properties.Settings.Default.macErrorsFileName;
                string fileName = Path.Combine(dir, name);
                if (!System.IO.File.Exists(fileName))
                {
                    throw new Exception(String.Format("A critial configuration file ({0}) is missing.", fileName));
                }

                Application.Run(new mainForm());
            }
            catch (TypeInitializationException exp)
            {
                MessageBox.Show(exp.Message);
                System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application", ".", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
                log.WriteEntry(FormatEventMessage(exp), System.Diagnostics.EventLogEntryType.Error, 1);
                if (exp.InnerException != null)
                {
                    log.WriteEntry(FormatEventMessage(exp.InnerException), System.Diagnostics.EventLogEntryType.Error, 2);
                }
            }
            catch (RFID.RFIDInterface.rfidException rfid)
            {
                System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application", ".", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
                try
                {
                    log.WriteEntry(rfid.Message, System.Diagnostics.EventLogEntryType.Error, (int)rfid.ErrorCode.ErrorCode);
                }
                catch (Exception)       {       }
            }
            catch (System.ComponentModel.Win32Exception win32)
            {
                switch (win32.NativeErrorCode)
                {
                // no point in trying to write the log
                case ERROR_EVENTLOG_FILE_CORRUPT:
                case ERROR_EVENTLOG_CANT_START:
                case ERROR_LOG_FILE_FULL:
                    MessageBox.Show("Unable to write to Application Log.\n\n" + win32.Message);
                    break;

                default:

                    try
                    {
                        System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application", ".", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
                        log.WriteEntry(win32.Message, System.Diagnostics.EventLogEntryType.Error, 1);
                    }
                    catch (Exception)       {       }
                    break;
                }
            }
            catch (Exception e)
            {
                try
                {
                    System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application", ".", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
                    log.WriteEntry(e.Message, System.Diagnostics.EventLogEntryType.Error, 1);

                    MessageBox.Show(e.Message);
                }
                catch (Exception)
                {
                    MessageBox.Show("Unable to write to Application Log.\n\n" + e.Message);
                }

                throw;
            }
        }
示例#49
0
 public static void Error(int eventID, string text)
 {
     DiagELog.WriteEntry("ServUO", text, EventLogEntryType.Error, eventID);
 }
示例#50
0
 public static void Warning(int eventID, string text)
 {
     DiagELog.WriteEntry("ServUO", text, EventLogEntryType.Warning, eventID);
 }
示例#51
0
 public static void Inform(int eventID, string text)
 {
     DiagELog.WriteEntry("ServUO", text, EventLogEntryType.Information, eventID);
 }
示例#52
0
 public Item(System.Diagnostics.EventLog l)
 {
     DisplayName = l.LogDisplayName;
     Name        = l.Log;
 }
示例#53
0
        protected override bool InitializeServer(RunFrame frame)
        {
            string baseAddress;
            string port;

            var sandbox = CreateFullTrustAppDomain();

            frame.SetState(KeySandbox, sandbox);

            // load test assemly into sandbox
            if (sandbox != null && TypeDescriptor.TestAssembly != null)
            {
                sandbox.Load(TypeDescriptor.TestAssembly.GetName());
            }

            // setup security strategy and base address
            port = _portArranger.Reserve();
            SecurityHelper.AddIpListen();
            SecurityOptionElement securityElem = frame.GetFirstElement <SecurityOptionElement>();

            if (securityElem != null)
            {
                SetupSecureEnvironment(securityElem.Certificate, port);
                baseAddress = string.Format(SecureBaseAddressTemplate, Environment.MachineName, port);
                frame.SetState(KeyIsSecuredServer, true);
            }
            else
            {
                baseAddress = string.Format(NormalBaseAddressTemplate, Environment.MachineName, port);
                frame.SetState(KeyIsSecuredServer, false);
            }

            // looking into the RunFrames and search for TraceElement. if it exists
            // set the tracer's type to the configuration otherwise skip this step
            TraceElement traceElem = frame.GetFirstElement <TraceElement>();
            Type         traceType = null;

            if (traceElem != null)
            {
                traceType = traceElem.TracerType;
            }

            // create initiator in the sandbox
            KatanaSelfHostServerInitiator serverInitiator;

            if (sandbox != null)
            {
                serverInitiator = sandbox.CreateInstanceAndUnwrap(
                    typeof(KatanaSelfHostServerInitiator).Assembly.FullName,
                    typeof(KatanaSelfHostServerInitiator).FullName)
                                  as KatanaSelfHostServerInitiator;
            }
            else
            {
                serverInitiator = new KatanaSelfHostServerInitiator();
            }
            try
            {
                // set up the server
                serverInitiator.Setup(
                    baseAddress,
                    TypeDescriptor.GetDesignatedMethod <NuwaKatanaConfigurationAttribute>(),
                    TypeDescriptor.ConfigureMethod,
                    traceType, GetDefaultRouteTemplate());
            }
            catch (Exception ex)
            {
                EventLog appLog = new System.Diagnostics.EventLog();
                appLog.Source = "Nuwa Katana Self Host Test";
                appLog.WriteEntry(string.Format("base address: {0}\n message: {1}\n stack trace: {2}\n", baseAddress, ex.Message, ex.StackTrace),
                                  EventLogEntryType.Error);
                throw ex;
            }
            frame.SetState(KeyReservedPort, port);
            frame.SetState(KeyBaseAddresss, baseAddress);
            frame.SetState(KeyServerInitiator, serverInitiator);

            return(true);
        }
示例#54
0
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     this.components = new System.ComponentModel.Container();
     System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PortScanner));
     this.notifyIcon1         = new System.Windows.Forms.NotifyIcon(this.components);
     this.contextMenu1        = new System.Windows.Forms.ContextMenu();
     this.mi_Restore          = new System.Windows.Forms.MenuItem();
     this.mi_Quit             = new System.Windows.Forms.MenuItem();
     this.mainMenu1           = new System.Windows.Forms.MainMenu();
     this.mi_LogFile          = new System.Windows.Forms.MenuItem();
     this.mi_NewFile          = new System.Windows.Forms.MenuItem();
     this.mi_LoadFile         = new System.Windows.Forms.MenuItem();
     this.mi_PortScannerExit  = new System.Windows.Forms.MenuItem();
     this.menuItem5           = new System.Windows.Forms.MenuItem();
     this.mi_PortScannerStart = new System.Windows.Forms.MenuItem();
     this.mi_PortScannerStop  = new System.Windows.Forms.MenuItem();
     this.mi_Log                 = new System.Windows.Forms.MenuItem();
     this.mi_LogRefresh          = new System.Windows.Forms.MenuItem();
     this.mi_LogDeleteLog        = new System.Windows.Forms.MenuItem();
     this.mi_PortScannerSettings = new System.Windows.Forms.MenuItem();
     this.mi_MailService         = new System.Windows.Forms.MenuItem();
     this.mi_MailServiceStart    = new System.Windows.Forms.MenuItem();
     this.mi_MailServiceStop     = new System.Windows.Forms.MenuItem();
     this.imageList1             = new System.Windows.Forms.ImageList(this.components);
     this.serviceController1     = new System.ServiceProcess.ServiceController();
     this.imageList2             = new System.Windows.Forms.ImageList(this.components);
     this.panelMain              = new System.Windows.Forms.Panel();
     this.splitter1              = new System.Windows.Forms.Splitter();
     this.panelBottom            = new System.Windows.Forms.Panel();
     this.listViewPorts          = new System.Windows.Forms.ListView();
     this.Type            = new System.Windows.Forms.ColumnHeader();
     this.Index           = new System.Windows.Forms.ColumnHeader();
     this.Date            = new System.Windows.Forms.ColumnHeader();
     this.Time            = new System.Windows.Forms.ColumnHeader();
     this.PScannedHost    = new System.Windows.Forms.ColumnHeader();
     this.HostPort        = new System.Windows.Forms.ColumnHeader();
     this.Message         = new System.Windows.Forms.ColumnHeader();
     this.panelTop        = new System.Windows.Forms.Panel();
     this.listViewMails   = new System.Windows.Forms.ListView();
     this.mType           = new System.Windows.Forms.ColumnHeader();
     this.mIndex          = new System.Windows.Forms.ColumnHeader();
     this.mDate           = new System.Windows.Forms.ColumnHeader();
     this.mTime           = new System.Windows.Forms.ColumnHeader();
     this.ScannedHost     = new System.Windows.Forms.ColumnHeader();
     this.mMessage        = new System.Windows.Forms.ColumnHeader();
     this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
     this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
     this.eventLog1       = new System.Diagnostics.EventLog();
     this.panelMain.SuspendLayout();
     this.panelBottom.SuspendLayout();
     this.panelTop.SuspendLayout();
     ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
     this.SuspendLayout();
     //
     // notifyIcon1
     //
     this.notifyIcon1.ContextMenu = this.contextMenu1;
     this.notifyIcon1.Icon        = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
     this.notifyIcon1.Text        = "Port Scanner";
     this.notifyIcon1.Visible     = true;
     this.notifyIcon1.Click      += new System.EventHandler(this.notifyIcon1_Click);
     //
     // contextMenu1
     //
     this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
         this.mi_Restore,
         this.mi_Quit
     });
     //
     // mi_Restore
     //
     this.mi_Restore.Index  = 0;
     this.mi_Restore.Text   = "Restore";
     this.mi_Restore.Click += new System.EventHandler(this.mi_Restore_Click);
     //
     // mi_Quit
     //
     this.mi_Quit.Index  = 1;
     this.mi_Quit.Text   = "Quit";
     this.mi_Quit.Click += new System.EventHandler(this.mi_Quit_Click);
     //
     // mainMenu1
     //
     this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
         this.mi_LogFile,
         this.menuItem5,
         this.mi_Log,
         this.mi_PortScannerSettings,
         this.mi_MailService
     });
     //
     // mi_LogFile
     //
     this.mi_LogFile.Index = 0;
     this.mi_LogFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
         this.mi_NewFile,
         this.mi_LoadFile,
         this.mi_PortScannerExit
     });
     this.mi_LogFile.Text = "File";
     //
     // mi_NewFile
     //
     this.mi_NewFile.Index  = 0;
     this.mi_NewFile.Text   = "New";
     this.mi_NewFile.Click += new System.EventHandler(this.mi_NewFile_Click);
     //
     // mi_LoadFile
     //
     this.mi_LoadFile.Index  = 1;
     this.mi_LoadFile.Text   = "Load";
     this.mi_LoadFile.Click += new System.EventHandler(this.mi_LoadFile_Click);
     //
     // mi_PortScannerExit
     //
     this.mi_PortScannerExit.Index  = 2;
     this.mi_PortScannerExit.Text   = "Exit";
     this.mi_PortScannerExit.Click += new System.EventHandler(this.mi_PortScannerExit_Click);
     //
     // menuItem5
     //
     this.menuItem5.Index = 1;
     this.menuItem5.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
         this.mi_PortScannerStart,
         this.mi_PortScannerStop
     });
     this.menuItem5.Text = "Scan";
     //
     // mi_PortScannerStart
     //
     this.mi_PortScannerStart.Index  = 0;
     this.mi_PortScannerStart.Text   = "Start";
     this.mi_PortScannerStart.Click += new System.EventHandler(this.mi_PortScannerStart_Click);
     //
     // mi_PortScannerStop
     //
     this.mi_PortScannerStop.Index  = 1;
     this.mi_PortScannerStop.Text   = "Stop";
     this.mi_PortScannerStop.Click += new System.EventHandler(this.mi_PortScannerStop_Click);
     //
     // mi_Log
     //
     this.mi_Log.Index = 2;
     this.mi_Log.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
         this.mi_LogRefresh,
         this.mi_LogDeleteLog
     });
     this.mi_Log.Text = "Log";
     //
     // mi_LogRefresh
     //
     this.mi_LogRefresh.Index  = 0;
     this.mi_LogRefresh.Text   = "Refresh";
     this.mi_LogRefresh.Click += new System.EventHandler(this.mi_LogRefresh_Click);
     //
     // mi_LogDeleteLog
     //
     this.mi_LogDeleteLog.Index  = 1;
     this.mi_LogDeleteLog.Text   = "Delete";
     this.mi_LogDeleteLog.Click += new System.EventHandler(this.mi_LogDeleteLog_Click);
     //
     // mi_PortScannerSettings
     //
     this.mi_PortScannerSettings.Index  = 3;
     this.mi_PortScannerSettings.Text   = "Settings";
     this.mi_PortScannerSettings.Click += new System.EventHandler(this.mi_PortScannerSettings_Click);
     //
     // mi_MailService
     //
     this.mi_MailService.Index = 4;
     this.mi_MailService.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
         this.mi_MailServiceStart,
         this.mi_MailServiceStop
     });
     this.mi_MailService.Text = "Mail Service (SMTP)";
     //
     // mi_MailServiceStart
     //
     this.mi_MailServiceStart.Index  = 0;
     this.mi_MailServiceStart.Text   = "Start";
     this.mi_MailServiceStart.Click += new System.EventHandler(this.mi_MailServiceStart_Click);
     //
     // mi_MailServiceStop
     //
     this.mi_MailServiceStop.Index  = 1;
     this.mi_MailServiceStop.Text   = "Stop";
     this.mi_MailServiceStop.Click += new System.EventHandler(this.mi_MailServiceStop_Click);
     //
     // imageList1
     //
     this.imageList1.ImageSize        = new System.Drawing.Size(16, 16);
     this.imageList1.ImageStream      = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
     this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
     //
     // serviceController1
     //
     this.serviceController1.MachineName = "hakki";
     this.serviceController1.ServiceName = "SMTPSVC";
     //
     // imageList2
     //
     this.imageList2.ImageSize        = new System.Drawing.Size(16, 16);
     this.imageList2.ImageStream      = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList2.ImageStream")));
     this.imageList2.TransparentColor = System.Drawing.Color.Silver;
     //
     // panelMain
     //
     this.panelMain.Controls.Add(this.splitter1);
     this.panelMain.Controls.Add(this.panelBottom);
     this.panelMain.Controls.Add(this.panelTop);
     this.panelMain.Dock     = System.Windows.Forms.DockStyle.Fill;
     this.panelMain.Location = new System.Drawing.Point(0, 0);
     this.panelMain.Name     = "panelMain";
     this.panelMain.Size     = new System.Drawing.Size(600, 401);
     this.panelMain.TabIndex = 0;
     //
     // splitter1
     //
     this.splitter1.Dock     = System.Windows.Forms.DockStyle.Top;
     this.splitter1.Location = new System.Drawing.Point(0, 200);
     this.splitter1.Name     = "splitter1";
     this.splitter1.Size     = new System.Drawing.Size(600, 2);
     this.splitter1.TabIndex = 7;
     this.splitter1.TabStop  = false;
     //
     // panelBottom
     //
     this.panelBottom.Controls.Add(this.listViewPorts);
     this.panelBottom.Dock     = System.Windows.Forms.DockStyle.Fill;
     this.panelBottom.Location = new System.Drawing.Point(0, 200);
     this.panelBottom.Name     = "panelBottom";
     this.panelBottom.Size     = new System.Drawing.Size(600, 201);
     this.panelBottom.TabIndex = 2;
     //
     // listViewPorts
     //
     this.listViewPorts.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
         this.Type,
         this.Index,
         this.Date,
         this.Time,
         this.PScannedHost,
         this.HostPort,
         this.Message
     });
     this.listViewPorts.Dock           = System.Windows.Forms.DockStyle.Fill;
     this.listViewPorts.FullRowSelect  = true;
     this.listViewPorts.GridLines      = true;
     this.listViewPorts.Location       = new System.Drawing.Point(0, 0);
     this.listViewPorts.Name           = "listViewPorts";
     this.listViewPorts.Size           = new System.Drawing.Size(600, 201);
     this.listViewPorts.SmallImageList = this.imageList1;
     this.listViewPorts.TabIndex       = 0;
     this.listViewPorts.View           = System.Windows.Forms.View.Details;
     this.listViewPorts.DoubleClick   += new System.EventHandler(this.listViewPorts_DoubleClick_1);
     this.listViewPorts.ColumnClick   += new System.Windows.Forms.ColumnClickEventHandler(this.listViewPorts_ColumnClick);
     //
     // Type
     //
     this.Type.Text  = "Type";
     this.Type.Width = 120;
     //
     // Index
     //
     this.Index.Text  = "Index";
     this.Index.Width = 42;
     //
     // Date
     //
     this.Date.Text  = "Date";
     this.Date.Width = 75;
     //
     // Time
     //
     this.Time.Text  = "Time";
     this.Time.Width = 75;
     //
     // PScannedHost
     //
     this.PScannedHost.Text  = "Host";
     this.PScannedHost.Width = 100;
     //
     // HostPort
     //
     this.HostPort.Text  = "Port";
     this.HostPort.Width = 120;
     //
     // Message
     //
     this.Message.Text  = "Message";
     this.Message.Width = 200;
     //
     // panelTop
     //
     this.panelTop.BackColor = System.Drawing.SystemColors.ControlLight;
     this.panelTop.Controls.Add(this.listViewMails);
     this.panelTop.Dock     = System.Windows.Forms.DockStyle.Top;
     this.panelTop.Location = new System.Drawing.Point(0, 0);
     this.panelTop.Name     = "panelTop";
     this.panelTop.Size     = new System.Drawing.Size(600, 200);
     this.panelTop.TabIndex = 6;
     //
     // listViewMails
     //
     this.listViewMails.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
         this.mType,
         this.mIndex,
         this.mDate,
         this.mTime,
         this.ScannedHost,
         this.mMessage
     });
     this.listViewMails.Dock           = System.Windows.Forms.DockStyle.Fill;
     this.listViewMails.FullRowSelect  = true;
     this.listViewMails.GridLines      = true;
     this.listViewMails.Location       = new System.Drawing.Point(0, 0);
     this.listViewMails.Name           = "listViewMails";
     this.listViewMails.Size           = new System.Drawing.Size(600, 200);
     this.listViewMails.SmallImageList = this.imageList1;
     this.listViewMails.TabIndex       = 0;
     this.listViewMails.View           = System.Windows.Forms.View.Details;
     this.listViewMails.DoubleClick   += new System.EventHandler(this.listViewMails_DoubleClick);
     this.listViewMails.ColumnClick   += new System.Windows.Forms.ColumnClickEventHandler(this.listViewMails_ColumnClick);
     //
     // mType
     //
     this.mType.Text  = "Type";
     this.mType.Width = 75;
     //
     // mIndex
     //
     this.mIndex.Text  = "Index";
     this.mIndex.Width = 40;
     //
     // mDate
     //
     this.mDate.Text  = "Date";
     this.mDate.Width = 75;
     //
     // mTime
     //
     this.mTime.Text  = "Time";
     this.mTime.Width = 75;
     //
     // ScannedHost
     //
     this.ScannedHost.Text  = "Scanned Host";
     this.ScannedHost.Width = 120;
     //
     // mMessage
     //
     this.mMessage.Text  = "Not Responding Ports";
     this.mMessage.Width = 200;
     //
     // eventLog1
     //
     this.eventLog1.SynchronizingObject = this;
     //
     // PortScanner
     //
     this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
     this.BackColor         = System.Drawing.SystemColors.ControlLight;
     this.ClientSize        = new System.Drawing.Size(600, 401);
     this.Controls.Add(this.panelMain);
     this.Menu          = this.mainMenu1;
     this.Name          = "PortScanner";
     this.ShowInTaskbar = false;
     this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
     this.Text          = "Port Scanner Utility";
     this.Load         += new System.EventHandler(this.Form1_Load);
     this.panelMain.ResumeLayout(false);
     this.panelBottom.ResumeLayout(false);
     this.panelTop.ResumeLayout(false);
     ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
     this.ResumeLayout(false);
 }
示例#55
0
        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            DialogResult result = DialogResult.Cancel;

            System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application", ".", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
            RFID.RFIDInterface.rfidLogErrorException logError = e.Exception as RFID.RFIDInterface.rfidLogErrorException;
            if (logError == null)
            {
                RFID.RFIDInterface.rfidException rfid = e.Exception as RFID.RFIDInterface.rfidException;
                if (rfid == null)
                {
                    log.WriteEntry(FormatEventMessage(e.Exception), System.Diagnostics.EventLogEntryType.Error);
                }
                else
                {
                    log.WriteEntry(FormatEventMessage(rfid), System.Diagnostics.EventLogEntryType.Error, (int)rfid.ErrorCode.ErrorCode);
                }
            }
            else
            {
                if (!logError.HasBeenLogged)
                {
                    RFID.RFIDInterface.rfidException rfid = logError.InnerException as RFID.RFIDInterface.rfidException;
                    if (rfid == null)
                    {
                        log.WriteEntry(FormatEventMessage(logError.InnerException), System.Diagnostics.EventLogEntryType.Error);
                    }
                    else
                    {
                        log.WriteEntry(FormatEventMessage(rfid), System.Diagnostics.EventLogEntryType.Error, (int)rfid.ErrorCode.ErrorCode);
                    }
                }
                Application.Exit();
            }

            try
            {
                result = ShowThreadExceptionDialog(e.Exception);
            }
            catch
            {
                try
                {
                    MessageBox.Show("Fatal Error", "Fatal Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
                }
                finally
                {
                    Application.Exit();
                }
            }
            // Exits the program when the user clicks Abort.
            if (result == DialogResult.Abort)
            {
                try
                {
                    Application.Exit();
                }
                catch
                {
                    Application.Exit();
                }
                finally
                {
                    Application.Exit();
                }
            }
        }
示例#56
0
 public static void setEventLogger(EventLog eventlog)
 {
     evt = eventlog;
 }
示例#57
0
        // End File Copy Ops -------------------------

        // File Sync Ops -----------------------------
        public static int syncFiles(string fSource, string fDestiny, string[] files, int act)
        {
            int    result    = 0;
            string direction = "";

            try
            {
                switch (act)
                {
                case 0:
                    foreach (string file in files)
                    {
                        System.IO.FileInfo currentSourceFile  = new System.IO.FileInfo(Path.Combine(fSource, file));
                        System.IO.FileInfo currentDestinyFile = new System.IO.FileInfo(Path.Combine(fDestiny, file));
                        if (currentSourceFile.LastWriteTime > currentDestinyFile.LastWriteTime)
                        {
                            //Console.WriteLine("Source > Destiny " + currentSourceFile + " " + currentDestinyFile);
                            //System.IO.File.Delete(currentDestinyFile.FullName);
                            System.IO.File.Copy(currentSourceFile.FullName, currentDestinyFile.FullName, true);
                            //FMove(currentSourceFile.FullName, currentDestinyFile.FullName);
                            direction = "Source: " + currentSourceFile + " > Destiny: " + currentDestinyFile;
                            result    = 1;
                        }
                        else
                        {
                            if (currentSourceFile.LastWriteTime < currentDestinyFile.LastWriteTime)
                            {
                                //Console.WriteLine("Destiny > Source" + currentDestinyFile + " " + currentSourceFile);
                                //System.IO.File.Delete(currentSourceFile.FullName);
                                System.IO.File.Copy(currentDestinyFile.FullName, currentSourceFile.FullName, true);
                                //FMove(currentDestinyFile.FullName, currentSourceFile.FullName);
                                result    = 2;
                                direction = "Destiny: " + currentSourceFile + " > Source: " + currentDestinyFile;
                            }
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
                appLog.Source = "dLibSystemOps - syncFiles";
                appLog.Log    = ex.Message;
                appLog.WriteEntry("syncFiles \n\n" +
                                  "General Failure syncing Lotus Notes DATA " +
                                  "Direction: " + direction +
                                  "\n\nMessage: " + ex.Message +
                                  "\n\nSource: " + ex.Source +
                                  "\n\nStack: " + ex.StackTrace +
                                  "\n\nTarget: " + ex.TargetSite, EventLogEntryType.FailureAudit, 3012, 02);


                MessageBox.Show("dLibSystemOps - syncFiles \n\n" +
                                "General Failure syncing Lotus Notes DATA " +
                                "\n\nMessage: " + ex.Message +
                                "\n\nSource: " + ex.Source +
                                "\n\nStack: " + ex.StackTrace +
                                "\n\nTarget: " + ex.TargetSite, "Information: Exception", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
            }
            return(result);
        }
示例#58
0
        /// <summary>
        /// Construct a sink posting to the Windows event log, creating the specified <paramref name="source"/> if it does not exist.
        /// </summary>
        /// <param name="source">The source name by which the application is registered on the local computer. </param>
        /// <param name="logName">The name of the log the source's entries are written to. Possible values include Application, System, or a custom event log.</param>
        /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param>
        /// <param name="machineName">The name of the machine hosting the event log written to.</param>
        /// <param name="manageEventSource">If false does not check/create event source.  Defaults to true i.e. allow sink to manage event source creation</param>
        public EventLogSink(string source, string logName, ITextFormatter textFormatter, string machineName,
                            bool manageEventSource)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (textFormatter == null)
            {
                throw new ArgumentNullException(nameof(textFormatter));
            }

            //The source is limitted in length and allowed chars
            //see: https://msdn.microsoft.com/en-us/library/e29k5ebc%28v=vs.110%29.aspx
            source = source.Substring(0, Math.Min(source.Length, 212));
            source = source.Replace("<", "_");
            source = source.Replace(">", "_");

            _textFormatter = textFormatter;
            _logName       = logName;

            if (string.IsNullOrWhiteSpace(_logName))
            {
                _logName = APPLICATION_LOG;
            }

            _log = new System.Diagnostics.EventLog(_logName);

            if (manageEventSource)
            {
                var sourceData = new EventSourceCreationData(source, _logName)
                {
                    MachineName = machineName
                };
                Action logSourceMoved = () => { };

                var sourceExistsInAnyLog = System.Diagnostics.EventLog.SourceExists(source, machineName);
                if (sourceExistsInAnyLog)
                {
                    var existingLogWithSourceName = System.Diagnostics.EventLog.LogNameFromSourceName(source, machineName);

                    if (!string.IsNullOrWhiteSpace(existingLogWithSourceName))
                    {
                        //remove it from previous log so we can associated it with the current logName
                        System.Diagnostics.EventLog.DeleteEventSource(source, machineName);

                        //stash a reference to this guy so we can add a log entry noting the logs your looking for are in the
                        //log previously associated with "source"
                        //we don't log here in case creating the event source fails (if the create failed, an entry here would be misleading)
                        logSourceMoved = () =>
                        {
                            var metaSource = $"serilog-{_logName}";
                            if (!System.Diagnostics.EventLog.SourceExists(metaSource, machineName))
                            {
                                System.Diagnostics.EventLog.CreateEventSource(new EventSourceCreationData(metaSource,
                                                                                                          _logName)
                                {
                                    MachineName = machineName
                                });
                            }

                            _log.Source = metaSource;
                            _log.WriteEntry(
                                message:
                                $"Event source {source} was previously registered in log {existingLogWithSourceName}. " +
                                $"The source has been registered with this log, {_logName}, however a computer restart may be required " +
                                $"before event logs will appear in {_logName} with source {source}. Until then, messages may be logged to {existingLogWithSourceName}.",
                                type: EventLogEntryType.Warning,
                                eventID: (int)LogEventLevel.Warning);
                        };
                    }
                }
                else
                {
                    System.Diagnostics.EventLog.CreateEventSource(sourceData);
                }

                logSourceMoved();
            }

            _log.Source = source;
        }
示例#59
0
 public NullEventLog(EventLog coreEventLog)
     : base(coreEventLog)
 {
 }
        // 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();
                }
            }
        }