protected void createEventLogSource_Click(object sender, EventArgs e)
        {
            try
            {
                EventSourceCreationData creationData = new EventSourceCreationData(_Source, _LogName);
                if (EventLog.Exists(_LogName, ".") == false)
                {
                    //source未在该服务器上注册过
                    EventLog.CreateEventSource(creationData);
                    createMessage.InnerText = "没有Log,创建Log和Source";
                }
                else
                {
                    if (EventLog.SourceExists(_Source))
                    {
                        string originalLogName = EventLog.LogNameFromSourceName(_Source, ".");

                        //source注册的日志名称和指定的logName不一致,且不等于source自身
                        //(事件日志源“System”等于日志名称,不能删除。[System.InvalidOperationException])
                        if (string.Compare(_LogName, originalLogName, true) != 0 && string.Compare(_Source, originalLogName, true) != 0)
                        {
                            //删除现有的关联重新注册
                            EventLog.DeleteEventSource(_Source, ".");
                            EventLog.CreateEventSource(creationData);

                            createMessage.InnerText = "已经有Log,重新创建Log和Source";
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                createMessage.InnerText = ex.Message;
            }
        }
        static void Run()
        {
            string messageFile = "message.txt";

            string myLogName;
            string sourceName = "SampleApplicationSource";

            // Create the event source if it does not exist.
            if (!EventLog.SourceExists(sourceName))
            {
                // Create a new event source for the custom event log named "myNewLog".
                myLogName = "myNewLog";
                EventSourceCreationData mySourceData = new EventSourceCreationData(sourceName, myLogName);

                // Set the message resource file that the event source references.
                // All event resource identifiers correspond to test in this file.
                if (!System.IO.File.Exists(messageFile))
                {
                    Console.WriteLine("Input message resource file does not exist - {0}", messageFile);
                    messageFile = "";
                }
                else
                {
                    // Set the specified file as the resource file for message text,
                    //   category text, and message parameter strings.
                    mySourceData.MessageResourceFile = messageFile;
                    mySourceData.CategoryResourceFile = messageFile;
                    mySourceData.CategoryCount = CategoryCount;
                }
            }
        }
Beispiel #3
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;
        }
Beispiel #4
0
        private bool Init()
        {
            try
            {
                if (!EventLog.SourceExists(_eventSourceName))
                {
                    var eventSourceData = new EventSourceCreationData(_eventSourceName, _logName);
                    EventLog.CreateEventSource(eventSourceData);
                }

                _DBConnStr = ConfigurationManager.AppSettings["DBConnStr"].Trim();
                _MQServerUri = ConfigurationManager.AppSettings["MQServerUri"].Trim();
                _QueueName = ConfigurationManager.AppSettings["QueueName"].Trim();
                _Interval = int.Parse(ConfigurationManager.AppSettings["Interval"].Trim());
                _KpiInterval = int.Parse(ConfigurationManager.AppSettings["KpiInterval"].Trim());

                _Timer = new Timer() { Interval = _Interval, AutoReset = true, Enabled = true };
                _Timer.Elapsed += new ElapsedEventHandler(SendKpi);

                Log("Init completed.");
                return true;
            }
            catch(Exception ex)
            {
                LogError(ex.Message);
                return false;
            }
        }
		public override void CreateEventSource (EventSourceCreationData sourceData)
		{
			// construct path for storing log entries
			string logDir = FindLogStore (sourceData.LogName);
			// create event log store (if necessary), and modify access
			// permissions (unix only)
			if (!Directory.Exists (logDir)) {
				// ensure the log name is valid for customer logs
				ValidateCustomerLogName (sourceData.LogName, sourceData.MachineName);

				Directory.CreateDirectory (logDir);
				// MS does not allow an event source to be named after an already
				// existing event log. To speed up checking whether a given event
				// source already exists (either as a event source or event log)
				// we create an event source directory named after the event log.
				// This matches what MS does with the registry-based registration.
				Directory.CreateDirectory (Path.Combine (logDir, sourceData.LogName));
				if (RunningOnUnix) {
					ModifyAccessPermissions (logDir, "777");
					ModifyAccessPermissions (logDir, "+t");
				}
			}
			// create directory for event source, so we can check if the event
			// source already exists
			string sourceDir = Path.Combine (logDir, sourceData.Source);
			Directory.CreateDirectory (sourceDir);
		}
		public override void CreateEventSource (EventSourceCreationData sourceData)
		{
			using (RegistryKey eventLogKey = GetEventLogKey (sourceData.MachineName, true)) {
				if (eventLogKey == null)
					throw new InvalidOperationException ("EventLog registry key is missing.");

				bool logKeyCreated = false;
				RegistryKey logKey = null;
				try {
					logKey = eventLogKey.OpenSubKey (sourceData.LogName, true);
					if (logKey == null) {
						ValidateCustomerLogName (sourceData.LogName, 
							sourceData.MachineName);

						logKey = eventLogKey.CreateSubKey (sourceData.LogName);
						logKey.SetValue ("Sources", new string [] { sourceData.LogName,
							sourceData.Source });
						UpdateLogRegistry (logKey);

						using (RegistryKey sourceKey = logKey.CreateSubKey (sourceData.LogName)) {
							UpdateSourceRegistry (sourceKey, sourceData);
						}

						logKeyCreated = true;
					}

					if (sourceData.LogName != sourceData.Source) {
						if (!logKeyCreated) {
							string [] sources = (string []) logKey.GetValue ("Sources");
							if (sources == null) {
								logKey.SetValue ("Sources", new string [] { sourceData.LogName,
									sourceData.Source });
							} else {
								bool found = false;
								for (int i = 0; i < sources.Length; i++) {
									if (sources [i] == sourceData.Source) {
										found = true;
										break;
									}
								}
								if (!found) {
									string [] newSources = new string [sources.Length + 1];
									Array.Copy (sources, 0, newSources, 0, sources.Length);
									newSources [sources.Length] = sourceData.Source;
									logKey.SetValue ("Sources", newSources);
								}
							}
						}
						using (RegistryKey sourceKey = logKey.CreateSubKey (sourceData.Source)) {
							UpdateSourceRegistry (sourceKey, sourceData);
						}
					}
				} finally {
					if (logKey != null)
						logKey.Close ();
				}
			}
		}
Beispiel #7
0
        protected void Application_Error(object sender, EventArgs e)
        {
            var objErr = Server.GetLastError().GetBaseException();
            var source = new EventSourceCreationData("ECO.Web", "Application");
            if (!EventLog.SourceExists(source.Source, source.MachineName))
                EventLog.CreateEventSource(source);

            EventLog.WriteEntry(source.Source, GetInnerMostException(objErr).Message);
        }
Beispiel #8
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>
        public EventLogSink(string source, string logName, ITextFormatter textFormatter, string machineName)
        {
            if (source == null) throw new ArgumentNullException("source");

            _textFormatter = textFormatter;
            _source = source;

            var sourceData = new EventSourceCreationData(source, logName) { MachineName = machineName };

            if (!System.Diagnostics.EventLog.SourceExists(source, machineName)) System.Diagnostics.EventLog.CreateEventSource(sourceData);
        }
Beispiel #9
0
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);

            if (!EventLog.SourceExists(eventSourceName, "."))
            {
                EventSourceCreationData eventLogData = new EventSourceCreationData(eventSourceName, "Application");
                eventLogData.MachineName = ".";
                EventLog.CreateEventSource(eventLogData);
            }
        }
Beispiel #10
0
 public static void InsertarInformacionEventLog(string strOrigen, string strMensaje)
 {
     // Verifico que en el EventLog exista el orig
     if (!EventLog.SourceExists(strOrigen, "."))
     {
         // Si el origen no existe en el EventLog, lo creo dentro del grupo de errores de Aplicacion
         EventSourceCreationData srcData = new EventSourceCreationData(strOrigen, "Application");
         EventLog.CreateEventSource(srcData);
     }
     // Escribo el registro del warning en el EventLog
     EventLog.WriteEntry(strOrigen, strMensaje, EventLogEntryType.Information, 123);
 }
Beispiel #11
0
		/// <summary>
		///   Creates a logger based on <see cref = "EventLog" />.
		/// </summary>
		/// <param name = "logName"><see cref = "EventLog.Log" /></param>
		/// <param name = "machineName"><see cref = "EventLog.MachineName" /></param>
		/// <param name = "source"><see cref = "EventLog.Source" /></param>
		public DiagnosticsLogger(string logName, string machineName, string source)
		{
			// Create the source, if it does not already exist.
			if (!EventLog.SourceExists(source, machineName))
			{
				var eventSourceCreationData = new EventSourceCreationData(source, logName);
				eventSourceCreationData.MachineName = machineName;
				EventLog.CreateEventSource(eventSourceCreationData);
			}

			eventLog = new EventLog(logName, machineName, source);
		}
Beispiel #12
0
 public static void InsertarWarningEventLog(string strOrigen, System.Exception e)
 {
     // Verifico que en el EventLog exista el origen
     if (!EventLog.SourceExists(strOrigen, "."))
     {
         // Si el origen no existe en el EventLog, lo creo dentro del grupo de errores de Aplicacion
         EventSourceCreationData srcData = new EventSourceCreationData(strOrigen, "Application");
         EventLog.CreateEventSource(srcData);
     }
     // Escribo el registro del warning en el EventLog
     EventLog.WriteEntry(strOrigen, e.Source + "\n" + e.Message + "\n" + e.StackTrace, EventLogEntryType.Warning);
 }
Beispiel #13
0
		/// <summary>
		/// Initializes the logger by creating the necessary
		/// <see cref="EventLog"/> source.
		/// </summary>
		public EventLogger()
		{
			string source = ConfigurationSettings.Settings.ConnectionString;

			// Create the source, if it does not already exist.
			if (!EventLog.SourceExists(source, MACHINE_NAME))
			{
				EventSourceCreationData sourceData = new EventSourceCreationData(source, LOG_NAME);
				EventLog.CreateEventSource(sourceData);
			}

			_eventLog = new EventLog(LOG_NAME, MACHINE_NAME, source);
		}
        //// GET: api/Heroku
        //public string Get()
        //{
        //    LogToEvent("Entered Get", EventLogEntryType.Information);
        //    return "Get Successful";
        //}
        private void LogToEvent(string msg, EventLogEntryType errorType)
        {
            // create event source
            string strSource = "Wlocate";
            string instanceName = System.AppDomain.CurrentDomain.BaseDirectory;
            EventSourceCreationData evtSource = new EventSourceCreationData(strSource, strSource);
            if (!EventLog.SourceExists(strSource))
                EventLog.CreateEventSource(evtSource);

            // check error type
            string strLog = String.Format("{0}: {1}\r\n\"{2}\"", instanceName, strSource, msg);
            EventLog.WriteEntry(strSource, strLog, errorType);
        }
Beispiel #15
0
        public static void WriteToEventLog(string msg, string source) {
            

            if (!EventLog.SourceExists(source)) { 
                EventSourceCreationData sourceData = new EventSourceCreationData(source, source);

                EventLog.CreateEventSource(sourceData);
            }

            EventLog log = new EventLog();
            log.Source = source;
            log.WriteEntry(msg);
        }
		public void Constructor1 ()
		{
			EventSourceCreationData crd;

			crd = new EventSourceCreationData (null, null);
			Assert.AreEqual (0, crd.CategoryCount, "#A1");
			Assert.IsNull (crd.CategoryResourceFile, "#A2");
			Assert.IsNull (crd.LogName, "#A3");
			Assert.IsNotNull (crd.MachineName, "#A4");
			Assert.AreEqual (".", crd.MachineName, "#A5");
			Assert.IsNull (crd.MessageResourceFile, "#A6");
			Assert.IsNull (crd.ParameterResourceFile, "#A7");
			Assert.IsNull (crd.Source, "#A8");

			crd = new EventSourceCreationData ("src", null);
			Assert.AreEqual (0, crd.CategoryCount, "#B1");
			Assert.IsNull (crd.CategoryResourceFile, "#B2");
			Assert.IsNull (crd.LogName, "#B3");
			Assert.IsNotNull (crd.MachineName, "#B4");
			Assert.AreEqual (".", crd.MachineName, "#B5");
			Assert.IsNull (crd.MessageResourceFile, "#B6");
			Assert.IsNull (crd.ParameterResourceFile, "#B7");
			Assert.IsNotNull (crd.Source, "#B8");
			Assert.AreEqual ("src", crd.Source, "#B9");

			crd = new EventSourceCreationData (null, "log");
			Assert.AreEqual (0, crd.CategoryCount, "#C1");
			Assert.IsNull (crd.CategoryResourceFile, "#C2");
			Assert.IsNotNull (crd.LogName, "#C3");
			Assert.AreEqual ("log", crd.LogName, "#C4");
			Assert.IsNotNull (crd.MachineName, "#C5");
			Assert.AreEqual (".", crd.MachineName, "#C6");
			Assert.IsNull (crd.MessageResourceFile, "#C7");
			Assert.IsNull (crd.ParameterResourceFile, "#C8");
			Assert.IsNull (crd.Source, "#C9");

			crd = new EventSourceCreationData ("src", "log");
			Assert.AreEqual (0, crd.CategoryCount, "#C1");
			Assert.IsNull (crd.CategoryResourceFile, "#C2");
			Assert.IsNotNull (crd.LogName, "#C3");
			Assert.AreEqual ("log", crd.LogName, "#C4");
			Assert.IsNotNull (crd.MachineName, "#C5");
			Assert.AreEqual (".", crd.MachineName, "#C6");
			Assert.IsNull (crd.MessageResourceFile, "#C7");
			Assert.IsNull (crd.ParameterResourceFile, "#C8");
			Assert.IsNotNull (crd.Source, "#C9");
			Assert.AreEqual ("src", crd.Source, "#C10");
		}
Beispiel #17
0
        /// <summary>
        /// 해당 EventLog를 반환한다. Event Source가 없다면 생성한다.
        /// </summary>
        /// <param name="logName">로그 이름</param>
        /// <param name="source">엔트리 소스</param>
        /// <param name="machineName">로그가 있는 컴퓨터</param>
        /// <returns></returns>
        public static EventLog GetEventLog(string logName, string source, string machineName) {
            logName.ShouldNotBeWhiteSpace("logName");

            if(EventLog.SourceExists(source, machineName) == false) {
                var sourceData = new EventSourceCreationData(source, logName)
                                 {
                                     MachineName = machineName
                                 };
                EventLog.CreateEventSource(sourceData);
            }

            return new EventLog(logName, machineName, source)
                   {
                       EnableRaisingEvents = true
                   };
        }
Beispiel #18
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {

            if (!EventLog.SourceExists("SmokeSignal"))
            {
                EventSourceCreationData cd = new EventSourceCreationData("SmokeSignal", "Application");

                EventLog.CreateEventSource(cd);
            }
 
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
			{ 
				new SmokeSignal() 
			};
            ServiceBase.Run(ServicesToRun);
        }
Beispiel #19
0
    /// <summary>
    /// 创建事件日志
    /// </summary>
    /// <param name="machine">主机名称</param>
    /// <param name="logName">日志名称</param>
    /// <param name="source">事件源描述</param>
    /// <returns>事件日志</returns>
    public static EventLog CreateEventLog(string machine, string logName, string source)
    {
      EventLog log = GetEventLog(machine, logName);

      if (log == null)
      {
        EventSourceCreationData data = new EventSourceCreationData(source, logName);
        EventLog.CreateEventSource(data);
        log = GetEventLog(machine, logName);
        log.Source = source;
      }
      else
      {
        log.Source = source;
      }

      return log;
    }
Beispiel #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EventLogListener"/> class.
        /// </summary>
        public EventLogListener()
        {
            var assembly = AssemblyHelper.GetEntryAssembly();

            Source = assembly.Title();
            LogName = "Application";
            MachineName = Dns.GetHostName();

            var sourceData = new EventSourceCreationData(Source, LogName)
            {
                MachineName = MachineName
            };

            if (!EventLog.SourceExists(Source, MachineName))
            {
                EventLog.CreateEventSource(sourceData);
            }
        }
Beispiel #21
0
 public static void InsertarErrorEventLog(string strOrigen, System.Exception e)
 {
     // Verifico que en el EventLog exista el origen
     // Se puede utilizar la sobrecarga para indicarle en que servidor hacer el log
     // El punto "." representa el machineName localhost
     //EventLogPermission eventLogPermission = new EventLogPermission(EventLogPermissionAccess.Administer, ".");
     //eventLogPermission.PermitOnly();
     if (!EventLog.SourceExists(strOrigen, "."))
     {
         // Si el origen no existe en el EventLog, lo creo dentro del grupo de errores de Aplicacion
         EventSourceCreationData srcData = new EventSourceCreationData(strOrigen, "Application");
         EventLog.CreateEventSource(srcData);
     }
     // Escribo el registro del error en el EventLog
     /*
      * e.Source = Origen del mensaje Ej. Si fue un error del motor de base de datos
      * e.Message = Mensaje que indica el error que ocurrio
      * e.StackTrace = Pila de llamadas (Metodos) que se ocuparon antes de que se de el error
      */
     // Si no especifico el tipo de Error, el EventLog lo va a tomar como "Informacion"
     EventLog.WriteEntry(strOrigen, e.Source + "\n" + e.Message + "\n" + e.StackTrace, EventLogEntryType.Error);
     // Vuelvo a lanzar al error para que siga escalando hasta la capa de interfaz de usuario
 }
Beispiel #22
0
		private void btnCreate_Click(object sender, EventArgs e)
		{
			if (ValidateUserInput())
			{
				try
				{
					if (EventLogExists(tbEventLogName.Text)) {
						MessageBox.Show("This log allready exists on " + machineName + ".", "Smoothy", MessageBoxButtons.OK, MessageBoxIcon.Stop);
					}
					else {
						EventSourceCreationData data = new EventSourceCreationData(tbSourceName.Text, tbEventLogName.Text);
						data.MachineName = machineName;

						EventLog.CreateEventSource(data);

						this.DialogResult = DialogResult.OK;
					}
				}
				catch (Exception ex)
				{
					MessageBox.Show("Failed to create event log : " + ex.Message, "Smoothy", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
Beispiel #23
0
        static void CreateEventSource(EventSourceCreationData sourceData)
        {
            if (sourceData.Source == null || sourceData.Source.Length == 0)
            {
                throw new ArgumentException("Source property value has not been specified.");
            }

            if (sourceData.LogName == null || sourceData.LogName.Length == 0)
            {
                throw new ArgumentException("Log property value has not been specified.");
            }

            if (SourceExists(sourceData.Source, sourceData.MachineName))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
                                                          "Source '{0}' already exists on '{1}'.", sourceData.Source,
                                                          sourceData.MachineName));
            }

            EventLogImpl impl = CreateEventLogImpl(sourceData.LogName,
                                                   sourceData.MachineName, sourceData.Source);

            impl.CreateEventSource(sourceData);
        }
Beispiel #24
0
        public void Add(String Source, String _Content, EventLogEntryType _Type)
        {
            String LogName = ConfigurationManager.AppSettings["ServiceName"];

            if (String.IsNullOrEmpty(LogName))
            {
                LogName = "yueyaCms.Service";
            }

            String MachineName = ".";

            if (!EventLog.SourceExists(Source, MachineName))
            {
                var SourceEntity = new EventSourceCreationData(Source, LogName)
                {
                    MachineName = MachineName
                };
                EventLog.CreateEventSource(SourceEntity);
            }

            new EventLog(LogName, MachineName, Source).WriteEntry(_Content,
                _Type,
                Thread.CurrentContext.ContextID);
        }
        /// <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("source");
            if (textFormatter == null) throw new ArgumentNullException("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;
            _source = source;

            var sourceData = new EventSourceCreationData(source, logName) {MachineName = machineName};

            if (manageEventSource)
            {
                if (!System.Diagnostics.EventLog.SourceExists(source, machineName))
                {
                    System.Diagnostics.EventLog.CreateEventSource(sourceData);
                }
            }
        }
Beispiel #26
0
 private static void WriteLog(string zsModule, string zsSource, string zsMsg, EventLogEntryType eType)
 {
     try
     {
         zsSource = LogPrefix + zsSource;
         if (!EventLog.SourceExists(zsSource, LogMachine))
         {
             EventSourceCreationData srcData = new EventSourceCreationData(zsSource, LogName);
             EventLog.CreateEventSource(srcData);
         }
         EventLog eLog = null;
         try
         {
             eLog = new EventLog(zsModule, LogMachine, zsSource);
             eLog.WriteEntry(zsMsg, eType, 100);
         }
         finally
         {
             if (eLog != null)
             {
                 eLog.Dispose();
             }
         }
     }
     catch
     {
         if (!EventLog.SourceExists(LogPrefix, LogMachine))
         {
             EventSourceCreationData srcData = new EventSourceCreationData(LogPrefix, LogName);
             EventLog.CreateEventSource(srcData);
         }
         EventLog eLog = new EventLog(LogName, LogMachine, LogPrefix);
         eLog.WriteEntry(@"Error trying to write to the log", EventLogEntryType.Error, 100);
         eLog.Dispose();
     }
 }
Beispiel #27
0
        public WindowsEventLogging(string source, string log, int maxLvl, int dfltLvl)
        {
            this._source = source;
            this._log = log;
            this._maxLvl = maxLvl;
            this._dfltLvl = dfltLvl;

            if (!EventLog.SourceExists(source))
            {

                EventSourceCreationData data = new EventSourceCreationData(source, log);
                EventLog.CreateEventSource(data);

            }
        }
Beispiel #28
0
        private void CreateEventSourceIfNeeded()
        {
            // if we throw anywhere, we remain non-operational
            try
            {
                if (EventLog.SourceExists(Source, MachineName))
                {
                    var currentLogName = EventLog.LogNameFromSourceName(Source, MachineName);
                    if (currentLogName != Log)
                    {
                        // re-create the association between Log and Source
                        EventLog.DeleteEventSource(Source, MachineName);
                        var escd = new EventSourceCreationData(Source, Log)
                                       {
                                           MachineName = MachineName
                                       };

                        EventLog.CreateEventSource(escd);
                    }
                }
                else
                {
                    var escd = new EventSourceCreationData(Source, Log)
                                   {
                                       MachineName = MachineName
                                   };

                    EventLog.CreateEventSource(escd);
                }
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                InternalLogger.Error("Error when connecting to EventLog: {0}", exception);
                throw;
            }
        }
Beispiel #29
0
        /// <summary>
        ///     Performs installation which requires administrative permissions.
        /// </summary>
        /// <param name="installationContext">The installation context.</param>
        public void Install(InstallationContext installationContext)
        {
            if (EventLog.SourceExists(Source, MachineName))
            {
                var currentLogName = EventLog.LogNameFromSourceName(Source, MachineName);
                if (currentLogName != Log)
                {
                    // re-create the association between Log and Source
                    EventLog.DeleteEventSource(Source, MachineName);

                    var escd = new EventSourceCreationData(Source, Log)
                                   {
                                       MachineName = MachineName
                                   };

                    EventLog.CreateEventSource(escd);
                }
            }
            else
            {
                var escd = new EventSourceCreationData(Source, Log)
                               {
                                   MachineName = MachineName
                               };

                EventLog.CreateEventSource(escd);
            }
        }
Beispiel #30
0
 public static void CreateEventSource(EventSourceCreationData sourceData)
 {
     throw new NotImplementedException();
 }
Beispiel #31
0
        public override void CreateEventSource(EventSourceCreationData sourceData)
        {
            using (RegistryKey eventLogKey = GetEventLogKey(sourceData.MachineName, true)) {
                if (eventLogKey == null)
                {
                    throw new InvalidOperationException("EventLog registry key is missing.");
                }

                bool        logKeyCreated = false;
                RegistryKey logKey        = null;
                try {
                    logKey = eventLogKey.OpenSubKey(sourceData.LogName, true);
                    if (logKey == null)
                    {
                        ValidateCustomerLogName(sourceData.LogName,
                                                sourceData.MachineName);

                        logKey = eventLogKey.CreateSubKey(sourceData.LogName);
                        logKey.SetValue("Sources", new string [] { sourceData.LogName,
                                                                   sourceData.Source });
                        UpdateLogRegistry(logKey);

                        using (RegistryKey sourceKey = logKey.CreateSubKey(sourceData.LogName)) {
                            UpdateSourceRegistry(sourceKey, sourceData);
                        }

                        logKeyCreated = true;
                    }

                    if (sourceData.LogName != sourceData.Source)
                    {
                        if (!logKeyCreated)
                        {
                            string [] sources = (string [])logKey.GetValue("Sources");
                            if (sources == null)
                            {
                                logKey.SetValue("Sources", new string [] { sourceData.LogName,
                                                                           sourceData.Source });
                            }
                            else
                            {
                                bool found = false;
                                for (int i = 0; i < sources.Length; i++)
                                {
                                    if (sources [i] == sourceData.Source)
                                    {
                                        found = true;
                                        break;
                                    }
                                }
                                if (!found)
                                {
                                    string [] newSources = new string [sources.Length + 1];
                                    Array.Copy(sources, 0, newSources, 0, sources.Length);
                                    newSources [sources.Length] = sourceData.Source;
                                    logKey.SetValue("Sources", newSources);
                                }
                            }
                        }
                        using (RegistryKey sourceKey = logKey.CreateSubKey(sourceData.Source)) {
                            UpdateSourceRegistry(sourceKey, sourceData);
                        }
                    }
                } finally {
                    if (logKey != null)
                    {
                        logKey.Close();
                    }
                }
            }
        }
Beispiel #32
0
		private static bool CheckLog( string logName, string machineName, string applicationName)
		{
			bool bRes = false;

			Debug.Assert( (logName.Trim().Length > 0 || machineName.Trim().Length > 0 ),
				"One of the parameters passed in is empty.  See exception");

			if (logName.Trim().Length == 0 || logName.Trim().Length > 100)
			{
				throw new ArgumentException(SmartResourceManager.GetString("SEL_005", "Workshare.Common.Exceptions.Resource", Assembly.GetAssembly(typeof(SmartEventLog)), System.Threading.Thread.CurrentThread.CurrentCulture),
					"logName");
			}
			if (machineName.Trim().Length == 0 || machineName.Trim().Length > 100)
			{
				throw new ArgumentException(SmartResourceManager.GetString("SEL_006", "Workshare.Common.Exceptions.Resource", Assembly.GetAssembly(typeof(SmartEventLog)), System.Threading.Thread.CurrentThread.CurrentCulture),
					"machineName");
			}
			// Check that it exists
			if ( EventLog.Exists( logName, machineName ) )
			{	
				if ( !EventLog.SourceExists(applicationName, machineName) )
				{
					// The log does not exist so let's create it.
					try
					{
                        EventSourceCreationData creationData = new EventSourceCreationData(applicationName, logName);
                        creationData.MachineName = machineName;
						EventLog.CreateEventSource( creationData );
					}
					catch( SecurityException )
					{
						// Access to the register is restricted so let's just try it anyway.
					}
					catch( ArgumentException e )
					{					
						// Check to see if it's because the source is already registered for a different log.
						if ( e.Message.IndexOf( "already exists" )> 0 )
						{
							// It is so let's delete it and try again.
							EventLog.DeleteEventSource(applicationName, machineName);
							CheckLog( logName, machineName, applicationName );
						}
					}
				}
				bRes = true;


			}
			return bRes;
		}
        public static void CreateEventSource(EventSourceCreationData sourceData)
        {
            if (sourceData == null)
            {
                throw new ArgumentNullException("sourceData");
            }
            string logName     = sourceData.LogName;
            string source      = sourceData.Source;
            string machineName = sourceData.MachineName;

            if (!SyntaxCheck.CheckMachineName(machineName))
            {
                throw new ArgumentException(SR.GetString("InvalidParameter", new object[] { "machineName", machineName }));
            }
            if ((logName == null) || (logName.Length == 0))
            {
                logName = "Application";
            }
            if (!ValidLogName(logName, false))
            {
                throw new ArgumentException(SR.GetString("BadLogName"));
            }
            if ((source == null) || (source.Length == 0))
            {
                throw new ArgumentException(SR.GetString("MissingParameter", new object[] { "source" }));
            }
            if ((source.Length + @"SYSTEM\CurrentControlSet\Services\EventLog".Length) > 0xfe)
            {
                throw new ArgumentException(SR.GetString("ParameterTooLong", new object[] { "source", 0xfe - @"SYSTEM\CurrentControlSet\Services\EventLog".Length }));
            }
            new EventLogPermission(EventLogPermissionAccess.Administer, machineName).Demand();
            Mutex mutex = null;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                SharedUtils.EnterMutex("netfxeventlog.1.0", ref mutex);
                if (SourceExists(source, machineName, true))
                {
                    if (".".Equals(machineName))
                    {
                        throw new ArgumentException(SR.GetString("LocalSourceAlreadyExists", new object[] { source }));
                    }
                    throw new ArgumentException(SR.GetString("SourceAlreadyExists", new object[] { source, machineName }));
                }
                _UnsafeGetAssertPermSet().Assert();
                RegistryKey localMachine = null;
                RegistryKey keyParent    = null;
                RegistryKey logKey       = null;
                RegistryKey sourceLogKey = null;
                RegistryKey key5         = null;
                try
                {
                    if (machineName == ".")
                    {
                        localMachine = Registry.LocalMachine;
                    }
                    else
                    {
                        localMachine = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName);
                    }
                    keyParent = localMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\EventLog", true);
                    if (keyParent == null)
                    {
                        if (!".".Equals(machineName))
                        {
                            throw new InvalidOperationException(SR.GetString("RegKeyMissing", new object[] { @"SYSTEM\CurrentControlSet\Services\EventLog", logName, source, machineName }));
                        }
                        throw new InvalidOperationException(SR.GetString("LocalRegKeyMissing", new object[] { @"SYSTEM\CurrentControlSet\Services\EventLog", logName, source }));
                    }
                    logKey = keyParent.OpenSubKey(logName, true);
                    if ((logKey == null) && (logName.Length >= 8))
                    {
                        string strA = logName.Substring(0, 8);
                        if (((string.Compare(strA, "AppEvent", StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(strA, "SecEvent", StringComparison.OrdinalIgnoreCase) == 0)) || (string.Compare(strA, "SysEvent", StringComparison.OrdinalIgnoreCase) == 0))
                        {
                            throw new ArgumentException(SR.GetString("InvalidCustomerLogName", new object[] { logName }));
                        }
                        string str5 = FindSame8FirstCharsLog(keyParent, logName);
                        if (str5 != null)
                        {
                            throw new ArgumentException(SR.GetString("DuplicateLogName", new object[] { logName, str5 }));
                        }
                    }
                    bool flag = logKey == null;
                    if (flag)
                    {
                        if (SourceExists(logName, machineName, true))
                        {
                            if (".".Equals(machineName))
                            {
                                throw new ArgumentException(SR.GetString("LocalLogAlreadyExistsAsSource", new object[] { logName }));
                            }
                            throw new ArgumentException(SR.GetString("LogAlreadyExistsAsSource", new object[] { logName, machineName }));
                        }
                        logKey = keyParent.CreateSubKey(logName);
                        if (!SkipRegPatch)
                        {
                            logKey.SetValue("Sources", new string[] { logName, source }, RegistryValueKind.MultiString);
                        }
                        SetSpecialLogRegValues(logKey, logName);
                        sourceLogKey = logKey.CreateSubKey(logName);
                        SetSpecialSourceRegValues(sourceLogKey, sourceData);
                    }
                    if (logName != source)
                    {
                        if (!flag)
                        {
                            SetSpecialLogRegValues(logKey, logName);
                            if (!SkipRegPatch)
                            {
                                string[] array = logKey.GetValue("Sources") as string[];
                                if (array == null)
                                {
                                    logKey.SetValue("Sources", new string[] { logName, source }, RegistryValueKind.MultiString);
                                }
                                else if (Array.IndexOf <string>(array, source) == -1)
                                {
                                    string[] destinationArray = new string[array.Length + 1];
                                    Array.Copy(array, destinationArray, array.Length);
                                    destinationArray[array.Length] = source;
                                    logKey.SetValue("Sources", destinationArray, RegistryValueKind.MultiString);
                                }
                            }
                        }
                        key5 = logKey.CreateSubKey(source);
                        SetSpecialSourceRegValues(key5, sourceData);
                    }
                }
                finally
                {
                    if (localMachine != null)
                    {
                        localMachine.Close();
                    }
                    if (keyParent != null)
                    {
                        keyParent.Close();
                    }
                    if (logKey != null)
                    {
                        logKey.Flush();
                        logKey.Close();
                    }
                    if (sourceLogKey != null)
                    {
                        sourceLogKey.Flush();
                        sourceLogKey.Close();
                    }
                    if (key5 != null)
                    {
                        key5.Flush();
                        key5.Close();
                    }
                    CodeAccessPermission.RevertAssert();
                }
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.ReleaseMutex();
                    mutex.Close();
                }
            }
        }
 public static void CreateEventSource(EventSourceCreationData sourceData)
 {
 }
Beispiel #35
0
        public static void CreateEventLog(string prm_Informacion, int prm_EventoID, CategEvento prm_Categoria)
        {
            string NameEventLog = GlobalSettings.GetDEFAULT_NombreEventLog();

            bool logExists = EventLog.Exists(NameEventLog);

            EventLog DemoLog = new EventLog(NameEventLog, ".");

            if (!logExists)
            {
                System.Diagnostics.EventSourceCreationData creationData = new
                                                                          System.Diagnostics.EventSourceCreationData(NameEventLog, NameEventLog);
                creationData.MachineName = ".";

                EventLog.CreateEventSource(creationData);
                DemoLog.Source           = NameEventLog;
                DemoLog.MaximumKilobytes = 2048;

                DemoLog.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 7);
            }
            Trace.AutoFlush = true;
            EventLogTraceListener MyListener = new EventLogTraceListener(DemoLog);

            DemoLog.Source = NameEventLog;
            short             CATEGORIA = 0;
            EventLogEntryType prm_Tipo  = EventLogEntryType.SuccessAudit;

            switch (prm_Categoria)
            {
            case CategEvento.OK:
                CATEGORIA = 0;
                prm_Tipo  = System.Diagnostics.EventLogEntryType.Warning;
                break;

            case CategEvento.INSERT:
                CATEGORIA = 1;
                prm_Tipo  = System.Diagnostics.EventLogEntryType.FailureAudit;
                break;

            case CategEvento.UPDATE:
                prm_Tipo  = System.Diagnostics.EventLogEntryType.FailureAudit;
                CATEGORIA = 2;
                break;

            case CategEvento.DELETE:
                prm_Tipo  = System.Diagnostics.EventLogEntryType.FailureAudit;
                CATEGORIA = 3;
                break;

            case CategEvento.TRANSACTION:
                prm_Tipo  = System.Diagnostics.EventLogEntryType.Error;
                CATEGORIA = 4;
                break;

            case CategEvento.MESSAGE:
                CATEGORIA = 5;
                prm_Tipo  = System.Diagnostics.EventLogEntryType.Warning;
                break;

            case CategEvento.LIST:
                CATEGORIA = 5;
                prm_Tipo  = System.Diagnostics.EventLogEntryType.Warning;
                break;
            }
            DemoLog.WriteEntry(prm_Informacion, prm_Tipo, prm_EventoID, CATEGORIA); //
        }
Beispiel #36
0
 public abstract void CreateEventSource(EventSourceCreationData sourceData);
Beispiel #37
0
 public override void CreateEventSource(EventSourceCreationData sourceData)
 {
 }
        /// <summary>
        /// 注册日志来源和日志名称的映射关系
        /// </summary>
        /// <param name="source">来源</param>
        /// <param name="logName">日志名称</param>
        private string RegisterSourceToLogName(string source, string logName)
        {
            string registeredLogName = logName;

            EventSourceCreationData creationData = new EventSourceCreationData(source, logName);

            if (EventLog.SourceExists(source))
            {
                string originalLogName = EventLog.LogNameFromSourceName(source, FormattedEventLogTraceListener.DefaultMachineName);

                //source注册的日志名称和指定的logName不一致,且不等于source自身
                //(事件日志源“System”等于日志名称,不能删除。[System.InvalidOperationException])
                if (string.Compare(logName, originalLogName, true) != 0 && string.Compare(source, originalLogName, true) != 0)
                {
                    //删除现有的关联重新注册
                    EventLog.DeleteEventSource(source, FormattedEventLogTraceListener.DefaultMachineName);
                    EventLog.CreateEventSource(creationData);
                }
                else
                    registeredLogName = originalLogName;
            }
            else
                //source未在该服务器上注册过
                EventLog.CreateEventSource(creationData);

            return registeredLogName;
        }
Beispiel #39
0
 public static void CreateEventSource(System.Diagnostics.EventSourceCreationData sourceData)
 {
 }