Ejemplo n.º 1
0
        /// <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);
        }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 3
0
        /// <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.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase))
                {
                    // 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);
            }
        }
Ejemplo n.º 4
0
        /// <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 = LoggingConfiguration.AllTargets.OfType <PerformanceCounterTarget>().BucketSort(c => c.CategoryName);
            string categoryName       = 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[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.MustBeRethrownImmediately())
                {
                    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;
                }

                if (exception.MustBeRethrown())
                {
                    throw;
                }
            }
            finally
            {
                foreach (var t in countersByCategory[categoryName])
                {
                    t.created = true;
                }
            }
        }
Ejemplo n.º 5
0
        /// <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 (!initialized)
            {
                initialized = true;

                if (AutoCreate)
                {
                    using (var context = new InstallationContext())
                    {
                        Install(context);
                    }
                }

                try
                {
                    perfCounter = new PerformanceCounter(CategoryName, CounterName, InstanceName, false);
                }
                catch (Exception exception)
                {
                    InternalLogger.Error(exception, "Cannot open performance counter {0}/{1}/{2}.", CategoryName, CounterName, InstanceName);

                    if (exception.MustBeRethrown())
                    {
                        throw;
                    }
                }
            }

            return(perfCounter != null);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets the default set of resolution paths for the assembly resolution
        /// </summary>
        /// <returns>List of paths.</returns>
        internal IList <string> GetDefaultResolutionPaths()
        {
            var resolutionPaths = new List <string>();

            // Add the extension directories for assembly resolution
            var extensionDirectories = this.GetExtensionPaths(string.Empty).Select(e => Path.GetDirectoryName(Path.GetFullPath(e))).Distinct().ToList();

            if (extensionDirectories.Any())
            {
                resolutionPaths.AddRange(extensionDirectories);
            }

            // Keep current directory for resolution
            var currentDirectory = Path.GetDirectoryName(typeof(TestPluginCache).GetTypeInfo().Assembly.GetAssemblyLocation());

            if (!resolutionPaths.Contains(currentDirectory))
            {
                resolutionPaths.Add(currentDirectory);
            }

            // If running in Visual Studio context, add well known directories for resolution
            var installContext = new InstallationContext(new FileHelper());

            if (installContext.TryGetVisualStudioDirectory(out string vsInstallPath))
            {
                resolutionPaths.AddRange(installContext.GetVisualStudioCommonLocations(vsInstallPath));
            }

            return(resolutionPaths);
        }
Ejemplo n.º 7
0
        /// <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);
        }
        private Installation MigrateTenants(InstallConfig install)
        {
            var result = new Installation {
                Success = false, Message = string.Empty
            };

            string[] versions = Constants.ReleaseVersions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var upgrades = scope.ServiceProvider.GetRequiredService <IUpgradeManager>();

                using (var db = new InstallationContext(NormalizeConnectionString(_config.GetConnectionString(SettingKeys.ConnectionStringKey))))
                {
                    foreach (var tenant in db.Tenant.ToList())
                    {
                        MigrateScriptNamingConvention("Tenant", tenant.DBConnectionString);

                        var upgradeConfig = DeployChanges.To.SqlDatabase(NormalizeConnectionString(tenant.DBConnectionString))
                                            .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly(), s => s.Contains("Tenant.") && s.EndsWith(".sql", StringComparison.OrdinalIgnoreCase));

                        var upgrade = upgradeConfig.Build();
                        if (upgrade.IsUpgradeRequired())
                        {
                            var upgradeResult = upgrade.PerformUpgrade();
                            result.Success = upgradeResult.Successful;
                            if (!result.Success)
                            {
                                result.Message = upgradeResult.Error.Message;
                            }
                        }

                        // execute any version specific upgrade logic
                        string version = tenant.Version;
                        int    index   = Array.FindIndex(versions, item => item == version);
                        if (index != (versions.Length - 1))
                        {
                            if (index == -1)
                            {
                                index = 0;
                            }
                            for (int i = index; i < versions.Length; i++)
                            {
                                upgrades.Upgrade(tenant, versions[i]);
                            }
                            tenant.Version         = versions[versions.Length - 1];
                            db.Entry(tenant).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(result.Message))
            {
                result.Success = true;
            }

            return(result);
        }
Ejemplo n.º 9
0
 public virtual ValueTask InvokeAsync(
     InstallationContext context,
     Func <InstallationContext, ValueTask> next,
     CancellationToken cancellationToken = default)
 => AppliesTo(context)
         ? InstallAsync(context, cancellationToken)
         : next(context);
Ejemplo n.º 10
0
        /// <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(CategoryName))
            {
                return(false);
            }

            return(PerformanceCounterCategory.CounterExists(CounterName, CategoryName));
        }
Ejemplo n.º 11
0
        private async Task Init(long subscriptionId)
        {
            _pullRequests = await _dbContext
                            .PullRequests
                            .AsNoTracking()
                            .Where(q => q.SubscriptionId == subscriptionId &&
                                   q.PullRequestAnalyzeStatus == PullRequestAnalyzeStatus.NotAnalyzed)
                            .OrderBy(q => q.PullRequestInfo.MergedDateTime)
                            .ToArrayAsync();


            _loadMegaInfo = _pullRequests.Length > 100;

            _latestCommitDateTime = await _dbContext
                                    .Commits
                                    .Where(q => q.SubscriptionId == subscriptionId)
                                    .Select(q => q.DateTime)
                                    .MaxAsync();

            _subscription = await _dbContext.Subscriptions.SingleAsync(q => q.Id == subscriptionId);

            if (_gitHubOption != null)
            {
                _installationClient = await GitHubClientFactory.CreateGitHubInstallationClient(_gitHubOption, _subscription.InstallationId);
            }

            if (!_loadMegaInfo)
            {
                return;
            }

            _contributors = await _dbContext
                            .Contributors
                            .AsNoTracking()
                            .Where(q => q.SubscriptionId == subscriptionId && q.GitHubLogin != null).ToDictionaryAsync(q => q.GitHubLogin);

            var fileHistories = await _dbContext
                                .FileHistories
                                .AsNoTracking()
                                .Include(q => q.File)
                                .Where(q => q.SubscriptionId == subscriptionId)
                                .OrderBy(q => q.Contribution.DateTime)
                                .Select(q => new
            {
                q.File, q.OldPath, q.Path
            })
                                .ToArrayAsync();

            _files = new Dictionary <string, File>();

            foreach (var fileHistory in fileHistories)
            {
                _files[fileHistory.Path] = fileHistory.File;
            }
        }
Ejemplo n.º 12
0
        public ValueTask InstallAsync(InstallationContext context, CancellationToken cancellationToken = default)
        {
            _logger.InitialInstallers(_installers);
            var applicable = _installers.AllApplicable(context).ToList();

            _logger.ApplicableInstallers(applicable);

            return(applicable.Count > 0
                ? applicable.InvokePipelineAsync(context, cancellationToken)
                : ValueTask.CompletedTask);
        }
Ejemplo n.º 13
0
        /// <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!
        }
Ejemplo n.º 14
0
        /// <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);
            }
        }
        private Installation CreateTenant(InstallConfig install)
        {
            var result = new Installation {
                Success = false, Message = string.Empty
            };

            if (!string.IsNullOrEmpty(install.TenantName) && !string.IsNullOrEmpty(install.Aliases))
            {
                using (var db = new InstallationContext(NormalizeConnectionString(_config.GetConnectionString(SettingKeys.ConnectionStringKey))))
                {
                    Tenant tenant;
                    if (install.IsNewTenant)
                    {
                        tenant = new Tenant {
                            Name = install.TenantName, DBConnectionString = DenormalizeConnectionString(install.ConnectionString), CreatedBy = "", CreatedOn = DateTime.UtcNow, ModifiedBy = "", ModifiedOn = DateTime.UtcNow
                        };
                        db.Tenant.Add(tenant);
                        db.SaveChanges();
                        _cache.Remove("tenants");

                        if (install.TenantName == Constants.MasterTenant)
                        {
                            var job = new Job {
                                Name = "Notification Job", JobType = "Oqtane.Infrastructure.NotificationJob, Oqtane.Server", Frequency = "m", Interval = 1, StartDate = null, EndDate = null, IsEnabled = false, IsStarted = false, IsExecuting = false, NextExecution = null, RetentionHistory = 10, CreatedBy = "", CreatedOn = DateTime.UtcNow, ModifiedBy = "", ModifiedOn = DateTime.UtcNow
                            };
                            db.Job.Add(job);
                            db.SaveChanges();
                            _cache.Remove("jobs");
                        }
                    }
                    else
                    {
                        tenant = db.Tenant.FirstOrDefault(item => item.Name == install.TenantName);
                    }

                    foreach (string aliasname in install.Aliases.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        var alias = new Alias {
                            Name = aliasname, TenantId = tenant.TenantId, SiteId = -1, CreatedBy = "", CreatedOn = DateTime.UtcNow, ModifiedBy = "", ModifiedOn = DateTime.UtcNow
                        };
                        db.Alias.Add(alias);
                        db.SaveChanges();
                    }
                    _cache.Remove("aliases");
                }
            }

            result.Success = true;

            return(result);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Performs uninstallation which requires administrative permissions.
        /// </summary>
        /// <param name="installationContext">The installation context.</param>
        public void Uninstall(InstallationContext installationContext)
        {
            string categoryName = CategoryName;

            if (PerformanceCounterCategory.Exists(categoryName))
            {
                installationContext.Debug("Deleting category '{0}'", categoryName);
                PerformanceCounterCategory.Delete(categoryName);
            }
            else
            {
                installationContext.Debug("Category '{0}' does not exist.", categoryName);
            }
        }
Ejemplo n.º 17
0
        public TodoRepository(TodoContext appDb, IConfigurationRoot config)
        {
            try
            {
                appDb.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
            }
            catch (Exception)
            {
                appDb.InitializeTenant = new Tenant();;

                using (var db = new InstallationContext(NormalizeConnectionString(config.GetConnectionString(SettingKeys.ConnectionStringKey))))
                {
                    var master = db.Tenant.FirstOrDefault(i => i.Name == "Master");
                    appDb.InitializeTenant.DBConnectionString = master.DBConnectionString;
                }

                appDb.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
            }
            _appDb = appDb;
        }
Ejemplo n.º 18
0
        public async Task InstallAsync(
            IService service,
            string?directory = null,
            CancellationToken cancellationToken = default)
        {
            _logger.InvokedWorkingDirectory(directory);
            var workingDirectory = _serviceDirectory.GetInstallationDirectory(directory);

            _logger.ResolvedWorkingDirectory(workingDirectory);

            var context = new InstallationContext(
                workingDirectory,
                service,
                // TODO: Select sources
                service.Sources);

            _logger.InitialContextCreated(context);

            await _installationPipeline.InstallAsync(context, cancellationToken);
        }
Ejemplo n.º 19
0
        private Installation CreateTenant(InstallConfig install)
        {
            var result = new Installation {
                Success = false, Message = string.Empty
            };

            if (!string.IsNullOrEmpty(install.TenantName) && !string.IsNullOrEmpty(install.Aliases))
            {
                using (var db = new InstallationContext(NormalizeConnectionString(_config.GetConnectionString(SettingKeys.ConnectionStringKey))))
                {
                    Tenant tenant;
                    if (install.IsNewTenant)
                    {
                        tenant = new Tenant {
                            Name = install.TenantName, DBConnectionString = DenormalizeConnectionString(install.ConnectionString), CreatedBy = "", CreatedOn = DateTime.UtcNow, ModifiedBy = "", ModifiedOn = DateTime.UtcNow
                        };
                        db.Tenant.Add(tenant);
                        db.SaveChanges();
                        _cache.Remove("tenants");
                    }
                    else
                    {
                        tenant = db.Tenant.FirstOrDefault(item => item.Name == install.TenantName);
                    }

                    foreach (string aliasname in install.Aliases.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        var alias = new Alias {
                            Name = aliasname, TenantId = tenant.TenantId, SiteId = -1, CreatedBy = "", CreatedOn = DateTime.UtcNow, ModifiedBy = "", ModifiedOn = DateTime.UtcNow
                        };
                        db.Alias.Add(alias);
                        db.SaveChanges();
                    }
                    _cache.Remove("aliases");
                }
            }

            result.Success = true;

            return(result);
        }
Ejemplo n.º 20
0
        public static void CreateLogTableIfNotExists(DatabaseTarget dbTarget
                                                     , string strConnectionString)
        {
            StringBuilder              sb = new StringBuilder();
            InstallationContext        installationContext = new InstallationContext();
            SqlConnectionStringBuilder builder             = new SqlConnectionStringBuilder
            {
                ConnectionString = strConnectionString
            };
            string strDatabase = builder.InitialCatalog;

            sb.AppendLine("IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' " +
                          "AND  TABLE_NAME = 'ApplicationLogs')");
            sb.AppendLine("RETURN");
            sb.AppendLine("");
            sb.AppendLine("CREATE TABLE [dbo].[ApplicationLogs](");
            sb.AppendLine("[Id] [int] IDENTITY NOT NULL,");
            sb.AppendLine("[RegisteredDate] [DATETIME] NOT NULL,");
            sb.AppendLine("[Message] [nvarchar](max) NULL,");
            sb.AppendLine(" CONSTRAINT [PK_ApplicationLogs] PRIMARY KEY CLUSTERED ");
            sb.AppendLine("(");
            sb.AppendLine("[Id] ASC");
            sb.AppendLine(")WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON" +
                          ", ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]");
            sb.AppendLine(") ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]");

            DatabaseCommandInfo createTableCommand = new DatabaseCommandInfo
            {
                Text        = sb.ToString(),
                CommandType = System.Data.CommandType.Text
            };

            dbTarget.InstallDdlCommands.Add(createTableCommand);
            // we can now connect to the target DB
            dbTarget.InstallConnectionString = strConnectionString;
            // create the table if it does not exist
            dbTarget.Install(installationContext);
        }
Ejemplo n.º 21
0
        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();
            }
        }
Ejemplo n.º 22
0
 /// <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);
 }
Ejemplo n.º 23
0
 /// <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);
 }
Ejemplo n.º 24
0
        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 = RenderLogEvent(commandInfo.ConnectionString, logEvent);
                    }
                    else if (InstallConnectionString != null)
                    {
                        // next, try InstallConnectionString
                        cs = RenderLogEvent(InstallConnectionString, logEvent);
                    }
                    else
                    {
                        // if it's not defined, fall back to regular connection string
                        cs = BuildConnectionString(logEvent);
                    }

                    // Set ConnectionType if it has not been initialized already
                    if (ConnectionType == null)
                    {
                        SetConnectionType();
                    }

                    EnsureConnectionOpen(cs);

                    using (var command = _activeConnection.CreateCommand())
                    {
                        command.CommandType = commandInfo.CommandType;
                        command.CommandText = RenderLogEvent(commandInfo.Text, logEvent);

                        try
                        {
                            installationContext.Trace("Executing {0} '{1}'", command.CommandType, command.CommandText);
                            command.ExecuteNonQuery();
                        }
                        catch (Exception exception)
                        {
                            if (exception.MustBeRethrownImmediately())
                            {
                                throw;
                            }

                            if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures)
                            {
                                installationContext.Warning(exception.Message);
                            }
                            else
                            {
                                installationContext.Error(exception.Message);
                                throw;
                            }
                        }
                    }
                }
            }
            finally
            {
                InternalLogger.Trace("DatabaseTarget: close connection after install.");

                CloseConnection();
            }
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Performs uninstallation which requires administrative permissions.
 /// </summary>
 /// <param name="installationContext">The installation context.</param>
 public void Uninstall(InstallationContext installationContext)
 {
     RunInstallCommands(installationContext, UninstallDdlCommands);
 }
 public InstallationContextTests()
 {
     this.mockFileHelper      = new Mock <IFileHelper>();
     this.installationContext = new InstallationContext(this.mockFileHelper.Object);
 }
Ejemplo n.º 27
0
 public ValueTask InstallAsync(InstallationContext context, CancellationToken cancellationToken = default)
 {
     throw new System.NotImplementedException();
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Get the unit tests extensions
        /// </summary>
        private IEnumerable <string> GetTestExtensionsInternal(string extensionType)
        {
            IEnumerable <string> installedExtensions = new List <string>();

            // Navigate up to the IDE folder
            // In case of xcopyable vstest.console, this functionality is not supported.
            var installContext = new InstallationContext(this.fileHelper);

            if (!installContext.TryGetVisualStudioDirectory(out string vsInstallPath))
            {
                throw new TestPlatformException(string.Format(CultureInfo.CurrentCulture, Resources.VSInstallationNotFound));
            }

            // Adding resolution paths for resolving dependencies.
            var resolutionPaths = installContext.GetVisualStudioCommonLocations(vsInstallPath);

            using (var assemblyResolver = new AssemblyResolver(resolutionPaths))
            {
                object extensionManager;
                object settingsManager;

                settingsManager = SettingsManagerType.GetMethod("CreateForApplication", new Type[] { typeof(String) }).Invoke(null, new object[] { installContext.GetVisualStudioPath(vsInstallPath) });
                if (settingsManager != null)
                {
                    try
                    {
                        // create extension manager
                        extensionManager = Activator.CreateInstance(ExtensionManagerServiceType, settingsManager);

                        if (extensionManager != null)
                        {
                            installedExtensions = ExtensionManagerServiceType.GetMethod("GetEnabledExtensionContentLocations", new Type[] { typeof(String) }).Invoke(
                                extensionManager, new object[] { extensionType }) as IEnumerable <string>;
                        }
                        else
                        {
                            if (EqtTrace.IsWarningEnabled)
                            {
                                EqtTrace.Warning("VSExtensionManager : Unable to create extension manager");
                            }
                        }
                    }
                    finally
                    {
                        // Dispose the settings manager
                        IDisposable disposable = (settingsManager as IDisposable);
                        if (disposable != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
                else
                {
                    if (EqtTrace.IsWarningEnabled)
                    {
                        EqtTrace.Warning("VSExtensionManager : Unable to create settings manager");
                    }
                }
            }

            return(installedExtensions);
        }
        private Installation MigrateModules(InstallConfig install)
        {
            var result = new Installation {
                Success = false, Message = string.Empty
            };

            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var moduledefinitions = scope.ServiceProvider.GetRequiredService <IModuleDefinitionRepository>();
                var sql = scope.ServiceProvider.GetRequiredService <ISqlRepository>();
                foreach (var moduledefinition in moduledefinitions.GetModuleDefinitions())
                {
                    if (!string.IsNullOrEmpty(moduledefinition.ReleaseVersions) && !string.IsNullOrEmpty(moduledefinition.ServerManagerType))
                    {
                        Type moduletype = Type.GetType(moduledefinition.ServerManagerType);

                        string[] versions = moduledefinition.ReleaseVersions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        using (var db = new InstallationContext(NormalizeConnectionString(_config.GetConnectionString(SettingKeys.ConnectionStringKey))))
                        {
                            foreach (var tenant in db.Tenant.ToList())
                            {
                                int index = Array.FindIndex(versions, item => item == moduledefinition.Version);
                                if (tenant.Name == install.TenantName && install.TenantName != Constants.MasterTenant)
                                {
                                    index = -1;
                                }
                                if (index != (versions.Length - 1))
                                {
                                    if (index == -1)
                                    {
                                        index = 0;
                                    }
                                    for (int i = index; i < versions.Length; i++)
                                    {
                                        try
                                        {
                                            if (moduletype.GetInterface("IInstallable") != null)
                                            {
                                                var moduleobject = ActivatorUtilities.CreateInstance(scope.ServiceProvider, moduletype);
                                                ((IInstallable)moduleobject).Install(tenant, versions[i]);
                                            }
                                            else
                                            {
                                                sql.ExecuteScript(tenant, moduletype.Assembly, Utilities.GetTypeName(moduledefinition.ModuleDefinitionName) + "." + versions[i] + ".sql");
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            result.Message = "An Error Occurred Installing " + moduledefinition.Name + " Version " + versions[i] + " - " + ex.Message.ToString();
                                        }
                                    }
                                }
                            }
                            if (string.IsNullOrEmpty(result.Message) && moduledefinition.Version != versions[versions.Length - 1])
                            {
                                moduledefinition.Version         = versions[versions.Length - 1];
                                db.Entry(moduledefinition).State = EntityState.Modified;
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(result.Message))
            {
                result.Success = true;
            }

            return(result);
        }
Ejemplo n.º 30
0
 /// <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(Source, MachineName));
 }