예제 #1
0
        private static void WriteLog(string categoryName, EventId eventId, LogLevel level, string message, Exception exception)
        {
            bool flag = string.IsNullOrEmpty(categoryName);

            if (flag)
            {
                throw new ArgumentNullException("categoryName");
            }
            bool           flag2 = LoggerFactory.ServiceProvider == null;
            ILoggerFactory factory;

            if (flag2)
            {
                IServiceCollection services = LoggerFactory.ServiceCollection ?? new ServiceCollection();
                services.AddFileLog(null);
                factory = ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services).GetService <ILoggerFactory>();
            }
            else
            {
                factory = LoggerFactory.ServiceProvider.GetService <ILoggerFactory>();
            }
            ILogger logger = factory.CreateLogger(categoryName);

            logger.Log(level, eventId, exception, message, Array.Empty <object>());
        }
예제 #2
0
 public void Run(Action <IConfiguration, IServiceProvider, ILoggerFactory> runCallback)
 {
     runCallback(
         new ConfigurationRoot(new List <IConfigurationProvider>()),
         ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(new ServiceCollection()),
         new NullLoggerFactory());
 }
예제 #3
0
        internal static Container BuildSimpleInjectorServiceProvider(this IServiceCollection serviceCollection)
        {
            var container = new Container
            {
                Options =
                {
                    DefaultScopedLifestyle = new AsyncScopedLifestyle()
                }
            };

            var appBuilder = new FakeApplicationBuilder
            {
                ApplicationServices = serviceCollection.BuildServiceProvider()
            };

            serviceCollection.AddSimpleInjector(container);
            serviceCollection.UseSimpleInjectorAspNetRequestScoping(container);

            ServiceCollection services = serviceCollection as ServiceCollection;

            ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services, validateScopes: true)
            .UseSimpleInjector(container);



            return(container);
        }
예제 #4
0
        private static IServiceCollection AddSwaggerInternal(
            this IServiceCollection services,
            string applicationName,
            Action <SwaggerGenOptions> configure = null)
        {
            services.AddApiVersioning((Action <ApiVersioningOptions>)(options =>
            {
                options.ReportApiVersions = true;
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(1, 0);
            }));

            services.AddVersionedApiExplorer((Action <ApiExplorerOptions>)(options =>
            {
                options.GroupNameFormat           = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            }));

            services.AddSwaggerGen((Action <SwaggerGenOptions>)(options =>
            {
                foreach (ApiVersionDescription versionDescription in ServiceProviderServiceExtensions
                         .GetRequiredService <IApiVersionDescriptionProvider>(
                             ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services))
                         .ApiVersionDescriptions)
                {
                    options.SwaggerDoc(versionDescription.GroupName, new OpenApiInfo()
                    {
                        Title   = applicationName,
                        Version = versionDescription.ApiVersion.ToString()
                    });
                }

                options.UseInlineDefinitionsForEnums();

                options.MapType <Guid>((Func <OpenApiSchema>)(() => new OpenApiSchema()
                {
                    Type   = "string",
                    Format = "uuid"
                }));
                options.MapType <Decimal>((Func <OpenApiSchema>)(() => new OpenApiSchema()
                {
                    Type   = "number",
                    Format = ""
                }));
                options.MapType <Decimal?>((Func <OpenApiSchema>)(() => new OpenApiSchema()
                {
                    Type   = "number",
                    Format = ""
                }));

                Action <SwaggerGenOptions> action = configure;
                if (action == null)
                {
                    return;
                }
                action(options);
            }));

            return(services);
        }
예제 #5
0
        public DecoratorBuilder <TInterface> Envelop(Func <IServiceProvider, TInterface, TInterface> envelop)
        {
            var provider = ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(_services);

            _decoratedService = envelop(provider, _decoratedService);

            return(this);
        }
예제 #6
0
        public UseCaseBus Build()
        {
            var provider        = ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services);
            var usecaseProvider = new UseCaseProvider(provider);

            bus.Setup(usecaseProvider);

            return(bus);
        }
예제 #7
0
        public TestServiceProvider()
        {
            var services = new ServiceProvider().ServiceCollection;


            //Services = services;
            var bootstrapper = new BootstrapManager(services);

            _serviceProvider = ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services);
        }
예제 #8
0
        public DecoratorBuilder <TInterface> Default <TService>()
            where TService : class, TInterface
        {
            ServiceCollectionServiceExtensions.AddTransient <TService>(_services);
            var provider = ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(_services);

            _decoratedService = (TInterface)provider.GetService(typeof(TService));

            return(this);
        }
예제 #9
0
        // Taken from Microsoft.AspNetCore.Hosting.WebHostBuilder.Build() due to breaking change in Microsoft.Extensions.DependencyInjection
        // See https://github.com/aspnet/EntityFrameworkCore/issues/8498
        // Can be removed once the AspNetCore packages are updated to 2.x
        public static IWebHost BuildWebHost(this IWebHostBuilder builder)
        {
            IServiceCollection serviceCollection      = (IServiceCollection)InvokeMethod((WebHostBuilder)builder, "BuildCommonServices");
            IServiceProvider   hostingServiceProvider = ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(serviceCollection);

            InvokeMethod((WebHostBuilder)builder, "AddApplicationServices", new object[] { serviceCollection, hostingServiceProvider });
            WebHost webHost = new WebHost(
                serviceCollection,
                hostingServiceProvider,
                (WebHostOptions)GetFieldValue((WebHostBuilder)builder, "_options"),
                (IConfiguration)GetFieldValue((WebHostBuilder)builder, "_config"));

            if ((IServiceProvider)GetFieldValue(webHost, "_applicationServices") == null)
            {
                IServiceCollection applicationServiceCollection = (IServiceCollection)GetFieldValue(webHost, "_applicationServiceCollection");
                SetFieldValue(webHost, "_applicationServices", applicationServiceCollection.BuildServiceProvider());
            }

            SetFieldValue(webHost, "_application", BuildApplication(webHost));
            return(webHost);
        }
예제 #10
0
        private static IServiceCollection AddSwaggerInternal(
            this IServiceCollection services,
            string applicationName,
            Action <SwaggerGenOptions> configure = null)
        {
            services.AddApiVersioning((Action <ApiVersioningOptions>)(options =>
            {
                options.ReportApiVersions = true;
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(1, 0);
            }));

            services.AddVersionedApiExplorer((Action <ApiExplorerOptions>)(options =>
            {
                options.GroupNameFormat           = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            }));

            services.AddSwaggerGen((Action <SwaggerGenOptions>)(options =>
            {
                foreach (ApiVersionDescription versionDescription in (IEnumerable <ApiVersionDescription>)ServiceProviderServiceExtensions.GetRequiredService <IApiVersionDescriptionProvider>(ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services)).ApiVersionDescriptions)
                {
                    options.SwaggerDoc(versionDescription.GroupName, new OpenApiInfo()
                    {
                        Title   = applicationName,
                        Version = versionDescription.ApiVersion.ToString()
                    });
                }

                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey,
                    Scheme      = "Bearer"
                });

                options.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        Array.Empty <string>()
                    }
                });

                options.UseInlineDefinitionsForEnums();

                options.MapType <Guid>((Func <OpenApiSchema>)(() => new OpenApiSchema()
                {
                    Type   = "string",
                    Format = "uuid"
                }));
                options.MapType <Decimal>((Func <OpenApiSchema>)(() => new OpenApiSchema()
                {
                    Type   = "number",
                    Format = ""
                }));
                options.MapType <Decimal?>((Func <OpenApiSchema>)(() => new OpenApiSchema()
                {
                    Type   = "number",
                    Format = ""
                }));

                Action <SwaggerGenOptions> action = configure;
                if (action == null)
                {
                    return;
                }
                action(options);
            }));

            return(services);
        }
 /// <summary>
 /// Adds LiteX SQLite Cache manager services
 /// </summary>
 /// <param name="services"></param>
 /// <param name="config">SQLite configuration settings, default: use 'SQLiteConfig' from appsettings.json</param>
 /// <returns></returns>
 public static IServiceCollection AddLiteXSQLiteCache(this IServiceCollection services, SQLiteConfig config = null)
 {
     //IL_0019: Unknown result type (might be due to invalid IL or missing references)
     //IL_001e: Expected O, but got Unknown
     //IL_002b: Unknown result type (might be due to invalid IL or missing references)
     //IL_0030: Unknown result type (might be due to invalid IL or missing references)
     if (config == null)
     {
         IConfiguration        requiredService = ServiceProviderServiceExtensions.GetRequiredService <IConfiguration>((IServiceProvider)ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services));
         IConfigurationSection section         = requiredService.GetSection(SQLiteCacheDefaults.SettingsSection);
         config = ((section != null) ? ConfigurationBinder.Get <SQLiteConfig>(section) : null);
         if (config == null)
         {
             config = new SQLiteConfig
             {
                 FileName      = SQLiteCacheDefaults.FileName,
                 FilePath      = SQLiteCacheDefaults.FilePath,
                 OpenMode      = 0,
                 CacheMode     = 0,
                 EnableLogging = LiteXCacheDefaults.EnableLogging
             };
         }
         config.FilePath = ((!string.IsNullOrWhiteSpace(config.FilePath)) ? config.FilePath : SQLiteCacheDefaults.FilePath);
     }
     return(services.AddLiteXSQLiteCache(delegate(SQLiteConfig option)
     {
         //IL_0029: Unknown result type (might be due to invalid IL or missing references)
         //IL_003a: Unknown result type (might be due to invalid IL or missing references)
         option.FileName = config.FileName;
         option.FilePath = config.FilePath;
         option.OpenMode = config.OpenMode;
         option.CacheMode = config.CacheMode;
     }));
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddScoped <IUserHelper, WebUserHelper>();
            services.AddScoped <IUserProvider, SqlUserProvider>();
            services.AddScoped <IAccountHelper, WebAccountHelper>();
            services.AddScoped <IAccountProvider, SqlAccountProvider>();
            services.AddScoped <IResolutorFacade, ResolutorFacade>();
            services.AddScoped <IRequestHelper, WebRequestHelper>();
            services.AddScoped <IRequestProvider, SqlRequestProvider>();
            services.AddScoped <IVeicleHelper, WebVeicleHelper>();
            services.AddScoped <IVeicleProvider, SqlVeicleProvider>();
            services.AddScoped <IFileService, BlobService>();

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new SqlProfile());
                mc.AddProfile(new FrontEndProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            var connectionStringSql = Configuration.GetConnectionString("DefaultConnection");
            var connectionBlobCloud = Configuration.GetConnectionString("CloudConnection");


            /*   string storageConnectionString = Environment.GetEnvironmentVariable("DefaultEndpointsProtocol=https;AccountName=vapdev;AccountKey=28hpcto4rpAQJcK/Zqmk5sa1Qm6OaKODliNulnwLl7FYcNBFeoGa5WKcaGYcHT0k1Q2oTYyCVmyhMCry2UetXA==;EndpointSuffix=core.windows.net");
             *
             * // Check whether the connection string can be parsed.
             * CloudStorageAccount storageAccount;
             * if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
             * {
             * }
             * else
             * {
             *     // Otherwise, let the user know that they need to define the environment variable.
             *     Console.WriteLine(
             *         "A connection string has not been defined in the system environment variables. " +
             *         "Add an environment variable named 'storageconnectionstring' with your storage " +
             *         "connection string as a value.");
             *     Console.WriteLine("Press any key to exit the sample application.");
             *     Console.ReadLine();
             * }
             */


            //var connection = @"data source=srv-db-dev;initial catalog=Test42;persist security info=True;user id=Test42User;password=Test42Password;";
            //var testConnectionString = @"data source=srv-db-dev;initial catalog=Test42_Copia_Test;persist security info=True;user id=Test42User;password=Test42Password;";
            //OAuthAuthorizationServerOptions oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions()
            //{

            //    AllowInsecureHttp = true,
            //    TokenEndpointPath = new PathString("/token"),
            //    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            //    Provider = new ApplicationOAuthProviderApi(),
            //    AuthorizeEndpointPath = new PathString("/api/AccountApi/login"),
            //    ApplicationCanDisplayErrors = true,

            //    RefreshTokenProvider = new SimpleRefreshTokenProvider(),
            //    AccessTokenFormat = new CustomJwtFormat(), //localhost?


            //};
            //services.AddAuthentication().AddOAuth("", services => Oa);
            services.AddDbContext <SqlModelsContext>
                (options => options
                .UseLazyLoadingProxies()
                .UseSqlServer(connectionStringSql));

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = OpenIdConnectDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddOpenIdConnect((Action <OpenIdConnectOptions>)(options =>
            {
                options.Authority               = "https://login.microsoftonline.com/99169c38-99a6-4511-9596-51869cca9f6e"; //endpoint OIDC che voglio utilizzare ok
                options.ClientId                = "10415ac4-186b-4ce6-954a-e234a72f0dd0";                                   //ok
                options.CallbackPath            = "/Auth/Logged";                                                           //url di risposta ed è pannello URL di risposta in Azure AD
                options.SignedOutRedirectUri    = "/Auth/LoggedOut";
                options.Events.OnTicketReceived = async ctx =>
                {
                    string authenticationType        = "authenticationType";
                    var myServices                   = ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services);
                    IUserHelper userHelper           = myServices.GetService <IUserHelper>();
                    IResolutorFacade resolutorFacade = myServices.GetService <IResolutorFacade>();
                    //services.ApplicationServices
                    //userHelper = DependencyResolver.Current.GetService<IUserHelper>();
                    // userHelper = this.Configuration.Get<IUserHelper>();
                    ClaimsIdentity claims = new ClaimsIdentity(authenticationType);



                    var email = ctx.Principal.FindFirstValue(ClaimTypes.Upn);
                    //var ajeje = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value;

                    //ctx.Principal.FindFirst(a=>a.)
                    var user = await resolutorFacade.UserAsync(email);
                    // ci.AddClaim(new Claim(accounts, ajeje));
                    claims.AddClaim(new Claim(ClaimTypes.Name, user.Name));
                    claims.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
                    claims.AddClaim(new Claim(ClaimTypes.Surname, user.Surname));
                    claims.AddClaim(new Claim(ClaimTypes.Thumbprint, user.Image));

                    var accounts = user.Assignements.Select(x => x.Account);

                    if (accounts.Count() == 0)
                    {
                        throw new Exception(Resource.not_authorized);
                    }

                    //var authClaims = "claims";

                    foreach (var account in accounts)
                    {
                        //ci.Add(new ClaimsPrincipal(accounts));
                        claims.AddClaim(new Claim("account", JsonConvert.SerializeObject(account)));
                    }


                    var defaultAccount = accounts.FirstOrDefault(x => x.IsDefault);
                    if (defaultAccount == null)
                    {
                        defaultAccount = accounts.FirstOrDefault();
                    }

                    claims.AddClaim(new Claim("selectedAccountId", defaultAccount.Id));
                    claims.AddClaim(new Claim("selectedAccountEmail", defaultAccount.Email));

                    //foreach(var role in defaultAccount.Roles)
                    //{
                    //    claims.AddClaim(new Claim(ClaimTypes.Role, role.DefaultRole.Name));
                    //}

                    claims.AddClaim(new Claim(ClaimTypes.Role, Enum.GetName(typeof(AccountantTypes), defaultAccount.AccountType)));

                    claims.AddClaim(new Claim("selectedAccount", JsonConvert.SerializeObject(defaultAccount)));

                    ctx.Principal.AddIdentity(claims);
                };
            }))
            .AddCookie(options =>
            {
                options.LoginPath = "/auth/login";
            });

            services.AddLocalization(o =>
            {
                // We will put our translations in a folder called Resources
                o.ResourcesPath = "Resources";
            });
            services.AddMvc(
                options =>
            {
                options.ModelBinderProviders.Insert(0, new MyBinderProvider());

                options.AllowValidatingTopLevelNodes = false;
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }