private IServiceProvider?CreateFromHosting(string[] args)
    {
        _reporter.WriteVerbose(DesignStrings.FindingHostingServices);

        var serviceProviderFactory = HostFactoryResolver.ResolveServiceProviderFactory(_startupAssembly);

        if (serviceProviderFactory == null)
        {
            _reporter.WriteVerbose(DesignStrings.NoCreateHostBuilder);

            return(null);
        }

        var aspnetCoreEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        var dotnetEnvironment     = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
        var environment           = aspnetCoreEnvironment
                                    ?? dotnetEnvironment
                                    ?? "Development";

        if (aspnetCoreEnvironment == null)
        {
            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", environment);
        }

        if (dotnetEnvironment == null)
        {
            Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", environment);
        }

        _reporter.WriteVerbose(DesignStrings.UsingEnvironment(environment));

        try
        {
            var services = serviceProviderFactory(args);
            if (services == null)
            {
                _reporter.WriteWarning(DesignStrings.MalformedCreateHostBuilder);

                return(null);
            }

            _reporter.WriteVerbose(DesignStrings.UsingHostingServices);

            return(services.CreateScope().ServiceProvider);
        }
        catch (Exception ex)
        {
            if (ex is TargetInvocationException)
            {
                ex = ex.InnerException !;
            }

            _reporter.WriteVerbose(ex.ToString());
            _reporter.WriteWarning(DesignStrings.InvokeCreateHostBuilderFailed(ex.Message));

            return(null);
        }
    }
    private string ProcessTemplate(string inputFile, TextTemplatingCallback handler)
    {
        var output = _host.ProcessTemplate(
            inputFile,
            File.ReadAllText(inputFile),
            handler);

        foreach (CompilerError error in handler.Errors)
        {
            var builder = new StringBuilder();

            if (!string.IsNullOrEmpty(error.FileName))
            {
                builder.Append(error.FileName);

                if (error.Line > 0)
                {
                    builder
                    .Append("(")
                    .Append(error.Line);

                    if (error.Column > 0)
                    {
                        builder
                        .Append(",")
                        .Append(error.Line);
                    }
                    builder.Append(")");
                }

                builder.Append(" : ");
            }

            builder
            .Append(error.IsWarning ? "warning" : "error")
            .Append(" ")
            .Append(error.ErrorNumber)
            .Append(": ")
            .AppendLine(error.ErrorText);

            if (error.IsWarning)
            {
                _reporter.WriteWarning(builder.ToString());
            }
            else
            {
                _reporter.WriteError(builder.ToString());
            }
        }

        if (handler.OutputEncoding != Encoding.UTF8)
        {
            _reporter.WriteWarning(DesignStrings.EncodingIgnored(handler.OutputEncoding.WebName));
        }

        return(output);
    }
        private IServiceProvider CreateFromHosting(string[] args)
        {
            _reporter.WriteVerbose(DesignStrings.FindingHostingServices);

            var serviceProviderFactory = HostFactoryResolver.ResolveServiceProviderFactory(_startupAssembly);
            if (serviceProviderFactory == null)
            {
                _reporter.WriteVerbose(DesignStrings.NoCreateHostBuilder);

                return null;
            }

            // TODO: Remove when dotnet/cli#6617 is fixed
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            if (environment == null)
            {
                environment = "Development";
                Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", environment);
            }

            _reporter.WriteVerbose(DesignStrings.UsingEnvironment(environment));

            try
            {
                var services = serviceProviderFactory(args);
                if (services == null)
                {
                    _reporter.WriteWarning(DesignStrings.MalformedCreateHostBuilder);

                    return null;
                }

                _reporter.WriteVerbose(DesignStrings.UsingHostingServices);

                return services.CreateScope().ServiceProvider;
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }

                _reporter.WriteVerbose(ex.ToString());
                _reporter.WriteWarning(DesignStrings.InvokeCreateHostBuilderFailed(ex.Message));

                return null;
            }
        }
Exemple #4
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual ScaffoldedModel ScaffoldModel(
            string connectionString,
            DatabaseModelFactoryOptions databaseOptions,
            ModelReverseEngineerOptions modelOptions,
            ModelCodeGenerationOptions codeOptions)
        {
            if (!string.IsNullOrWhiteSpace(codeOptions.ContextName) &&
                (!_cSharpUtilities.IsValidIdentifier(codeOptions.ContextName) ||
                 _cSharpUtilities.IsCSharpKeyword(codeOptions.ContextName)))
            {
                throw new ArgumentException(
                          DesignStrings.ContextClassNotValidCSharpIdentifier(codeOptions.ContextName));
            }

            var resolvedConnectionString = _connectionStringResolver.ResolveConnectionString(connectionString);

            if (resolvedConnectionString != connectionString)
            {
                codeOptions.SuppressConnectionStringWarning = true;
            }
            else if (!codeOptions.SuppressOnConfiguring)
            {
                _reporter.WriteWarning(DesignStrings.SensitiveInformationWarning);
            }

            if (codeOptions.ConnectionString == null)
            {
                codeOptions.ConnectionString = connectionString;
            }

            var databaseModel         = _databaseModelFactory.Create(resolvedConnectionString, databaseOptions);
            var modelConnectionString = (string?)(databaseModel[ScaffoldingAnnotationNames.ConnectionString]);

            if (!string.IsNullOrEmpty(modelConnectionString))
            {
                codeOptions.ConnectionString = modelConnectionString;
                databaseModel.RemoveAnnotation(ScaffoldingAnnotationNames.ConnectionString);
            }

            var model = _factory.Create(databaseModel, modelOptions);

            if (model == null)
            {
                throw new InvalidOperationException(
                          DesignStrings.ProviderReturnedNullModel(
                              _factory.GetType().ShortDisplayName()));
            }

            if (string.IsNullOrEmpty(codeOptions.ContextName))
            {
                var annotatedName = model.GetDatabaseName();
                codeOptions.ContextName = !string.IsNullOrEmpty(annotatedName)
                    ? _code.Identifier(annotatedName + DbContextSuffix)
                    : DefaultDbContextName;
            }

            var codeGenerator = ModelCodeGeneratorSelector.Select(codeOptions.Language);

            return(codeGenerator.GenerateModel(model, codeOptions));
        }
        private void ProcessElement(IAnnotatable metadata, string version)
        {
            if (version.StartsWith("1.", StringComparison.Ordinal) &&
                metadata is IMutableAnnotatable mutableMetadata)
            {
                foreach (var annotation in mutableMetadata.GetAnnotations().ToList())
                {
                    var colon = annotation.Name.IndexOf(':');
                    if (colon > 0)
                    {
                        var stripped = annotation.Name.Substring(colon);
                        if (_relationalNames.Contains(stripped))
                        {
                            mutableMetadata.RemoveAnnotation(annotation.Name);
                            var relationalName = "Relational" + stripped;
                            var duplicate      = mutableMetadata.FindAnnotation(relationalName);

                            if (duplicate == null)
                            {
                                mutableMetadata[relationalName] = annotation.Value;
                            }
                            else if (!Equals(duplicate.Value, annotation.Value))
                            {
                                _operationReporter.WriteWarning(
                                    DesignStrings.MultipleAnnotationConflict(stripped.Substring(1)));
                            }
                        }
                    }
                }
            }
        }
Exemple #6
0
        private IServiceProvider CreateFromBuildWebHost(string[] args)
        {
            _reporter.WriteVerbose(DesignStrings.FindingBuildWebHost);

            var webHostFactoryResult = WebHostFactoryResolver.ResolveWebHostFactory <object, object>(_startupAssembly);

            switch (webHostFactoryResult.ResultKind)
            {
            case FactoryResolutionResultKind.Success:
                break;

            case FactoryResolutionResultKind.NoEntryPoint:
                _reporter.WriteVerbose(DesignStrings.NoEntryPoint(_startupAssembly.GetName().Name));
                return(null);

            case FactoryResolutionResultKind.NoCreateWebHostBuilder:
            case FactoryResolutionResultKind.NoBuildWebHost:
                _reporter.WriteVerbose(DesignStrings.NoBuildWebHost(webHostFactoryResult.ProgramType.DisplayName()));
                return(null);

            default:
                Debug.Fail("Unexpected value: " + webHostFactoryResult.ResultKind);
                return(null);
            }

            // TODO: Remove when dotnet/cli#6617 is fixed
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            if (environment == null)
            {
                environment = "Development";
                Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", environment);
            }

            _reporter.WriteVerbose(DesignStrings.UsingEnvironment(environment));
            _reporter.WriteVerbose(DesignStrings.UsingBuildWebHost(webHostFactoryResult.ProgramType.ShortDisplayName()));

            try
            {
                var webHost          = webHostFactoryResult.WebHostFactory(args);
                var webHostType      = webHost.GetType();
                var servicesProperty = webHostType.GetTypeInfo().GetDeclaredProperty("Services");
                var services         = (IServiceProvider)servicesProperty.GetValue(webHost);

                return(services.CreateScope().ServiceProvider);
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }

                _reporter.WriteVerbose(ex.ToString());
                _reporter.WriteWarning(DesignStrings.InvokeBuildWebHostFailed(webHostFactoryResult.ProgramType.ShortDisplayName(), ex.Message));

                return(null);
            }
        }
        private object Invoke(Type type, string[] methodNames, IServiceCollection services)
        {
            if (type == null)
            {
                return(null);
            }

            MethodInfo method = null;

            // ReSharper disable once ForCanBeConvertedToForeach
            for (var i = 0; i < methodNames.Length; i++)
            {
                method = type.GetTypeInfo().GetDeclaredMethod(methodNames[i]);
                if (method != null)
                {
                    break;
                }
            }

            if (method == null)
            {
                return(null);
            }

            try
            {
                var instance = !method.IsStatic
                    ? ActivatorUtilities.GetServiceOrCreateInstance(GetHostServices(), type)
                    : null;

                var parameters = method.GetParameters();
                var arguments  = new object[parameters.Length];
                for (var i = 0; i < parameters.Length; i++)
                {
                    var parameterType = parameters[i].ParameterType;
                    arguments[i] = parameterType == typeof(IServiceCollection)
                        ? services
                        : ActivatorUtilities.GetServiceOrCreateInstance(GetHostServices(), parameterType);
                }

                return(method.Invoke(instance, arguments));
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }

                _reporter.WriteWarning(
                    DesignStrings.InvokeStartupMethodFailed(method.Name, type.ShortDisplayName(), ex.Message));
                _reporter.WriteVerbose(ex.ToString());

                return(null);
            }
        }
        private IServiceProvider CreateFromBuildWebHost(string[] args)
        {
            _reporter.WriteVerbose(DesignStrings.FindingBuildWebHost);

            var programType = FindProgramClass();

            if (programType == null)
            {
                _reporter.WriteVerbose(DesignStrings.NoEntryPoint(_startupAssembly.GetName().Name));

                return(null);
            }

            var buildWebHostMethod = programType.GetTypeInfo().GetDeclaredMethod("BuildWebHost");

            if (buildWebHostMethod == null)
            {
                _reporter.WriteVerbose(DesignStrings.NoBuildWebHost(programType.DisplayName()));

                return(null);
            }

            // TODO: Remove when dotnet/cli#6617 is fixed
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            if (environment == null)
            {
                environment = "Development";
                Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", environment);
            }

            _reporter.WriteVerbose(DesignStrings.UsingEnvironment(environment));
            _reporter.WriteVerbose(DesignStrings.UsingBuildWebHost(programType.ShortDisplayName()));

            try
            {
                var webHost          = buildWebHostMethod.Invoke(null, new object[] { args });
                var webHostType      = webHost.GetType();
                var servicesProperty = webHostType.GetTypeInfo().GetDeclaredProperty("Services");
                var services         = (IServiceProvider)servicesProperty.GetValue(webHost);

                return(services.CreateScope().ServiceProvider);
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }

                _reporter.WriteVerbose(ex.ToString());
                _reporter.WriteWarning(DesignStrings.InvokeBuildWebHostFailed(programType.ShortDisplayName(), ex.Message));

                return(null);
            }
        }
Exemple #9
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual IEnumerable <MigrationInfo> GetMigrations(
            [CanBeNull] string contextType,
            [CanBeNull] string connectionString,
            bool noConnect)
        {
            using var context = _contextOperations.CreateContext(contextType);

            if (connectionString != null)
            {
                context.Database.SetConnectionString(connectionString);
            }

            var services = _servicesBuilder.Build(context);

            EnsureServices(services);

            var migrationsAssembly = services.GetRequiredService <IMigrationsAssembly>();
            var idGenerator        = services.GetRequiredService <IMigrationsIdGenerator>();

            HashSet <string> appliedMigrations = null;

            if (!noConnect)
            {
                try
                {
                    appliedMigrations = new HashSet <string>(
                        context.Database.GetAppliedMigrations(),
                        StringComparer.OrdinalIgnoreCase);
                }
                catch (Exception ex)
                {
                    _reporter.WriteVerbose(ex.ToString());
                    _reporter.WriteWarning(DesignStrings.ErrorConnecting(ex.Message));
                }
            }

            return(from id in migrationsAssembly.Migrations.Keys
                   select new MigrationInfo
            {
                Id = id,
                Name = idGenerator.GetName(id),
                Applied = appliedMigrations?.Contains(id)
            });
        }
Exemple #10
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual void Optimize(string?outputDir, string?modelNamespace, string?contextType)
        {
            using var context = CreateContext(contextType);

            var services   = _servicesBuilder.Build(context);
            var scaffolder = services.GetRequiredService <ICompiledModelScaffolder>();

            outputDir = outputDir != null
                ? Path.GetFullPath(Path.Combine(_projectDir, outputDir))
                : _projectDir;

            var finalModelNamespace = modelNamespace ?? GetNamespaceFromOutputPath(outputDir) ?? "";

            scaffolder.ScaffoldModel(
                context.GetService <IDesignTimeModel>().Model,
                outputDir,
                new CompiledModelCodeGenerationOptions
            {
                ContextType               = context.GetType(),
                ModelNamespace            = finalModelNamespace,
                Language                  = _language,
                UseNullableReferenceTypes = _nullable
            });

            var fullName = context.GetType().ShortDisplayName() + "Model";

            if (!string.IsNullOrEmpty(modelNamespace))
            {
                fullName = modelNamespace + "." + fullName;
            }

            _reporter.WriteInformation(DesignStrings.CompiledModelGenerated($"options.UseModel({fullName}.Instance)"));

            var cacheKeyFactory = context.GetService <IModelCacheKeyFactory>();

            if (!(cacheKeyFactory is ModelCacheKeyFactory))
            {
                _reporter.WriteWarning(DesignStrings.CompiledModelCustomCacheKeyFactory(cacheKeyFactory.GetType().ShortDisplayName()));
            }
        }
Exemple #11
0
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual void Log <TState>(
            LogLevel logLevel,
            EventId eventId,
            TState state,
            Exception exception,
            Func <TState, Exception, string> formatter)
        {
            // Only show SQL when verbose
            if (_categoryName == DbLoggerCategory.Database.Command.Name &&
                eventId.Id == RelationalEventId.CommandExecuted.Id)
            {
                logLevel = LogLevel.Debug;
            }

            var message = GetMessage(state, exception, formatter);

            switch (logLevel)
            {
            case LogLevel.Critical:
            case LogLevel.Error:
                _reporter.WriteError(message);
                break;

            case LogLevel.Warning:
                _reporter.WriteWarning(message);
                break;

            case LogLevel.Information:
                _reporter.WriteInformation(message);
                break;

            default:
                _reporter.WriteVerbose(message);
                break;
            }
        }
Exemple #12
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual void Log <TState>(
            LogLevel logLevel,
            EventId eventId,
            TState state,
            Exception exception,
            Func <TState, Exception, string> formatter)
        {
            // Only show SQL when verbose
            if (_categoryName == typeof(RelationalCommandBuilderFactory).FullName &&
                eventId.Id == (int)RelationalEventId.ExecutedCommand)
            {
                logLevel = LogLevel.Debug;
            }

            var message = GetMessage(state, exception, formatter);

            switch (logLevel)
            {
            case LogLevel.Critical:
            case LogLevel.Error:
                _reporter.WriteError(message);
                break;

            case LogLevel.Warning:
                _reporter.WriteWarning(message);
                break;

            case LogLevel.Information:
                _reporter.WriteInformation(message);
                break;

            default:
                _reporter.WriteVerbose(message);
                break;
            }
        }
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        protected virtual SequenceBuilder VisitSequence([NotNull] ModelBuilder modelBuilder, [NotNull] DatabaseSequence sequence)
        {
            Check.NotNull(modelBuilder, nameof(modelBuilder));
            Check.NotNull(sequence, nameof(sequence));

            if (string.IsNullOrEmpty(sequence.Name))
            {
                _reporter.WriteWarning(DesignStrings.SequencesRequireName);
                return(null);
            }

            Type sequenceType = null;

            if (sequence.StoreType != null)
            {
                sequenceType = _scaffoldingTypeMapper.FindMapping(
                    sequence.StoreType,
                    keyOrIndex: false,
                    rowVersion: false)
                               ?.ClrType;
            }

            if (sequenceType != null &&
                !Sequence.SupportedTypes.Contains(sequenceType))
            {
                _reporter.WriteWarning(DesignStrings.BadSequenceType(sequence.Name, sequence.StoreType));
                return(null);
            }

            var builder = sequenceType != null
                ? modelBuilder.HasSequence(sequenceType, sequence.Name, sequence.Schema)
                : modelBuilder.HasSequence(sequence.Name, sequence.Schema);

            if (sequence.IncrementBy.HasValue)
            {
                builder.IncrementsBy(sequence.IncrementBy.Value);
            }

            if (sequence.MaxValue.HasValue)
            {
                builder.HasMax(sequence.MaxValue.Value);
            }

            if (sequence.MinValue.HasValue)
            {
                builder.HasMin(sequence.MinValue.Value);
            }

            if (sequence.StartValue.HasValue)
            {
                builder.StartsAt(sequence.StartValue.Value);
            }

            if (sequence.IsCyclic.HasValue)
            {
                builder.IsCyclic(sequence.IsCyclic.Value);
            }

            return(builder);
        }