Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Migration DNX to CLI

$
0
0


I did the migration of a project I worked for, and today it was my first contact with ASP.NET CLI. The migration was simple, I did for VS2017, after some compilation errors, which all I could solve, there was one problem that I'm not getting and I ask you for help, in the build, there are no more errors, but when executing the project it shows me the following message: The project does not know how to run the web profile. If I try to run it through IIS it also shows the error: The project does not know how to run the IIS Express profile. I'll leave here my startup.cs to check

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Netprime.Core;
using Netprime.Crosscuts.Authentication;
using Netprime.Crosscuts.Authorization;
using Netprime.Crosscuts.Exception;
using Netprime.Data;

namespace Netprime.Server
{
    public class Startup
    {
        public IConfiguration Configuration { get; set; }

        private readonly string _databaseType;

        private IList<Assembly> NetprimeStartupAssemblies { get; }

        private IList<Assembly> DatabaseAssemblies { get; }


        public Startup(ILibraryManager libraryManager, IApplicationEnvironment appEnv)
        {
            var config = new ConfigurationBuilder();

            config.SetBasePath(appEnv.ApplicationBasePath);

            config.AddJsonFile("netprime.json");

            config.AddEnvironmentVariables();

            Configuration = config.Build();
            _databaseType = Configuration.GetSection("DbSection:Database").Value;

            var nativeDlls = Configuration.GetSection("Native:Dlls").Value.Split(new[] {" , "}, StringSplitOptions.RemoveEmptyEntries);

            var checkDlls = Convert.ToBoolean(Configuration.GetSection("Native:CheckDlls").Value);

            NetprimeStartupAssemblies = new List<Assembly>();
            var netprimeStartupLibraryInfo = libraryManager.GetReferencingLibraries("Netprime.Core");

            foreach (var libraryInfo in netprimeStartupLibraryInfo)
            {
                NetprimeStartupAssemblies.Add(Assembly.Load(libraryInfo.Name));
            }

            DatabaseAssemblies = new List<Assembly>()
            {
               Assembly.Load("Netprime.Data")
            };
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddAuthentication();

            services.AddMemoryCache();

            #warning parou de funcionar após a atualização, substituido para o AddMemoryCache()
            //services.AddCaching();

            services.AddScoped<IAuthenticatedUser, MvcLoggedUser>();

            services.AddSingleton(_ => Configuration);

            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(AuthorizationFilter));
                options.Filters.Add(typeof(NetprimeExceptionFilter));
            });

            services.Configure<DbSettings>(Configuration.GetSection("DbSection"));

            ConfigureDatabase(services);
            ConfigureComponents(services);
            ConfigureAllowedModules(services);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(cors =>
            {
                cors.AllowCredentials();
                cors.AllowAnyHeader();
                cors.AllowAnyMethod();
                cors.AllowAnyOrigin();
            });

            app.UseCookieAuthentication(options =>
            {
                options.AutomaticAuthenticate = true;
                options.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.CookieName = ".netprime.auth";
                options.ExpireTimeSpan = new TimeSpan(24, 0, 0); //Seta o tempo de expiração da sessão do usuário.
            });

            app.UseMvc(mvc =>
            {
                mvc.MapRoute("default", "api/{controller}/{action}");
            });

            app.UseFileServer();
        }

        private void ConfigureDatabase(IServiceCollection services)
        {
            var assembly = DatabaseAssemblies
                .SingleOrDefault(a => a.FullName.StartsWith("Netprime.Data", StringComparison.OrdinalIgnoreCase));

            if (assembly == null)
                throw new ApplicationException("Database assembly not found: Netprime.Data");

            var dbContextTypeInfo =
                assembly.DefinedTypes.SingleOrDefault(
                    t => !t.IsInterface && typeof(DbContext).IsAssignableFrom(t) && t.Name == $"{_databaseType}DbContext");

            if (dbContextTypeInfo == null)
                throw new ApplicationException("DbContext implementation not found in: Netprime.Data");

            services.AddScoped(typeof(DbContext), dbContextTypeInfo.AsType());
        }

        private void ConfigureComponents(IServiceCollection services)
        {
            var assemblies = NetprimeStartupAssemblies
                .Where(a => a.FullName.StartsWith("Netprime.", StringComparison.OrdinalIgnoreCase));

            foreach (var assembly in assemblies)
            {
                var startupComponentTypes =
                    assembly.DefinedTypes.Where(t => !t.IsInterface && typeof(IComponentStartup).IsAssignableFrom(t)).ToArray();

                if (startupComponentTypes.Length > 0)
                {
                    foreach (var startupComponentType in startupComponentTypes)
                    {
                        var startupComponentInstance = (IComponentStartup)Activator.CreateInstance(startupComponentType);
                        if (startupComponentInstance.DbServices == null)
                            continue;
                        foreach (var dbService in startupComponentInstance.DbServices.Where(
                                    dbService =>
                                        dbService.Value.Name.EndsWith($"{_databaseType}Db",
                                            StringComparison.OrdinalIgnoreCase)))
                        {
                            services.AddScoped(dbService.Key, dbService.Value);
                        }
                    }
                }
            }
        }

        private void ConfigureAllowedModules(IServiceCollection services)
        {
            var assemblies = NetprimeStartupAssemblies
                .Where(a => a.FullName.StartsWith("Netprime.", StringComparison.OrdinalIgnoreCase));

            foreach (var assembly in assemblies)
            {
                var startupServiceTypes =
                    assembly.DefinedTypes.Where(t => !t.IsInterface && typeof (IServiceStartup).IsAssignableFrom(t))
                        .ToArray();

                if (startupServiceTypes.Length > 0)
                {
                    foreach (var startupServiceType in startupServiceTypes)
                    {
                        var startupServiceInstance = (IServiceStartup)Activator.CreateInstance(startupServiceType);
                        if (startupServiceInstance.Services != null)
                        {
                            foreach (var service in startupServiceInstance.Services)
                            {
                                services.AddScoped(service.Key, service.Value);
                            }
                        }

                        if (startupServiceInstance.DbServices != null)
                        {
                            foreach (var service in startupServiceInstance.DbServices.Where(
                                    dbService =>
                                        dbService.Value.Name.EndsWith($"{_databaseType}Db",
                                            StringComparison.OrdinalIgnoreCase)))
                            {
                                services.AddScoped(service.Key, service.Value);
                            }
                        }
                    }
                }

                var startupModuleTypes =
                    assembly.DefinedTypes.Where(t => !t.IsInterface && typeof (IModuleStartup).IsAssignableFrom(t))
                        .ToArray();
                if (startupModuleTypes.Length == 0)
                    continue;

                foreach (var startupModuleType in startupModuleTypes)
                {
                    var startupModuleInstance = (IModuleStartup)Activator.CreateInstance(startupModuleType);

                    if (startupModuleInstance.DbServices != null)
                    {
                        foreach (
                            var dbService in
                                startupModuleInstance.DbServices.Where(
                                    dbService =>
                                        dbService.Value.Name.EndsWith($"{_databaseType}Db",
                                            StringComparison.OrdinalIgnoreCase)))
                        {
                            services.AddScoped(dbService.Key, dbService.Value);
                        }
                    }
                }
            }
        }

        // Entry point for the application.
        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }
}
Please, I ask you to help me get back to running my project normally

Viewing all articles
Browse latest Browse all 9386

Trending Articles