/// <summary> /// Uninstalls target-specific objects from current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Uninstallation typically runs with administrative permissions. /// </remarks> public void Uninstall(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); foreach (IInstallable installable in this.configItems.OfType <IInstallable>()) { installationContext.Info("Uninstalling '{0}'", installable); try { installable.Uninstall(installationContext); installationContext.Info("Finished uninstalling '{0}'.", installable); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } installationContext.Error("Uninstallation of '{0}' failed: {1}.", installable, exception); } } }
/// <summary> /// Installs target-specific objects on current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Installation typically runs with administrative permissions. /// </remarks> public void Install(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); var configItemsList = GetInstallableItems(); foreach (IInstallable installable in configItemsList) { installationContext.Info("Installing '{0}'", installable); try { installable.Install(installationContext); installationContext.Info("Finished installing '{0}'.", installable); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } installationContext.Error("'{0}' installation failed: {1}.", installable, exception); } } }
/// <summary> /// Uninstalls target-specific objects from current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Uninstallation typically runs with administrative permissions. /// </remarks> public void Uninstall(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); var configItemsList = GetInstallableItems(); foreach (IInstallable installable in configItemsList) { installationContext.Info("Uninstalling '{0}'", installable); try { installable.Uninstall(installationContext); installationContext.Info("Finished uninstalling '{0}'.", installable); } catch (Exception exception) { InternalLogger.Error(exception, "Uninstall of '{0}' failed.", installable); if (exception.MustBeRethrownImmediately()) { throw; } installationContext.Error("Uninstall of '{0}' failed: {1}.", installable, exception); } } }
/// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { if (EventLog.SourceExists(this.Source, this.MachineName)) { string currentLogName = EventLog.LogNameFromSourceName(this.Source, this.MachineName); if (currentLogName != this.Log) { // re-create the association between Log and Source EventLog.DeleteEventSource(this.Source, this.MachineName); var escd = new EventSourceCreationData(this.Source, this.Log) { MachineName = this.MachineName }; EventLog.CreateEventSource(escd); } } else { var escd = new EventSourceCreationData(this.Source, this.Log) { MachineName = this.MachineName }; EventLog.CreateEventSource(escd); } }
/// <summary> /// Ensures that the performance counter has been initialized. /// </summary> /// <returns>True if the performance counter is operational, false otherwise.</returns> private bool EnsureInitialized() { if (!this.initialized) { this.initialized = true; if (this.AutoCreate) { using (var context = new InstallationContext()) { this.Install(context); } } try { this.perfCounter = new PerformanceCounter(this.CategoryName, this.CounterName, this.InstanceName, false); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Cannot open performance counter {0}/{1}/{2}: {3}", this.CategoryName, this.CounterName, this.InstanceName, exception); } } return this.perfCounter != null; }
/// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { string categoryName = this.CategoryName; if (PerformanceCounterCategory.Exists(categoryName)) { installationContext.Debug("Deleting category '{0}'", categoryName); PerformanceCounterCategory.Delete(categoryName); } else { installationContext.Debug("Category '{0}' does not exist.", categoryName); } }
/// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { if (!PerformanceCounterCategory.Exists(this.CategoryName)) { return false; } return PerformanceCounterCategory.CounterExists(this.CounterName, this.CategoryName); }
/// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { // categories must be installed together, so we must find all PerfCounter targets in the configuration file var countersByCategory = this.LoggingConfiguration.AllTargets.OfType<PerformanceCounterTarget>().BucketSort(c => c.CategoryName); string categoryName = this.CategoryName; if (countersByCategory[categoryName].Any(c => c.created)) { installationContext.Trace("Category '{0}' has already been installed.", categoryName); return; } try { PerformanceCounterCategoryType categoryType; CounterCreationDataCollection ccds = GetCounterCreationDataCollection(countersByCategory[this.CategoryName], out categoryType); if (PerformanceCounterCategory.Exists(categoryName)) { installationContext.Debug("Deleting category '{0}'", categoryName); PerformanceCounterCategory.Delete(categoryName); } installationContext.Debug("Creating category '{0}' with {1} counter(s) (Type: {2})", categoryName, ccds.Count, categoryType); foreach (CounterCreationData c in ccds) { installationContext.Trace(" Counter: '{0}' Type: ({1}) Help: {2}", c.CounterName, c.CounterType, c.CounterHelp); } PerformanceCounterCategory.Create(categoryName, "Category created by NLog", categoryType, ccds); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } if (installationContext.IgnoreFailures) { installationContext.Warning("Error creating category '{0}': {1}", categoryName, exception.Message); } else { installationContext.Error("Error creating category '{0}': {1}", categoryName, exception.Message); throw; } } finally { foreach (var t in countersByCategory[categoryName]) { t.created = true; } } }
/// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { this.RunInstallCommands(installationContext, this.UninstallDdlCommands); }
/// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { var fixedSource = GetFixedSource(); if (!string.IsNullOrEmpty(fixedSource)) { return EventLog.SourceExists(fixedSource, this.MachineName); } InternalLogger.Debug("Unclear if event source exists because it contains layout renderers"); return null; //unclear! }
/// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { var fixedSource = GetFixedSource(); if (string.IsNullOrEmpty(fixedSource)) { InternalLogger.Debug("Skipping removing of event source because it contains layout renderers"); } else { EventLog.DeleteEventSource(fixedSource, this.MachineName); } }
/// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { var fixedSource = GetFixedSource(); //always throw error to keep backwardscomp behavior. CreateEventSourceIfNeeded(fixedSource, true); }
/// <summary> /// Uninstalls target-specific objects from current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Uninstallation typically runs with administrative permissions. /// </remarks> public void Uninstall(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); foreach (IInstallable installable in EnumerableHelpers.OfType<IInstallable>(this.configItems)) { installationContext.Info("Uninstalling '{0}'", installable); try { installable.Uninstall(installationContext); installationContext.Info("Finished uninstalling '{0}'.", installable); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } installationContext.Error("Uninstallation of '{0}' failed: {1}.", installable, exception); } } }
public void SqlServer_InstallAndLogMessage() { if (SqlServerTest.IsTravis()) { Console.WriteLine("skipping test SqlServer_InstallAndLogMessage because we are running in Travis"); return; } SqlServerTest.TryDropDatabase(); try { SqlServerTest.CreateDatabase(); var connectionString = SqlServerTest.GetConnectionString(); LogManager.Configuration = CreateConfigurationFromString(@" <nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' throwExceptions='true'> <targets> <target name='database' xsi:type='Database' connectionstring=""" + connectionString + @""" commandText='insert into dbo.NLogSqlServerTest (Uid) values (@uid);'> <parameter name='@uid' layout='${event-properties:uid}' /> <install-command ignoreFailures=""false"" text=""CREATE TABLE dbo.NLogSqlServerTest ( Id int NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, Uid uniqueidentifier NULL );""/> </target> </targets> <rules> <logger name='*' writeTo='database' /> </rules> </nlog>"); //install InstallationContext context = new InstallationContext(); LogManager.Configuration.Install(context); var tableCatalog = SqlServerTest.IssueScalarQuery(@"SELECT TABLE_CATALOG FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Dbo' AND TABLE_NAME = 'NLogSqlServerTest'"); //check if table exists Assert.Equal("NLogTest", tableCatalog); var logger = LogManager.GetLogger("A"); var target = LogManager.Configuration.FindTargetByName<DatabaseTarget>("database"); var uid = new Guid("e7c648b4-3508-4df2-b001-753148659d6d"); var logEvent = new LogEventInfo(LogLevel.Info, null, null); logEvent.Properties["uid"] = uid; logger.Log(logEvent); var count = SqlServerTest.IssueScalarQuery("SELECT count(1) FROM dbo.NLogSqlServerTest"); Assert.Equal(1, count); var result = SqlServerTest.IssueScalarQuery("SELECT Uid FROM dbo.NLogSqlServerTest"); Assert.Equal(uid, result); } finally { SqlServerTest.TryDropDatabase(); } }
/// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { EventLog.DeleteEventSource(this.Source, this.MachineName); }
/// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { return EventLog.SourceExists(this.Source, this.MachineName); }
/// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { return null; }
static int Main(string[] args) { try { using (var context = new InstallationContext()) { context.LogOutput = Console.Out; XmlLoggingConfiguration configuration = null; bool uninstallMode = false; for (int i = 0; i < args.Length; ++i) { switch (args[i]) { case "-q": context.LogOutput = TextWriter.Null; break; case "-consolelog": context.LogOutput = Console.Out; break; case "-loglevel": context.LogLevel = LogLevel.FromString(args[++i]); break; case "-i": context.IgnoreFailures = true; break; case "-log": context.LogOutput = File.CreateText(args[++i]); break; case "-p": string arg = args[++i]; int p = arg.IndexOf('='); if (p < 0) { Console.WriteLine("Parameter '{0}' must be NAME=VALUE", arg); Usage(); return 1; } string paramName = arg.Substring(0, p); string paramValue = arg.Substring(p + 1); context.Parameters.Add(paramName, paramValue); break; case "-u": uninstallMode = true; break; case "-?": Usage(); return 0; default: if (args[i].StartsWith("-")) { Usage(); return 1; } configuration = new XmlLoggingConfiguration(args[i]); break; } } if (configuration == null) { Usage(); return 1; } if (uninstallMode) { configuration.Uninstall(context); } else { configuration.Install(context); } return 0; } } catch (Exception ex) { Console.WriteLine("EXCEPTION: {0}", ex); return 1; } }
private void RunInstallCommands(InstallationContext installationContext, IEnumerable<DatabaseCommandInfo> commands) { // create log event that will be used to render all layouts LogEventInfo logEvent = installationContext.CreateLogEvent(); try { foreach (var commandInfo in commands) { string cs; if (commandInfo.ConnectionString != null) { // if there is connection string specified on the command info, use it cs = commandInfo.ConnectionString.Render(logEvent); } else if (this.InstallConnectionString != null) { // next, try InstallConnectionString cs = this.InstallConnectionString.Render(logEvent); } else { // if it's not defined, fall back to regular connection string cs = this.BuildConnectionString(logEvent); } this.EnsureConnectionOpen(cs); var command = this.activeConnection.CreateCommand(); command.CommandType = commandInfo.CommandType; command.CommandText = commandInfo.Text.Render(logEvent); try { installationContext.Trace("Executing {0} '{1}'", command.CommandType, command.CommandText); command.ExecuteNonQuery(); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures) { installationContext.Warning(exception.Message); } else { installationContext.Error(exception.Message); throw; } } } } finally { this.CloseConnection(); } }