Esempio n. 1
0
	public Test(){
		var environment = CallContextServiceLocator.Locator.ServiceProvider.GetService(typeof(IApplicationEnvironment)) as IApplicationEnvironment;
 		var hostingEnvironment = new HostingEnvironment(environment);
        var startup = new Startup(hostingEnvironment);
		var testServer = TestServer.Create(x => startup.Configure(x, hostingEnvironment), startup.ConfigureServices);
		client = testServer.CreateClient();
	}
Esempio n. 2
0
    public TestBase()
    {
      if (ServiceProvider == null)
      {
        var services = new ServiceCollection();

        // set up empty in-memory test db
        services
          .AddEntityFrameworkInMemoryDatabase()
          .AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase().UseInternalServiceProvider(services.BuildServiceProvider()));

        // add identity service
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<AllReadyContext>();
        var context = new DefaultHttpContext();
        context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
        services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });

        // Setup hosting environment
        IHostingEnvironment hostingEnvironment = new HostingEnvironment();
        hostingEnvironment.EnvironmentName = "Development";
        services.AddSingleton(x => hostingEnvironment);

        // set up service provider for tests
        ServiceProvider = services.BuildServiceProvider();
      }
    }
Esempio n. 3
0
 public HostingEngine(IServiceProvider fallbackServices)
 {
     _fallbackServices = fallbackServices ?? CallContextServiceLocator.Locator.ServiceProvider;
     _appLifetime = new ApplicationLifetime();
     _applicationEnvironment = _fallbackServices.GetRequiredService<IApplicationEnvironment>();
     _hostingEnvironment = new HostingEnvironment(_applicationEnvironment);
     _fallbackServices = new WrappingServiceProvider(_fallbackServices, _hostingEnvironment, _appLifetime);
 }
        public void OverridesEnvironmentFromConfig()
        {
            var env = new HostingEnvironment();
            env.EnvironmentName = "SomeName";

            env.Initialize("DummyApplication", Path.GetFullPath("."), new WebHostOptions(){ Environment = "NewName" });

            Assert.Equal("NewName", env.EnvironmentName);
        }
        public void SetsFullPathToWwwroot()
        {
            var env = new HostingEnvironment();

            env.Initialize("DummyApplication", Path.GetFullPath("."), new WebHostOptions(){ WebRoot = "testroot" });

            Assert.Equal(Path.GetFullPath("."), env.ContentRootPath);
            Assert.Equal(Path.GetFullPath("testroot"), env.WebRootPath);
            Assert.IsAssignableFrom<PhysicalFileProvider>(env.ContentRootFileProvider);
            Assert.IsAssignableFrom<PhysicalFileProvider>(env.WebRootFileProvider);
        }
        public void DefaultsToNullFileProvider()
        {
            var env = new HostingEnvironment();

            env.Initialize("DummyApplication", Path.GetFullPath(Path.Combine("testroot", "wwwroot")), new WebHostOptions());

            Assert.Equal(Path.GetFullPath(Path.Combine("testroot", "wwwroot")), env.ContentRootPath);
            Assert.Null(env.WebRootPath);
            Assert.IsAssignableFrom<PhysicalFileProvider>(env.ContentRootFileProvider);
            Assert.IsAssignableFrom<NullFileProvider>(env.WebRootFileProvider);
        }
Esempio n. 7
0
        public void StartupWithNoConfigureThrows()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IFakeStartupCallback>(this);
            var services = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List<string>();
            var hostingEnv = new HostingEnvironment { EnvironmentName = "Boom" };
            var loader = new StartupLoader(services, hostingEnv);
            var type = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);

            var ex = Assert.Throws<InvalidOperationException>(() => loader.LoadMethods(type, diagnosticMessages));
            Assert.Equal("A public method named 'ConfigureBoom' or 'Configure' could not be found in the 'Microsoft.AspNet.Hosting.Fakes.StartupBoom' type.", ex.Message);
        }
Esempio n. 8
0
        public IISHost(HostingEnvironment env, ILogger log)
        {
            #region Preconditions

            if (env == null)
                throw new ArgumentNullException(nameof(env));

            if (log == null)
                throw new ArgumentNullException(nameof(log));

            #endregion

            this.env = env;
            this.log = log;
        }
        public AllReadyDataAccessEF7Tests()
        {
            if (_serviceProvider == null)
            {
                var services = new ServiceCollection();

                // Add EF (Full DB, not In-Memory)
                services.AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase());

                // Setup hosting environment
                IHostingEnvironment hostingEnvironment = new HostingEnvironment();
                hostingEnvironment.EnvironmentName = "Development";
                services.AddSingleton(x => hostingEnvironment);
                _serviceProvider = services.BuildServiceProvider();
            }
        }
        public void StartupClassCanHandleConfigureServicesThatReturnsNull()
        {
            var serviceCollection = new ServiceCollection();
            var services = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List<string>();
            var hostingEnv = new HostingEnvironment { EnvironmentName = "WithNullConfigureServices" };
            var loader = new StartupLoader(services, hostingEnv);
            var type = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);
            var startup = loader.LoadMethods(type, diagnosticMessages);

            var app = new ApplicationBuilder(services);
            app.ApplicationServices = startup.ConfigureServicesDelegate(new ServiceCollection());
            Assert.NotNull(app.ApplicationServices);
            startup.ConfigureDelegate(app);
            Assert.NotNull(app.ApplicationServices);
        }
Esempio n. 11
0
        public void StartupClassMayHaveHostingServicesInjected()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IFakeStartupCallback>(this);
            var services = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List<string>();
            var hostingEnv = new HostingEnvironment { EnvironmentName = "WithServices" };
            var loader = new StartupLoader(services, hostingEnv);
            var type = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);
            var startup = loader.LoadMethods(type, diagnosticMessages);

            var app = new ApplicationBuilder(services);
            app.ApplicationServices = startup.ConfigureServicesDelegate(serviceCollection);
            startup.ConfigureDelegate(app);

            Assert.Equal(2, _configurationMethodCalledList.Count);
        }
Esempio n. 12
0
        public void StartupClassAddsConfigureServicesToApplicationServices(string environment)
        {
            var services = new ServiceCollection().BuildServiceProvider();

            var diagnosticMessages = new List<string>();
            var hostingEnv = new HostingEnvironment { EnvironmentName = environment };
            var loader = new StartupLoader(services, hostingEnv);
            var type = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);
            var startup = loader.LoadMethods(type, diagnosticMessages);

            var app = new ApplicationBuilder(services);
            app.ApplicationServices = startup.ConfigureServicesDelegate(new ServiceCollection());
            startup.ConfigureDelegate(app);

            var options = app.ApplicationServices.GetRequiredService<IOptions<FakeOptions>>().Value;
            Assert.NotNull(options);
            Assert.True(options.Configured);
            Assert.Equal(environment, options.Environment);
        }
Esempio n. 13
0
        public void StartupWithTwoConfiguresThrows()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IFakeStartupCallback>(this);
            var services = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List<string>();
            var hostingEnv = new HostingEnvironment { EnvironmentName = "TwoConfigures" };
            var loader = new StartupLoader(services, hostingEnv);
            var type = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);

            var ex = Assert.Throws<InvalidOperationException>(() => loader.LoadMethods(type, diagnosticMessages));
            Assert.Equal("Having multiple overloads of method 'Configure' is not supported.", ex.Message);
        }
Esempio n. 14
0
        public void StartupLoaderCanLoadByTypeWithEnvironment()
        {
            var serviceCollection = new ServiceCollection();
            var services = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List<string>();
            var hostingEnv = new HostingEnvironment { EnvironmentName = "No" };
            var loader = new StartupLoader(services, hostingEnv);
            var startup = loader.LoadMethods(typeof(TestStartup), diagnosticMessages);

            var app = new ApplicationBuilder(services);
            app.ApplicationServices = startup.ConfigureServicesDelegate(serviceCollection);

            var ex = Assert.Throws<TargetInvocationException>(() => startup.ConfigureDelegate(app));
            Assert.IsAssignableFrom(typeof(InvalidOperationException), ex.InnerException);
        }
Esempio n. 15
0
        private void ConfigureApiServices(IServiceCollection services)
        {
            services.AddApiVersioning(options => options.VersionByQuery("api-version"));
            services.AddSwaggerApiVersioning();
            services.Configure <MvcJsonOptions>(
                options =>
            {
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.Converters.Add(new StringEnumConverter {
                    CamelCaseText = true
                });
                options.SerializerSettings.Converters.Add(
                    new IsoDateTimeConverter
                {
                    DateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ",
                    DateTimeStyles = DateTimeStyles.AdjustToUniversal
                });
            });

            services.AddSwaggerGen(
                options =>
            {
                options.FilterOperations(
                    (op, ctx) =>
                {
                    op.Responses["default"] = new Response
                    {
                        Description = "Error",
                        Schema      = ctx.SchemaRegistry.GetOrRegister(typeof(ApiError))
                    };
                    op.OperationId = $"{op.Tags.First()}_{op.OperationId}";
                });

                options.MapType <TimeSpan>(
                    () => new Schema
                {
                    Type   = "string",
                    Format = "duration"
                });
                options.MapType <TimeSpan?>(
                    () => new Schema
                {
                    Type   = "string",
                    Format = "duration"
                });
                options.MapType <JToken>(() => new Schema());

                options.DescribeAllEnumsAsStrings();

                string xmlPath;
                if (HostingEnvironment.IsDevelopment())
                {
                    xmlPath = Path.Combine(HostingEnvironment.ContentRootPath, "bin/Debug/net461");
                }
                else
                {
                    xmlPath = HostingEnvironment.ContentRootPath;
                }

                string xmlFile = Path.Combine(xmlPath, "Maestro.Web.xml");
                if (File.Exists(xmlFile))
                {
                    options.IncludeXmlComments(xmlFile);
                }

                options.AddSecurityDefinition(
                    "Bearer",
                    new ApiKeyScheme
                {
                    Type = "apiKey",
                    In   = "header",
                    Name = "Authorization"
                });

                options.FilterDocument(
                    (doc, ctx) =>
                {
                    doc.Security = new List <IDictionary <string, IEnumerable <string> > >
                    {
                        new Dictionary <string, IEnumerable <string> >
                        {
                            ["Bearer"] = Enumerable.Empty <string>()
                        }
                    };
                });
            });
        }
Esempio n. 16
0
        public void StartupClassWithConfigureServicesShouldMakeServiceAvailableInConfigure()
        {
            var serviceCollection = new ServiceCollection();
            var services = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List<string>();
            var hostingEnv = new HostingEnvironment { EnvironmentName = "WithConfigureServices" };
            var loader = new StartupLoader(services, hostingEnv);
            var type = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);
            var startup = loader.LoadMethods(type, diagnosticMessages);

            var app = new ApplicationBuilder(services);
            app.ApplicationServices = startup.ConfigureServicesDelegate(serviceCollection);
            startup.ConfigureDelegate(app);

            var foo = app.ApplicationServices.GetRequiredService<StartupWithConfigureServices.IFoo>();
            Assert.True(foo.Invoked);
        }
Esempio n. 17
0
 public void Shutdown()
 {
     HostingEnvironment.InitiateShutdown();
 }
Esempio n. 18
0
        public ILifetimeScope CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            var intermediateScope = _lifetimeScope.BeginLifetimeScope(
                builder => {
                foreach (var item in blueprint.Dependencies.Where(t => typeof(IModule).IsAssignableFrom(t.Type)))
                {
                    var registration = RegisterType(builder, item)
                                       .Keyed <IModule>(item.Type)
                                       .InstancePerDependency();

                    foreach (var parameter in item.Parameters)
                    {
                        registration = registration
                                       .WithParameter(parameter.Name, parameter.Value)
                                       .WithProperty(parameter.Name, parameter.Value);
                    }
                }
            });

            return(intermediateScope.BeginLifetimeScope(
                       "shell",
                       builder => {
                var dynamicProxyContext = new DynamicProxyContext();

                builder.Register(ctx => dynamicProxyContext);
                builder.Register(ctx => settings);
                builder.Register(ctx => blueprint.Descriptor);
                builder.Register(ctx => blueprint);

                var moduleIndex = intermediateScope.Resolve <IIndex <Type, IModule> >();
                foreach (var item in blueprint.Dependencies.Where(t => typeof(IModule).IsAssignableFrom(t.Type)))
                {
                    builder.RegisterModule(moduleIndex[item.Type]);
                }

                foreach (var item in blueprint.Dependencies.Where(t => typeof(IDependency).IsAssignableFrom(t.Type)))
                {
                    var registration = RegisterType(builder, item)
                                       .EnableDynamicProxy(dynamicProxyContext)
                                       .InstancePerLifetimeScope();

                    foreach (var interfaceType in item.Type.GetInterfaces()
                             .Where(itf => typeof(IDependency).IsAssignableFrom(itf) &&
                                    !typeof(IEventHandler).IsAssignableFrom(itf)))
                    {
                        registration = registration.As(interfaceType).AsSelf();
                        if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType))
                        {
                            registration = registration.InstancePerMatchingLifetimeScope("shell");
                        }
                        else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType))
                        {
                            registration = registration.InstancePerMatchingLifetimeScope("work");
                        }
                        else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType))
                        {
                            registration = registration.InstancePerDependency();
                        }
                    }

                    if (typeof(IEventHandler).IsAssignableFrom(item.Type))
                    {
                        var interfaces = item.Type.GetInterfaces();
                        foreach (var interfaceType in interfaces)
                        {
                            // register named instance for each interface, for efficient filtering inside event bus
                            // IEventHandler derived classes only
                            if (interfaceType.GetInterface(typeof(IEventHandler).Name) != null)
                            {
                                registration = registration.Named <IEventHandler>(interfaceType.Name);
                            }
                        }
                    }

                    foreach (var parameter in item.Parameters)
                    {
                        registration = registration
                                       .WithParameter(parameter.Name, parameter.Value)
                                       .WithProperty(parameter.Name, parameter.Value);
                    }
                }

                foreach (var item in blueprint.Controllers)
                {
                    var serviceKeyName = (item.AreaName + "/" + item.ControllerName).ToLowerInvariant();
                    var serviceKeyType = item.Type;
                    RegisterType(builder, item)
                    .EnableDynamicProxy(dynamicProxyContext)
                    .Keyed <IController>(serviceKeyName)
                    .Keyed <IController>(serviceKeyType)
                    .WithMetadata("ControllerType", item.Type)
                    .InstancePerDependency()
                    ;
                }

                foreach (var item in blueprint.HttpControllers)
                {
                    var serviceKeyName = (item.AreaName + "/" + item.ControllerName).ToLowerInvariant();
                    var serviceKeyType = item.Type;
                    RegisterType(builder, item)
                    .EnableDynamicProxy(dynamicProxyContext)
                    .Keyed <IHttpController>(serviceKeyName)
                    .Keyed <IHttpController>(serviceKeyType)
                    .WithMetadata("ControllerType", item.Type)
                    .InstancePerDependency();
                }

                // Register code-only registrations specific to a shell
                _shellContainerRegistrations.Registrations(builder);

                var optionalShellByNameConfig = HostingEnvironment.MapPath("~/Config/Sites." + settings.Name + ".config");
                if (File.Exists(optionalShellByNameConfig))
                {
                    builder.RegisterModule(new ConfigurationSettingsReader(ConfigurationSettingsReaderConstants.DefaultSectionName, optionalShellByNameConfig));
                }
                else
                {
                    var optionalShellConfig = HostingEnvironment.MapPath("~/Config/Sites.config");
                    if (File.Exists(optionalShellConfig))
                    {
                        builder.RegisterModule(new ConfigurationSettingsReader(ConfigurationSettingsReaderConstants.DefaultSectionName, optionalShellConfig));
                    }
                }

                var optionalComponentsConfig = HostingEnvironment.MapPath("~/Config/HostComponents.config");
                if (File.Exists(optionalComponentsConfig))
                {
                    builder.RegisterModule(new HostComponentsConfigModule(optionalComponentsConfig));
                }
            }));
        }
Esempio n. 19
0
 private bool CKEditorIngoThaWatchaIsInstalled()
 {
     return(File.Exists(HostingEnvironment.MapPath("~/Providers/HtmlEditorProviders/CKEditor/ckeditor.js")));
 }
Esempio n. 20
0
        /// <summary>
        /// Gets the full path of InstalledPlugins.txt file
        /// </summary>
        /// <returns></returns>
        private static string GetInstalledPluginsFilePath()
        {
            var filePath = HostingEnvironment.MapPath(_installedPluginsFilePath);

            return(filePath);
        }
        protected override void Load(ContainerBuilder builder)
        {
            var configuration = new ConfigurationService();

            builder.RegisterInstance(configuration)
            .AsSelf()
            .As <PoliteCaptcha.IConfigurationSource>();
            builder.Register(c => configuration.Current)
            .AsSelf()
            .As <IAppConfiguration>();

            builder.RegisterInstance(LuceneCommon.GetDirectory(configuration.Current.LuceneIndexLocation))
            .As <Lucene.Net.Store.Directory>()
            .SingleInstance();

            ConfigureSearch(builder, configuration);

            if (!string.IsNullOrEmpty(configuration.Current.AzureStorageConnectionString))
            {
                builder.RegisterInstance(new TableErrorLog(configuration.Current.AzureStorageConnectionString))
                .As <ErrorLog>()
                .SingleInstance();
            }
            else
            {
                builder.RegisterInstance(new SqlErrorLog(configuration.Current.SqlConnectionString))
                .As <ErrorLog>()
                .SingleInstance();
            }

            builder.RegisterType <HttpContextCacheService>()
            .AsSelf()
            .As <ICacheService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <ContentService>()
            .AsSelf()
            .As <IContentService>()
            .SingleInstance();

            builder.Register(c => new EntitiesContext(configuration.Current.SqlConnectionString, readOnly: configuration.Current.ReadOnlyMode))
            .AsSelf()
            .As <IEntitiesContext>()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <User> >()
            .AsSelf()
            .As <IEntityRepository <User> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <CuratedFeed> >()
            .AsSelf()
            .As <IEntityRepository <CuratedFeed> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <CuratedPackage> >()
            .AsSelf()
            .As <IEntityRepository <CuratedPackage> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <PackageRegistration> >()
            .AsSelf()
            .As <IEntityRepository <PackageRegistration> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <Package> >()
            .AsSelf()
            .As <IEntityRepository <Package> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <PackageDependency> >()
            .AsSelf()
            .As <IEntityRepository <PackageDependency> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <PackageStatistics> >()
            .AsSelf()
            .As <IEntityRepository <PackageStatistics> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <Credential> >()
            .AsSelf()
            .As <IEntityRepository <Credential> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <PackageOwnerRequest> >()
            .AsSelf()
            .As <IEntityRepository <PackageOwnerRequest> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <CuratedFeedService>()
            .AsSelf()
            .As <ICuratedFeedService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <UserService>()
            .AsSelf()
            .As <IUserService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <PackageService>()
            .AsSelf()
            .As <IPackageService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <EditPackageService>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder.RegisterType <FormsAuthenticationService>()
            .As <IFormsAuthenticationService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <CookieTempDataProvider>()
            .As <ITempDataProvider>()
            .InstancePerLifetimeScope();

            builder.RegisterType <NuGetExeDownloaderService>()
            .AsSelf()
            .As <INuGetExeDownloaderService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <StatusService>()
            .AsSelf()
            .As <IStatusService>()
            .InstancePerLifetimeScope();

            var mailSenderThunk = new Lazy <IMailSender>(
                () =>
            {
                var settings = configuration;
                if (settings.Current.SmtpUri != null && settings.Current.SmtpUri.IsAbsoluteUri)
                {
                    var smtpUri = new SmtpUri(settings.Current.SmtpUri);

                    var mailSenderConfiguration = new MailSenderConfiguration
                    {
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Host           = smtpUri.Host,
                        Port           = smtpUri.Port,
                        EnableSsl      = smtpUri.Secure
                    };

                    if (!string.IsNullOrWhiteSpace(smtpUri.UserName))
                    {
                        mailSenderConfiguration.UseDefaultCredentials = false;
                        mailSenderConfiguration.Credentials           = new NetworkCredential(
                            smtpUri.UserName,
                            smtpUri.Password);
                    }

                    return(new MailSender(mailSenderConfiguration));
                }
                else
                {
                    var mailSenderConfiguration = new MailSenderConfiguration
                    {
                        DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                        PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
                    };

                    return(new MailSender(mailSenderConfiguration));
                }
            });



            builder.Register(c => mailSenderThunk.Value)
            .AsSelf()
            .As <IMailSender>()
            .InstancePerLifetimeScope();

            builder.RegisterType <MessageService>()
            .AsSelf()
            .As <IMessageService>()
            .InstancePerLifetimeScope();

            builder.Register(c => HttpContext.Current.User)
            .AsSelf()
            .As <IPrincipal>()
            .InstancePerLifetimeScope();

            switch (configuration.Current.StorageType)
            {
            case StorageType.FileSystem:
            case StorageType.NotSpecified:
                ConfigureForLocalFileSystem(builder);
                break;

            case StorageType.AzureStorage:
                ConfigureForAzureStorage(builder, configuration);
                break;
            }

            builder.RegisterType <FileSystemService>()
            .AsSelf()
            .As <IFileSystemService>()
            .SingleInstance();

            builder.RegisterType <PackageFileService>()
            .AsSelf()
            .As <IPackageFileService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <UploadFileService>()
            .AsSelf()
            .As <IUploadFileService>()
            .InstancePerLifetimeScope();

            // todo: bind all package curators by convention
            builder.RegisterType <WebMatrixPackageCurator>()
            .AsSelf()
            .As <IAutomaticPackageCurator>()
            .InstancePerLifetimeScope();

            builder.RegisterType <Windows8PackageCurator>()
            .AsSelf()
            .As <IAutomaticPackageCurator>()
            .InstancePerLifetimeScope();

            // todo: bind all commands by convention
            builder.RegisterType <AutomaticallyCuratePackageCommand>()
            .AsSelf()
            .As <IAutomaticallyCuratePackageCommand>()
            .InstancePerLifetimeScope();

            builder.RegisterType <PackageIdsQuery>()
            .AsSelf()
            .As <IPackageIdsQuery>()
            .InstancePerLifetimeScope();

            builder.RegisterType <PackageVersionsQuery>()
            .AsSelf()
            .As <IPackageVersionsQuery>()
            .InstancePerLifetimeScope();

            builder.RegisterType <DiagnosticsService>()
            .AsSelf()
            .As <IDiagnosticsService>()
            .SingleInstance();
        }
Esempio n. 22
0
 private bool CKEditorDnnConnectIsInstalled()
 {
     return(File.Exists(HostingEnvironment.MapPath("~/Providers/HtmlEditorProviders/DNNConnect.CKE/js/ckeditor/4.5.3/ckeditor.js")));
 }
Esempio n. 23
0
        static WelcomeNewMemberAdaptiveCard()
        {
            var cardJsonFilePath = HostingEnvironment.MapPath("~/Helpers/AdaptiveCards/WelcomeNewMemberAdaptiveCard.json");

            CardTemplate = File.ReadAllText(cardJsonFilePath);
        }
        public ResponseAction PostTwitter(PostToTwitterViewModel message)
        {
            ResponseAction rsp = new ResponseAction();

            rsp.Success = true;
            bool trysended = false;
            List <TwitterAccountPart> TwitterAccountSettings = Twitter_GetAccessToken(message.AccountList);
            var pcr = _providerConfigurationService.Get("Twitter");

            foreach (TwitterAccountPart Faccount in TwitterAccountSettings)
            {
                try {
                    trysended = true;
                    OAuthTokens accesstoken = new OAuthTokens()
                    {
                        AccessToken       = Faccount.UserToken,
                        AccessTokenSecret = Faccount.UserTokenSecret,
                        ConsumerKey       = pcr.ProviderIdKey,
                        ConsumerSecret    = pcr.ProviderSecret
                    };
                    TwitterResponse <TwitterStatus> response;
                    string realmessage = message.Message;
                    if (!string.IsNullOrEmpty(message.Link))
                    {
                        realmessage += " " + message.Link;
                    }
                    if (string.IsNullOrEmpty(message.Picture))
                    {
                        response = TwitterStatus.Update(accesstoken, realmessage.Trim());
                    }
                    else
                    {
                        var mediaPath = HostingEnvironment.IsHosted
                                ? HostingEnvironment.MapPath("~/Media/") ?? ""
                                : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Media");
                        string physicalPath = mediaPath + _shellsettings.Name + "\\" + message.Picture;
                        byte[] photo        = System.IO.File.ReadAllBytes(physicalPath);
                        response = TwitterStatus.UpdateWithMedia(accesstoken, realmessage.Trim(), photo, new StatusUpdateOptions()
                        {
                            UseSSL = true, APIBaseAddress = "http://api.twitter.com/1.1/"
                        });
                    }
                    if (response.Result != RequestResult.Success)
                    {
                        if (response.Content != null)
                        {
                            Logger.Error("response.Content:" + response.Content);
                        }
                        rsp.Success = false;
                        if (response.ErrorMessage != null)
                        {
                            Logger.Error("response.ErrorMessage:" + response.ErrorMessage);
                            _notifier.Add(NotifyType.Error, T("Can't post on twitter: {0} {1}", Faccount.DisplayAs, response.ErrorMessage));
                        }
                        else
                        {
                            var       serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                            var       jsondict   = serializer.Deserialize <Dictionary <string, object> >(response.Content);
                            ArrayList errors     = (ArrayList)jsondict["errors"];
                            foreach (System.Collections.Generic.Dictionary <string, object> error in errors)
                            {
                                string errormsg = "";
                                foreach (var errordict in error)
                                {
                                    errormsg += " " + errordict.Key.ToString() + ":" + errordict.Value.ToString();
                                }
                                _notifier.Add(NotifyType.Error, T("Can't post on twitter: {0} {1}", Faccount.DisplayAs, errormsg));
                            }
                        }
                    }
                } catch (Exception ex) {
                    Logger.Error("Twitter Posting Error Message::" + ex.Message);
                    rsp.Success = false;
                    rsp.Message = "Twitter Posting Error Message: " + ex.Message;
                    _notifier.Add(NotifyType.Error, T("Twitter Posting {0}  Error Message: {1}", Faccount.DisplayAs, ex.Message));
                }
            }
            if (trysended && rsp.Success)
            {
                _notifier.Add(NotifyType.Information, T("Twitter posted"));
            }
            return(rsp);
        }
Esempio n. 25
0
 private string GetRootPath(string path)
 {
     return(Path.IsPathRooted(path) ? path : HostingEnvironment.MapPath(path));
 }
Esempio n. 26
0
 private static FileStream OpenUserDatabase()
 {
     return(new FileStream(HostingEnvironment.MapPath("~/userdb.xml"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None));
 }
Esempio n. 27
0
        public static string Get(string tenant, string key)
        {
            string configFile = HostingEnvironment.MapPath($"~/Tenants/{tenant}/Configs/Frapid.config");

            return(!File.Exists(configFile) ? string.Empty : ConfigurationManager.ReadConfigurationValue(configFile, key));
        }
        public ActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            if (model.DatabaseConnectionString != null)
            {
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();
            }

            //prepare language list
            foreach (var lang in _locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem
                {
                    Value    = Url.Action("ChangeLanguage", "Install", new { language = lang.Code }),
                    Text     = lang.Name,
                    Selected = _locService.GetCurrentLanguage().Code == lang.Code,
                });
            }

            model.DisableSqlCompact       = _config.UseFastInstallationService;
            model.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

            //SQL Server
            if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    //raw connection string
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
                    }

                    try
                    {
                        //try to create connection string
                        new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringWrongFormat"));
                    }
                }
                else
                {
                    //values
                    if (string.IsNullOrEmpty(model.SqlServerName))
                    {
                        ModelState.AddModelError("", _locService.GetResource("SqlServerNameRequired"));
                    }
                    if (string.IsNullOrEmpty(model.SqlDatabaseName))
                    {
                        ModelState.AddModelError("", _locService.GetResource("DatabaseNameRequired"));
                    }

                    //authentication type
                    if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL authentication
                        if (string.IsNullOrEmpty(model.SqlServerUsername))
                        {
                            ModelState.AddModelError("", _locService.GetResource("SqlServerUsernameRequired"));
                        }
                        if (string.IsNullOrEmpty(model.SqlServerPassword))
                        {
                            ModelState.AddModelError("", _locService.GetResource("SqlServerPasswordRequired"));
                        }
                    }
                }
            }


            //Consider granting access rights to the resource to the ASP.NET request identity.
            //ASP.NET has a base process identity
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7,
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>,
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
            var webHelper = EngineContext.Current.Resolve <IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite(webHelper);

            foreach (string dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir));
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite(webHelper);

            foreach (string file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file));
                }
            }

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    string connectionString;
                    if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL Server

                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //raw connection string

                            //we know that MARS option is required when using Entity Framework
                            //let's ensure that it's specified
                            var sqlCsb = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                            if (this.UseMars)
                            {
                                sqlCsb.MultipleActiveResultSets = true;
                            }
                            connectionString = sqlCsb.ToString();
                        }
                        else
                        {
                            //values
                            connectionString = CreateConnectionString(model.SqlAuthenticationType == "windowsauthentication",
                                                                      model.SqlServerName, model.SqlDatabaseName,
                                                                      model.SqlServerUsername, model.SqlServerPassword);
                        }

                        if (model.SqlServerCreateDatabase)
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                //create database
                                var collation             = model.UseCustomCollation ? model.Collation : "";
                                var errorCreatingDatabase = CreateDatabase(connectionString, collation);
                                if (!String.IsNullOrEmpty(errorCreatingDatabase))
                                {
                                    throw new Exception(errorCreatingDatabase);
                                }

                                //Database cannot be created sometimes. Weird! Seems to be Entity Framework issue
                                //that's just wait 5 seconds (3 seconds is not enough for some reasons)
                                Thread.Sleep(5000);
                            }
                        }
                        else
                        {
                            //check whether database exists
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                throw new Exception(_locService.GetResource("DatabaseNotExists"));
                            }
                        }
                    }
                    else
                    {
                        //SQL CE
                        string databaseFileName = "Nop.Db.sdf";
                        string databasePath     = @"|DataDirectory|\" + databaseFileName;
                        connectionString = "Data Source=" + databasePath + ";Persist Security Info=False";

                        //drop database if exists
                        string databaseFullPath = HostingEnvironment.MapPath("~/App_Data/") + databaseFileName;
                        if (System.IO.File.Exists(databaseFullPath))
                        {
                            System.IO.File.Delete(databaseFullPath);
                        }
                    }

                    //save settings
                    var dataProvider = model.DataProvider;
                    var settings     = new DataSettings
                    {
                        DataProvider         = dataProvider,
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    //init data provider
                    var dataProviderInstance = EngineContext.Current.Resolve <BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();


                    //now resolve installation service
                    var installationService = EngineContext.Current.Resolve <IInstallationService>();
                    installationService.InstallData(model.AdminEmail, model.AdminPassword, model.InstallSampleData);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = EngineContext.Current.Resolve <IPluginFinder>();
                    var plugins      = pluginFinder.GetPlugins <IPlugin>(LoadPluginsMode.All)
                                       .ToList()
                                       .OrderBy(x => x.PluginDescriptor.Group)
                                       .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                                       .ToList();
                    var pluginsIgnoredDuringInstallation = String.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation) ?
                                                           new List <string>():
                                                           _config.PluginsIgnoredDuringInstallation
                                                           .Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .Select(x => x.Trim())
                                                           .ToList();
                    foreach (var plugin in plugins)
                    {
                        if (pluginsIgnoredDuringInstallation.Contains(plugin.PluginDescriptor.SystemName))
                        {
                            continue;
                        }
                        plugin.Install();
                    }

                    //register default permissions
                    //var permissionProviders = EngineContext.Current.Resolve<ITypeFinder>().FindClassesOfType<IPermissionProvider>();
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        dynamic provider = Activator.CreateInstance(providerType);
                        EngineContext.Current.Resolve <IPermissionService>().InstallPermissions(provider);
                    }

                    //restart application
                    webHelper.RestartAppDomain();

                    //Redirect to home page
                    return(RedirectToRoute("HomePage"));
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //clear provider settings if something got wrong
                    settingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider         = null,
                        DataConnectionString = null
                    });

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message));
                }
            }
            return(View(model));
        }
Esempio n. 29
0
 public virtual string MapPath(string virtualPath)
 {
     return(HostingEnvironment.MapPath(virtualPath));
 }
Esempio n. 30
0
        /// <summary>
        /// Initialize
        /// </summary>
        public static void Initialize()
        {
            return;

            using (new WriteLockDisposable(Locker))
            {
                // TODO: Add verbose exception handling / raising here since this is happening on app startup and could
                // prevent app from starting altogether
                var pluginFolder = new DirectoryInfo(HostingEnvironment.MapPath(_pluginsPath));
                _shadowCopyFolder = new DirectoryInfo(HostingEnvironment.MapPath(_shadowCopyPath));

                var referencedPlugins   = new List <PluginDescriptor>();
                var incompatiblePlugins = new List <string>();

                _clearShadowDirectoryOnStartup = !String.IsNullOrEmpty(ConfigurationManager.AppSettings["ClearPluginsShadowDirectoryOnStartup"]) &&
                                                 Convert.ToBoolean(ConfigurationManager.AppSettings["ClearPluginsShadowDirectoryOnStartup"]);

                try
                {
                    var installedPluginSystemNames = PluginFileParser.ParseInstalledPluginsFile(GetInstalledPluginsFilePath());

                    Debug.WriteLine("Creating shadow copy folder and querying for dlls");
                    //ensure folders are created
                    Directory.CreateDirectory(pluginFolder.FullName);
                    Directory.CreateDirectory(_shadowCopyFolder.FullName);

                    //get list of all files in bin
                    var binFiles = _shadowCopyFolder.GetFiles("*", SearchOption.AllDirectories);
                    if (_clearShadowDirectoryOnStartup)
                    {
                        //clear out shadow copied plugins
                        foreach (var f in binFiles)
                        {
                            Debug.WriteLine("Deleting " + f.Name);
                            try
                            {
                                File.Delete(f.FullName);
                            }
                            catch (Exception exc)
                            {
                                Debug.WriteLine("Error deleting file " + f.Name + ". Exception: " + exc);
                            }
                        }
                    }

                    //load description files
                    foreach (var dfd in GetDescriptionFilesAndDescriptors(pluginFolder))
                    {
                        var descriptionFile  = dfd.Key;
                        var pluginDescriptor = dfd.Value;

                        //ensure that version of plugin is valid
                        if (!pluginDescriptor.SupportedVersions.Contains(OceanVersion.CurrentVersion, StringComparer.InvariantCultureIgnoreCase))
                        {
                            incompatiblePlugins.Add(pluginDescriptor.SystemName);
                            continue;
                        }

                        //some validation
                        if (String.IsNullOrWhiteSpace(pluginDescriptor.SystemName))
                        {
                            throw new Exception(string.Format("A plugin '{0}' has no system name. Try assigning the plugin a unique name and recompiling.", descriptionFile.FullName));
                        }
                        if (referencedPlugins.Contains(pluginDescriptor))
                        {
                            throw new Exception(string.Format("A plugin with '{0}' system name is already defined", pluginDescriptor.SystemName));
                        }

                        //set 'Installed' property
                        pluginDescriptor.Installed = installedPluginSystemNames
                                                     .ToList()
                                                     .Where(x => x.Equals(pluginDescriptor.SystemName, StringComparison.InvariantCultureIgnoreCase))
                                                     .FirstOrDefault() != null;

                        try
                        {
                            //get list of all DLLs in plugins (not in bin!)
                            var pluginFiles = descriptionFile.Directory.GetFiles("*.dll", SearchOption.AllDirectories)
                                              //just make sure we're not registering shadow copied plugins
                                              .Where(x => !binFiles.Select(q => q.FullName).Contains(x.FullName))
                                              .Where(x => IsPackagePluginFolder(x.Directory))
                                              .ToList();

                            //other plugin description info
                            var mainPluginFile = pluginFiles.Where(x => x.Name.Equals(pluginDescriptor.PluginFileName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                            pluginDescriptor.OriginalAssemblyFile = mainPluginFile;

                            //shadow copy main plugin file
                            pluginDescriptor.ReferencedAssembly = PerformFileDeploy(mainPluginFile);

                            //load all other referenced assemblies now
                            foreach (var plugin in pluginFiles
                                     .Where(x => !x.Name.Equals(mainPluginFile.Name, StringComparison.InvariantCultureIgnoreCase))
                                     .Where(x => !IsAlreadyLoaded(x)))
                            {
                                PerformFileDeploy(plugin);
                            }

                            //init plugin type (only one plugin per assembly is allowed)
                            foreach (var t in pluginDescriptor.ReferencedAssembly.GetTypes())
                            {
                                if (typeof(IPlugin).IsAssignableFrom(t))
                                {
                                    if (!t.IsInterface)
                                    {
                                        if (t.IsClass && !t.IsAbstract)
                                        {
                                            pluginDescriptor.PluginType = t;
                                            break;
                                        }
                                    }
                                }
                            }

                            referencedPlugins.Add(pluginDescriptor);
                        }
                        catch (ReflectionTypeLoadException ex)
                        {
                            var msg = string.Empty;
                            foreach (var e in ex.LoaderExceptions)
                            {
                                msg += e.Message + Environment.NewLine;
                            }

                            var fail = new Exception(msg, ex);
                            Debug.WriteLine(fail.Message, fail);

                            throw fail;
                        }
                    }
                }
                catch (Exception ex)
                {
                    var msg = string.Empty;
                    for (var e = ex; e != null; e = e.InnerException)
                    {
                        msg += e.Message + Environment.NewLine;
                    }

                    var fail = new Exception(msg, ex);
                    Debug.WriteLine(fail.Message, fail);

                    throw fail;
                }

                ReferencedPlugins   = referencedPlugins;
                IncompatiblePlugins = incompatiblePlugins;
            }
        }
Esempio n. 31
0
        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static IDependencyResolver RegisterTypes(IUnityContainer container)
        {
            IDependencyResolver resolver = container.Initialize <UnityConfig, WebAPICurrentIdentity>(string.Empty, string.Empty,
                                                                                                     WebApiConfiguration.ServiceBusConnectionString, HostingEnvironment.MapPath(WebApiConfiguration.MESSAGE_CONFIGURATION_FILE_PATH),
                                                                                                     WebApiConfiguration.CustomInstanceName,
                                                                                                     WebApiConfiguration.AutoDeleteOnIdle, WebApiConfiguration.DefaultMessageTimeToLive, WebApiConfiguration.LockDuration,
                                                                                                     WebApiConfiguration.MaxDeliveryCount);

            IDataUnitOfWork unitOfWork = (IDataUnitOfWork)resolver.BeginScope().GetService(typeof(IDataUnitOfWork));

            Security.ISecurity security = (Security.ISecurity)resolver.BeginScope().GetService(typeof(Security.ISecurity));
            container.RegisterInstance(AutoMapperConfig.RegisterMappings(unitOfWork, security));
            return(resolver);
        }
Esempio n. 32
0
        private Site ConfigureSite(IApp app)
        {
            #region Preconditions

            if (app == null)
                throw new ArgumentNullException(nameof(app));

            #endregion

            var physicalPath = GetAppPath(app);

            var site = serverManager.Sites.CreateElement();

            site.Id              = app.Id;
            site.Name            = app.Name.ToString(); // id?

            site.ServerAutoStart = true;                            // Start the server automatically
            site.LogFile.Enabled = false;                           // Disable site logging

            var siteApp = site.Applications.CreateElement();        // Create a site app

            siteApp.Path = "/";                                     // Site the root path
            siteApp.ApplicationPoolName = app.Name.ToString();      // Site the pool name

            site.Applications.Add(siteApp);

            // Create a virtual directory
            var virtualDirectory = siteApp.VirtualDirectories.CreateElement();

            virtualDirectory.Path = "/";
            virtualDirectory.PhysicalPath = physicalPath.ToString();

            siteApp.VirtualDirectories.Add(virtualDirectory);

            // env
            // { 
            //   listeners: [ "80/http", "http://carbon.com:8080" ]
            // }

            JsonObject env = null;

            if (app is App)
            {
                env = ((App)app).Env;
            }

            if (env == null)
            {

                Console.WriteLine("no env");
            }

            if (env != null && env.ContainsKey("listeners"))
            {
                foreach (var listener in (JsonArray)env["listeners"])
                {
                    var b = new WebBinding(Listener.Parse(listener));

                    var binding = site.Bindings.CreateElement();

                    binding.Protocol = b.Protocol;
                    binding.BindingInformation = b.ToString();

                    site.Bindings.Add(binding);
                }
            }
            else
            {
                Console.WriteLine("no listeners");
            }
            
            return site;
        }
        protected override void Initialize()
        {
            bool     enableLocalization               = true;
            string   absoluteFileName                 = HostingEnvironment.MapPath("~/Mvc.sitemap");
            TimeSpan absoluteCacheExpiration          = TimeSpan.FromMinutes(5);
            bool     visibilityAffectsDescendants     = true;
            bool     useTitleIfDescriptionNotProvided = true;



            bool securityTrimmingEnabled = false;

            string[] includeAssembliesForScan = new string[] { "MvcDemos" };


            var currentAssembly             = this.GetType().Assembly;
            var siteMapProviderAssembly     = typeof(SiteMaps).Assembly;
            var allAssemblies               = new Assembly[] { currentAssembly, siteMapProviderAssembly };
            var excludeTypes                = new Type[] {
// Use this array to add types you wish to explicitly exclude from convention-based
// auto-registration. By default all types that either match I[TypeName] = [TypeName] or
// I[TypeName] = [TypeName]Adapter will be automatically wired up as long as they don't
// have the [ExcludeFromAutoRegistrationAttribute].
//
// If you want to override a type that follows the convention, you should add the name
// of either the implementation name or the interface that it inherits to this list and
// add your manual registration code below. This will prevent duplicate registrations
// of the types from occurring.

// Example:
// typeof(SiteMap),
// typeof(SiteMapNodeVisibilityProviderStrategy)
            };
            var multipleImplementationTypes = new Type[] {
                typeof(ISiteMapNodeUrlResolver),
                typeof(ISiteMapNodeVisibilityProvider),
                typeof(IDynamicNodeProvider)
            };

// Matching type name (I[TypeName] = [TypeName]) or matching type name + suffix Adapter (I[TypeName] = [TypeName]Adapter)
// and not decorated with the [ExcludeFromAutoRegistrationAttribute].
            CommonConventions.RegisterDefaultConventions(
                (interfaceType, implementationType) => this.Container.RegisterType(interfaceType, implementationType, new ContainerControlledLifetimeManager()),
                new Assembly[] { siteMapProviderAssembly },
                allAssemblies,
                excludeTypes,
                string.Empty);

// Multiple implementations of strategy based extension points (and not decorated with [ExcludeFromAutoRegistrationAttribute]).
            CommonConventions.RegisterAllImplementationsOfInterface(
                (interfaceType, implementationType) => this.Container.RegisterType(interfaceType, implementationType, implementationType.Name, new ContainerControlledLifetimeManager()),
                multipleImplementationTypes,
                allAssemblies,
                excludeTypes,
                string.Empty);

// TODO: Find a better way to inject an array constructor

// Url Resolvers
            this.Container.RegisterType <ISiteMapNodeUrlResolverStrategy, SiteMapNodeUrlResolverStrategy>(new InjectionConstructor(
                                                                                                              new ResolvedArrayParameter <ISiteMapNodeUrlResolver>(this.Container.ResolveAll <ISiteMapNodeUrlResolver>().ToArray())
                                                                                                              ));

// Visibility Providers
            this.Container.RegisterType <ISiteMapNodeVisibilityProviderStrategy, SiteMapNodeVisibilityProviderStrategy>(new InjectionConstructor(
                                                                                                                            new ResolvedArrayParameter <ISiteMapNodeVisibilityProvider>(this.Container.ResolveAll <ISiteMapNodeVisibilityProvider>().ToArray()),
                                                                                                                            new InjectionParameter <string>(string.Empty)
                                                                                                                            ));

// Dynamic Node Providers
            this.Container.RegisterType <IDynamicNodeProviderStrategy, DynamicNodeProviderStrategy>(new InjectionConstructor(
                                                                                                        new ResolvedArrayParameter <IDynamicNodeProvider>(this.Container.ResolveAll <IDynamicNodeProvider>().ToArray())
                                                                                                        ));


// Pass in the global controllerBuilder reference
            this.Container.RegisterInstance <ControllerBuilder>(ControllerBuilder.Current);

            this.Container.RegisterType <IControllerTypeResolverFactory, ControllerTypeResolverFactory>(new InjectionConstructor(
                                                                                                            new List <string>(),
                                                                                                            new ResolvedParameter <IControllerBuilder>(),
                                                                                                            new ResolvedParameter <IBuildManager>()));

// Configure Security

// IMPORTANT: Must give arrays of object a name in Unity in order for it to resolve them.
            this.Container.RegisterType <IAclModule, AuthorizeAttributeAclModule>("authorizeAttribute");
            this.Container.RegisterType <IAclModule, XmlRolesAclModule>("xmlRoles");
            this.Container.RegisterType <IAclModule, CompositeAclModule>(new InjectionConstructor(new ResolvedArrayParameter <IAclModule>(
                                                                                                      new ResolvedParameter <IAclModule>("authorizeAttribute"),
                                                                                                      new ResolvedParameter <IAclModule>("xmlRoles"))));



            this.Container.RegisterInstance <System.Runtime.Caching.ObjectCache>(System.Runtime.Caching.MemoryCache.Default);
            this.Container.RegisterType(typeof(ICacheProvider <>), typeof(RuntimeCacheProvider <>));
            this.Container.RegisterType <ICacheDependency, RuntimeFileCacheDependency>(
                "cacheDependency", new InjectionConstructor(absoluteFileName));

            this.Container.RegisterType <ICacheDetails, CacheDetails>("cacheDetails",
                                                                      new InjectionConstructor(absoluteCacheExpiration, TimeSpan.MinValue, new ResolvedParameter <ICacheDependency>("cacheDependency")));

// Configure the visitors
            this.Container.RegisterType <ISiteMapNodeVisitor, UrlResolvingSiteMapNodeVisitor>();

// Prepare for the sitemap node providers
            this.Container.RegisterType <IXmlSource, FileXmlSource>("file1XmlSource", new InjectionConstructor(absoluteFileName));
            this.Container.RegisterType <IReservedAttributeNameProvider, ReservedAttributeNameProvider>(new InjectionConstructor(new List <string>()));

// IMPORTANT: Must give arrays of object a name in Unity in order for it to resolve them.
// Register the sitemap node providers
            this.Container.RegisterInstance <ISiteMapNodeProvider>("xmlSiteMapNodeProvider1",
                                                                   this.Container.Resolve <XmlSiteMapNodeProviderFactory>().Create(this.Container.Resolve <IXmlSource>("file1XmlSource")), new ContainerControlledLifetimeManager());
            this.Container.RegisterInstance <ISiteMapNodeProvider>("reflectionSiteMapNodeProvider1",
                                                                   this.Container.Resolve <ReflectionSiteMapNodeProviderFactory>().Create(includeAssembliesForScan), new ContainerControlledLifetimeManager());
            this.Container.RegisterType <ISiteMapNodeProvider, CompositeSiteMapNodeProvider>(new InjectionConstructor(new ResolvedArrayParameter <ISiteMapNodeProvider>(
                                                                                                                          new ResolvedParameter <ISiteMapNodeProvider>("xmlSiteMapNodeProvider1"),
                                                                                                                          new ResolvedParameter <ISiteMapNodeProvider>("reflectionSiteMapNodeProvider1"))));

// Configure the builders
            this.Container.RegisterType <ISiteMapBuilder, SiteMapBuilder>();

// Configure the builder sets
            this.Container.RegisterType <ISiteMapBuilderSet, SiteMapBuilderSet>("builderSet1",
                                                                                new InjectionConstructor(
                                                                                    "default",
                                                                                    securityTrimmingEnabled,
                                                                                    enableLocalization,
                                                                                    visibilityAffectsDescendants,
                                                                                    useTitleIfDescriptionNotProvided,
                                                                                    new ResolvedParameter <ISiteMapBuilder>(),
                                                                                    new ResolvedParameter <ICacheDetails>("cacheDetails")));

            this.Container.RegisterType <ISiteMapBuilderSetStrategy, SiteMapBuilderSetStrategy>(new InjectionConstructor(
                                                                                                    new ResolvedArrayParameter <ISiteMapBuilderSet>(new ResolvedParameter <ISiteMapBuilderSet>("builderSet1"))));
        }
Esempio n. 34
0
        public static UploadFileResult UploadFile(HttpPostedFileBase file, string uploadFolderPath, ILocalizationService localizationService, bool onlyImages = false)
        {
            var upResult = new UploadFileResult {
                UploadSuccessful = true
            };
            const string imageExtensions = "jpg,jpeg,png,gif";
            var          fileName        = Path.GetFileName(file.FileName);

            if (fileName != null)
            {
                // Lower case
                fileName = fileName.ToLower();

                // Get the file extension
                var fileExtension = Path.GetExtension(fileName.ToLower());

                //Before we do anything, check file size
                if (file.ContentLength > Convert.ToInt32(SiteConstants.FileUploadMaximumFileSizeInBytes))
                {
                    //File is too big
                    upResult.UploadSuccessful = false;
                    upResult.ErrorMessage     = localizationService.GetResourceString("Post.UploadFileTooBig");
                    return(upResult);
                }

                // now check allowed extensions
                var allowedFileExtensions = SiteConstants.FileUploadAllowedExtensions;

                if (onlyImages)
                {
                    allowedFileExtensions = imageExtensions;
                }

                if (!string.IsNullOrEmpty(allowedFileExtensions))
                {
                    // Turn into a list and strip unwanted commas as we don't trust users!
                    var allowedFileExtensionsList = allowedFileExtensions.ToLower().Trim()
                                                    .TrimStart(',').TrimEnd(',').Split(',').ToList();


                    // If can't work out extension then just error
                    if (string.IsNullOrEmpty(fileExtension))
                    {
                        upResult.UploadSuccessful = false;
                        upResult.ErrorMessage     = localizationService.GetResourceString("Errors.GenericMessage");
                        return(upResult);
                    }

                    // Remove the dot then check against the extensions in the web.config settings
                    fileExtension = fileExtension.TrimStart('.');
                    if (!allowedFileExtensionsList.Contains(fileExtension))
                    {
                        upResult.UploadSuccessful = false;
                        upResult.ErrorMessage     = localizationService.GetResourceString("Post.UploadBannedFileExtension");
                        return(upResult);
                    }
                }

                // Store these here as we may change the values within the image manipulation
                var newFileName = string.Empty;
                var path        = string.Empty;

                if (imageExtensions.Split(',').ToList().Contains(fileExtension))
                {
                    // Rotate image if wrong want around
                    using (var sourceimage = Image.FromStream(file.InputStream))
                    {
                        if (sourceimage.PropertyIdList.Contains(0x0112))
                        {
                            int rotationValue = sourceimage.GetPropertyItem(0x0112).Value[0];
                            switch (rotationValue)
                            {
                            case 1:     // landscape, do nothing
                                break;

                            case 8:     // rotated 90 right
                                // de-rotate:
                                sourceimage.RotateFlip(RotateFlipType.Rotate270FlipNone);
                                break;

                            case 3:     // bottoms up
                                sourceimage.RotateFlip(RotateFlipType.Rotate180FlipNone);
                                break;

                            case 6:     // rotated 90 left
                                sourceimage.RotateFlip(RotateFlipType.Rotate90FlipNone);
                                break;
                            }
                        }

                        using (var stream = new MemoryStream())
                        {
                            // Save the image as a Jpeg only
                            sourceimage.Save(stream, ImageFormat.Jpeg);
                            stream.Position = 0;

                            // Change the extension to jpg as that's what we are saving it as
                            fileName = fileName.Replace(fileExtension, "");
                            fileName = string.Concat(fileName, "jpg");
                            file     = new MemoryFile(stream, "image/jpeg", fileName);

                            // Sort the file name
                            newFileName = CreateNewFileName(fileName);
                            path        = Path.Combine(uploadFolderPath, newFileName);

                            // Save the file to disk
                            file.SaveAs(path);
                        }
                    }
                }
                else
                {
                    // Sort the file name
                    newFileName = CreateNewFileName(fileName);
                    path        = Path.Combine(uploadFolderPath, newFileName);

                    // Save the file to disk
                    file.SaveAs(path);
                }



                var hostingRoot = HostingEnvironment.MapPath("~/") ?? "";
                var fileUrl     = path.Substring(hostingRoot.Length).Replace('\\', '/').Insert(0, "/");

                upResult.UploadedFileName = newFileName;
                upResult.UploadedFileUrl  = fileUrl;
            }

            return(upResult);
        }
Esempio n. 35
0
 public SupplierIndexModel(ApplicationDbContext context, HostingEnvironment hostingEnvironment)
 {
     _context            = context;
     _hostingEnvironment = hostingEnvironment;
 }
Esempio n. 36
0
        protected override void Load(ContainerBuilder builder)
        {
            var diagnosticsService = new DiagnosticsService();

            builder.RegisterInstance(diagnosticsService)
            .AsSelf()
            .As <IDiagnosticsService>()
            .SingleInstance();

            var configuration = new ConfigurationService(new SecretReaderFactory(diagnosticsService));

            builder.RegisterInstance(configuration)
            .AsSelf()
            .As <PoliteCaptcha.IConfigurationSource>();

            builder.RegisterInstance(configuration)
            .AsSelf()
            .As <IGalleryConfigurationService>();

            builder.Register(c => configuration.Current)
            .AsSelf()
            .As <IAppConfiguration>();

            // Force the read of this configuration, so it will be initialized on startup
            builder.Register(c => configuration.Features)
            .AsSelf()
            .As <FeatureConfiguration>();

            builder.RegisterType <TelemetryService>().As <ITelemetryService>().SingleInstance();
            builder.RegisterType <CredentialBuilder>().As <ICredentialBuilder>().SingleInstance();
            builder.RegisterType <CredentialValidator>().As <ICredentialValidator>().SingleInstance();

            builder.RegisterInstance(LuceneCommon.GetDirectory(configuration.Current.LuceneIndexLocation))
            .As <Lucene.Net.Store.Directory>()
            .SingleInstance();

            ConfigureSearch(builder, configuration);

            if (!string.IsNullOrEmpty(configuration.Current.AzureStorageConnectionString))
            {
                builder.RegisterInstance(new TableErrorLog(configuration.Current.AzureStorageConnectionString))
                .As <ErrorLog>()
                .SingleInstance();
            }
            else
            {
                builder.RegisterInstance(new SqlErrorLog(configuration.Current.SqlConnectionString))
                .As <ErrorLog>()
                .SingleInstance();
            }

            builder.RegisterType <DateTimeProvider>().AsSelf().As <IDateTimeProvider>().SingleInstance();

            builder.RegisterType <HttpContextCacheService>()
            .AsSelf()
            .As <ICacheService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <ContentService>()
            .AsSelf()
            .As <IContentService>()
            .SingleInstance();

            builder.Register(c => new EntitiesContext(configuration.Current.SqlConnectionString, readOnly: configuration.Current.ReadOnlyMode))
            .AsSelf()
            .As <IEntitiesContext>()
            .As <DbContext>()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <User> >()
            .AsSelf()
            .As <IEntityRepository <User> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <CuratedFeed> >()
            .AsSelf()
            .As <IEntityRepository <CuratedFeed> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <CuratedPackage> >()
            .AsSelf()
            .As <IEntityRepository <CuratedPackage> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <PackageRegistration> >()
            .AsSelf()
            .As <IEntityRepository <PackageRegistration> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <Package> >()
            .AsSelf()
            .As <IEntityRepository <Package> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <PackageDependency> >()
            .AsSelf()
            .As <IEntityRepository <PackageDependency> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <PackageDelete> >()
            .AsSelf()
            .As <IEntityRepository <PackageDelete> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <Credential> >()
            .AsSelf()
            .As <IEntityRepository <Credential> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityRepository <PackageOwnerRequest> >()
            .AsSelf()
            .As <IEntityRepository <PackageOwnerRequest> >()
            .InstancePerLifetimeScope();

            builder.RegisterType <CuratedFeedService>()
            .AsSelf()
            .As <ICuratedFeedService>()
            .InstancePerLifetimeScope();

            builder.Register(c => new SupportRequestDbContext(configuration.Current.SqlConnectionStringSupportRequest))
            .AsSelf()
            .As <ISupportRequestDbContext>()
            .InstancePerLifetimeScope();

            builder.RegisterType <SupportRequestService>()
            .AsSelf()
            .As <ISupportRequestService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <UserService>()
            .AsSelf()
            .As <IUserService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <PackageNamingConflictValidator>()
            .AsSelf()
            .As <IPackageNamingConflictValidator>()
            .InstancePerLifetimeScope();

            builder.RegisterType <PackageService>()
            .AsSelf()
            .As <IPackageService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <PackageDeleteService>()
            .AsSelf()
            .As <IPackageDeleteService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <EditPackageService>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder.RegisterType <FormsAuthenticationService>()
            .As <IFormsAuthenticationService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <CookieTempDataProvider>()
            .As <ITempDataProvider>()
            .InstancePerLifetimeScope();

            builder.RegisterType <NuGetExeDownloaderService>()
            .AsSelf()
            .As <INuGetExeDownloaderService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <StatusService>()
            .AsSelf()
            .As <IStatusService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <SecurityPolicyService>()
            .AsSelf()
            .As <ISecurityPolicyService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <SecurePushSubscription>()
            .SingleInstance();

            builder.RegisterType <RequireSecurePushForCoOwnersPolicy>()
            .SingleInstance();

            var mailSenderThunk = new Lazy <IMailSender>(
                () =>
            {
                var settings = configuration;
                if (settings.Current.SmtpUri != null && settings.Current.SmtpUri.IsAbsoluteUri)
                {
                    var smtpUri = new SmtpUri(settings.Current.SmtpUri);

                    var mailSenderConfiguration = new MailSenderConfiguration
                    {
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Host           = smtpUri.Host,
                        Port           = smtpUri.Port,
                        EnableSsl      = smtpUri.Secure
                    };

                    if (!string.IsNullOrWhiteSpace(smtpUri.UserName))
                    {
                        mailSenderConfiguration.UseDefaultCredentials = false;
                        mailSenderConfiguration.Credentials           = new NetworkCredential(
                            smtpUri.UserName,
                            smtpUri.Password);
                    }

                    return(new MailSender(mailSenderConfiguration));
                }
                else
                {
                    var mailSenderConfiguration = new MailSenderConfiguration
                    {
                        DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                        PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
                    };

                    return(new MailSender(mailSenderConfiguration));
                }
            });

            builder.Register(c => mailSenderThunk.Value)
            .AsSelf()
            .As <IMailSender>()
            .InstancePerLifetimeScope();

            builder.RegisterType <MessageService>()
            .AsSelf()
            .As <IMessageService>()
            .InstancePerLifetimeScope();

            builder.Register(c => HttpContext.Current.User)
            .AsSelf()
            .As <IPrincipal>()
            .InstancePerLifetimeScope();

            IAuditingService defaultAuditingService = null;

            switch (configuration.Current.StorageType)
            {
            case StorageType.FileSystem:
            case StorageType.NotSpecified:
                ConfigureForLocalFileSystem(builder, configuration);
                defaultAuditingService = GetAuditingServiceForLocalFileSystem(configuration);
                break;

            case StorageType.AzureStorage:
                ConfigureForAzureStorage(builder, configuration);
                defaultAuditingService = GetAuditingServiceForAzureStorage(configuration);
                break;
            }

            RegisterAuditingServices(builder, defaultAuditingService);

            builder.RegisterType <FileSystemService>()
            .AsSelf()
            .As <IFileSystemService>()
            .SingleInstance();

            builder.RegisterType <PackageFileService>()
            .AsSelf()
            .As <IPackageFileService>()
            .InstancePerLifetimeScope();

            builder.RegisterType <UploadFileService>()
            .AsSelf()
            .As <IUploadFileService>()
            .InstancePerLifetimeScope();

            // todo: bind all package curators by convention
            builder.RegisterType <WebMatrixPackageCurator>()
            .AsSelf()
            .As <IAutomaticPackageCurator>()
            .InstancePerLifetimeScope();

            builder.RegisterType <Windows8PackageCurator>()
            .AsSelf()
            .As <IAutomaticPackageCurator>()
            .InstancePerLifetimeScope();

            // todo: bind all commands by convention
            builder.RegisterType <AutomaticallyCuratePackageCommand>()
            .AsSelf()
            .As <IAutomaticallyCuratePackageCommand>()
            .InstancePerLifetimeScope();

            if (configuration.Current.Environment == Constants.DevelopmentEnvironment)
            {
                builder.RegisterType <AllowLocalHttpRedirectPolicy>()
                .As <ISourceDestinationRedirectPolicy>()
                .InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <NoLessSecureDestinationRedirectPolicy>()
                .As <ISourceDestinationRedirectPolicy>()
                .InstancePerLifetimeScope();
            }

            ConfigureAutocomplete(builder, configuration);
        }
        /// <summary>
        /// Automatically creates a database for the template if it doesn't already exists.
        /// You might delete this method to disable auto create functionality.
        /// </summary>
        private static void EnsureDatabase(string databaseKey)
        {
            var cs = SqlConnections.GetConnectionString(databaseKey);

            if (cs.Dialect.GetType() == typeof(OracleDialect))
            {
                return;
            }

            var cb = cs.ProviderFactory.CreateConnectionStringBuilder();

            cb.ConnectionString = cs.ConnectionString;

            string catalogKey = "?";

            foreach (var ck in new[] { "Initial Catalog", "Database", "AttachDBFilename" })
            {
                if (cb.ContainsKey(ck))
                {
                    catalogKey = ck;
                    break;
                }
            }

            var catalog = cb[catalogKey] as string;

            cb[catalogKey] = null;

            using (var serverConnection = SqlConnections.New(cb.ConnectionString, cs.ProviderName))
            {
                try
                {
                    serverConnection.Open();
                }
                catch (SqlException ex)
                {
                    if (ex.ErrorCode != -2146232060)
                    {
                        throw;
                    }

                    const string oldVer = @"\v11.0";

                    if (cb.ConnectionString.IndexOf(oldVer) >= 0)
                    {
                        throw new Exception(
                                  "You don't seem to have SQL Express LocalDB 2012 installed.\r\n\r\n" +
                                  "If you have Visual Studio 2015 (with SQL LocalDB 2014) " +
                                  "try changing '" + databaseKey + "' connection string in WEB.CONFIG to:\r\n\r\n" +
                                  cs.ConnectionString.Replace(oldVer, @"\MSSqlLocalDB") + "\r\n\r\nor:\r\n\r\n" +
                                  cs.ConnectionString.Replace(oldVer, @"\v12.0") + "';\r\n\r\n" +
                                  "You can also try another SQL server type like .\\SQLExpress.");
                    }

                    throw;
                }

                string databasesQuery      = "SELECT * FROM sys.databases WHERE NAME = @name";
                string createDatabaseQuery = @"CREATE DATABASE [{0}]";

                if (String.Equals(cs.ProviderName, "npgsql", StringComparison.OrdinalIgnoreCase))
                {
                    databasesQuery      = "select * from postgres.pg_catalog.pg_database where datname = @name";
                    createDatabaseQuery = "CREATE DATABASE \"{0}\"";
                }

                if (String.Equals(cs.ProviderName, "MySql.Data.MySqlClient", StringComparison.OrdinalIgnoreCase))
                {
                    databasesQuery      = "SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @name";
                    createDatabaseQuery = "CREATE DATABASE `{0}`";
                }

                if (serverConnection.Query(databasesQuery, new { name = catalog }).Any())
                {
                    return;
                }

                var isLocalServer = serverConnection.ConnectionString.IndexOf(@"(localdb)\", StringComparison.OrdinalIgnoreCase) >= 0 ||
                                    serverConnection.ConnectionString.IndexOf(@".\") >= 0;

                string command;
                if (isLocalServer)
                {
                    var filename = Path.Combine(HostingEnvironment.MapPath("~/App_Data"), catalog);
                    command = String.Format(@"CREATE DATABASE [{0}] ON PRIMARY (Name = N'{0}', FILENAME = '{1}.mdf') LOG ON (NAME = N'{0}_log', FILENAME = '{1}.ldf')",
                                            catalog, filename);

                    if (File.Exists(filename + ".mdf"))
                    {
                        command += " FOR ATTACH";
                    }
                }
                else
                {
                    command = String.Format(createDatabaseQuery, catalog);
                }

                serverConnection.Execute(command);
                SqlConnection.ClearAllPools();
            }
        }
Esempio n. 38
0
        public void StartupLoaderCanLoadByType()
        {
            var serviceCollection = new ServiceCollection();
            var services = serviceCollection.BuildServiceProvider();

            var diagnosticMessages = new List<string>();
            var hostingEnv = new HostingEnvironment();
            var loader = new StartupLoader(services, hostingEnv);
            var startup = loader.LoadMethods(typeof(TestStartup), diagnosticMessages);

            var app = new ApplicationBuilder(services);
            app.ApplicationServices = startup.ConfigureServicesDelegate(serviceCollection);
            startup.ConfigureDelegate(app);

            var foo = app.ApplicationServices.GetRequiredService<SimpleService>();
            Assert.Equal("Configure", foo.Message);
        }
        public bool Post([FromBody] Komentar k)
        {
            Korisnik user = (Korisnik)HttpContext.Current.Session["user"];

            if (user == null)
            {
                user = new Korisnik();
                HttpContext.Current.Session["user"] = user;
            }

            Korisnici users  = HttpContext.Current.Application["korisnici"] as Korisnici;
            Voznje    voznje = HttpContext.Current.Application["voznje"] as Voznje;

            foreach (Korisnik korisnik in users.korisnici)
            {
                if (korisnik.KorisnickoIme == user.KorisnickoIme)
                {
                    foreach (Voznja ride in korisnik.voznjeKorisnika)
                    {
                        if (ride.IdVoznje == k.IdVoznje)
                        {
                            ride.Komentar.IdVoznje      = k.IdVoznje;
                            ride.Komentar.DatumObjave   = DateTime.UtcNow;
                            ride.Komentar.KorisnickoIme = user.KorisnickoIme;
                            ride.Komentar.OcenaVoznje   = k.OcenaVoznje;
                            ride.Komentar.Opis          = k.Opis;

                            //string path = @"C:\Users\Coa\Desktop\NovaVerzija\WebAPI\WebAPI\App_Data\voznje.txt";
                            string path = "~/App_Data/voznje.txt";
                            path = HostingEnvironment.MapPath(path);

                            string line = String.Empty;

                            line = ride.IdVoznje.ToString() + '|' + ride.VremePorudzbine.ToString() + '|' + ride.LokacijaDolaskaTaksija.X + '|' + ride.LokacijaDolaskaTaksija.Y + '|' +
                                   ride.LokacijaDolaskaTaksija.Adresa.UlicaBroj + '|' + ride.LokacijaDolaskaTaksija.Adresa.NaseljenoMesto + '|' + ride.LokacijaDolaskaTaksija.Adresa.PozivniBroj + '|' + ride.Automobil + '|' +
                                   ride.Musterija + '|' + ride.Odrediste.X + '|' + ride.Odrediste.Y + '|' + ride.Odrediste.Adresa.UlicaBroj + '|' + ride.Odrediste.Adresa.NaseljenoMesto + '|' + ride.Odrediste.Adresa.PozivniBroj + '|' +
                                   ride.Dispecer + '|' + ride.Vozac + '|' + ride.Iznos + '|' + ride.Komentar.Opis + '|' + ride.Komentar.DatumObjave + '|' + ride.Komentar.KorisnickoIme + '|' +
                                   ride.Komentar.OcenaVoznje + '|' + ride.Status + '|' + Environment.NewLine;

                            string[] arrLine = File.ReadAllLines(path);
                            arrLine[ride.IdVoznje] = line;
                            File.WriteAllLines(path, arrLine);
                            File.WriteAllLines(path, File.ReadAllLines(path).Where(l => !string.IsNullOrWhiteSpace(l)));

                            foreach (Korisnik kor in users.korisnici)
                            {
                                if (kor.KorisnickoIme == ride.Musterija)
                                {
                                    foreach (Voznja voznja in kor.voznjeKorisnika)
                                    {
                                        if (voznja.IdVoznje == ride.IdVoznje)
                                        {
                                            voznja.Komentar = ride.Komentar;
                                        }
                                    }
                                }
                            }

                            Voznje voznje2 = new Voznje("~/App_Data/voznje.txt");
                            HttpContext.Current.Application["voznje"] = voznje2;

                            HttpContext.Current.Application["korisnici"] = users;

                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
        /// <summary>
        /// Gets the log files from the default log file directory
        /// </summary>
        /// <returns>A collection of log file items</returns>
        public IEnumerable <LogFileItem> GetLogFiles()
        {
            string fullPath = HostingEnvironment.MapPath(BaseLogPath);

            return(GetLogFilesFromPath(fullPath));
        }
        public void Stop(bool immediate)
        {
            this.timer.Dispose();

            HostingEnvironment.UnregisterObject(this);
        }
 public override Stream Open()
 {
     return(File.Open(HostingEnvironment.MapPath(VirtualPath), FileMode.Open, FileAccess.Read));
 }
Esempio n. 43
0
        public Voznje(string path)
        {
            Korisnici korisnici = HttpContext.Current.Application["korisnici"] as Korisnici;
            Vozaci    vozaci    = HttpContext.Current.Application["vozaci"] as Vozaci;
            Dispeceri dispeceri = HttpContext.Current.Application["dispeceri"] as Dispeceri;

            foreach (Korisnik k in korisnici.korisnici)
            {
                k.voznjeKorisnika = new List <Voznja>();
            }
            foreach (Dispecer k in dispeceri.dispecers)
            {
                k.voznjeKorisnika = new List <Voznja>();
            }
            foreach (Vozac k in vozaci.vozaci)
            {
                k.voznjeKorisnika = new List <Voznja>();
            }

            path   = HostingEnvironment.MapPath(path);
            voznje = new List <Voznja>();
            FileStream   stream = new FileStream(path, FileMode.Open);
            StreamReader sr     = new StreamReader(stream);
            string       line   = "";

            while ((line = sr.ReadLine()) != null)
            {
                if (line == null || line == "")
                {
                    break;
                }

                string[] tokens = line.Split('|');
                Voznja   d      = new Voznja(Int32.Parse(tokens[0]), tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6], tokens[7], tokens[8], tokens[9], tokens[10], tokens[11], tokens[12], tokens[13], tokens[14], tokens[15], tokens[16], tokens[17], tokens[18], tokens[19], tokens[20], tokens[21]);
                voznje.Add(d);

                //tokens[8]
                foreach (Korisnik k in korisnici.korisnici)
                {
                    if (k.KorisnickoIme == tokens[8])
                    {
                        k.voznjeKorisnika.Add(d);
                    }
                }

                //tokens[15]
                foreach (Vozac vozac in vozaci.vozaci)
                {
                    if (tokens[15] == vozac.KorisnickoIme)
                    {
                        vozac.voznjeKorisnika.Add(d);
                    }
                }

                //tokens[14]
                foreach (Dispecer dispecer in dispeceri.dispecers)
                {
                    if (tokens[14] == dispecer.KorisnickoIme)
                    {
                        dispecer.voznjeKorisnika.Add(d);
                    }
                }
            }
            sr.Close();
            stream.Close();
        }
Esempio n. 44
0
        protected virtual InstallationResult InstallCore(ILifetimeScope scope, InstallModel model)
        {
            UpdateResult(x =>
            {
                x.ProgressMessage = _locService.GetResource("Progress.CheckingRequirements");
                x.Completed       = false;
                Logger.Info(x.ProgressMessage);
            });

            if (DataSettings.DatabaseIsInstalled())
            {
                return(UpdateResult(x =>
                {
                    x.Success = true;
                    x.RedirectUrl = Url.Action("Index", "Home");
                    Logger.Info("Application already installed");
                }));
            }

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            if (model.DatabaseConnectionString != null)
            {
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();
            }

            //SQL Server
            if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    //raw connection string
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                    {
                        UpdateResult(x =>
                        {
                            x.Errors.Add(_locService.GetResource("ConnectionStringRequired"));
                            Logger.Error(x.Errors.Last());
                        });
                    }

                    try
                    {
                        //try to create connection string
                        new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch (Exception ex)
                    {
                        UpdateResult(x =>
                        {
                            x.Errors.Add(_locService.GetResource("ConnectionStringWrongFormat"));
                            Logger.Error(ex, x.Errors.Last());
                        });
                    }
                }
                else
                {
                    //values
                    if (string.IsNullOrEmpty(model.SqlServerName))
                    {
                        UpdateResult(x =>
                        {
                            x.Errors.Add(_locService.GetResource("SqlServerNameRequired"));
                            Logger.Error(x.Errors.Last());
                        });
                    }

                    if (string.IsNullOrEmpty(model.SqlDatabaseName))
                    {
                        UpdateResult(x =>
                        {
                            x.Errors.Add(_locService.GetResource("DatabaseNameRequired"));
                            Logger.Error(x.Errors.Last());
                        });
                    }

                    //authentication type
                    if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL authentication
                        if (string.IsNullOrEmpty(model.SqlServerUsername))
                        {
                            UpdateResult(x =>
                            {
                                x.Errors.Add(_locService.GetResource("SqlServerUsernameRequired"));
                                Logger.Error(x.Errors.Last());
                            });
                        }

                        if (string.IsNullOrEmpty(model.SqlServerPassword))
                        {
                            UpdateResult(x =>
                            {
                                x.Errors.Add(_locService.GetResource("SqlServerPasswordRequired"));
                                Logger.Error(x.Errors.Last());
                            });
                        }
                    }
                }
            }


            //Consider granting access rights to the resource to the ASP.NET request identity.
            //ASP.NET has a base process identity
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7,
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>,
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
            var webHelper = scope.Resolve <IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite(webHelper);

            foreach (string dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    UpdateResult(x =>
                    {
                        x.Errors.Add(string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir));
                        Logger.Error(x.Errors.Last());
                    });
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite(webHelper);

            foreach (string file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    UpdateResult(x =>
                    {
                        x.Errors.Add(string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file));
                        Logger.Error(x.Errors.Last());
                    });
                }
            }

            if (GetInstallResult().HasErrors)
            {
                return(UpdateResult(x =>
                {
                    x.Completed = true;
                    x.Success = false;
                    x.RedirectUrl = null;
                    Logger.Error("Aborting installation.");
                }));
            }
            else
            {
                SmartObjectContext dbContext = null;
                var shouldDeleteDbOnFailure  = false;

                try
                {
                    string connectionString = null;
                    if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL Server

                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //raw connection string

                            //we know that MARS option is required when using Entity Framework
                            //let's ensure that it's specified
                            var sqlCsb = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                            sqlCsb.MultipleActiveResultSets = true;
                            connectionString = sqlCsb.ToString();
                        }
                        else
                        {
                            //values
                            connectionString = CreateConnectionString(
                                model.SqlAuthenticationType == "windowsauthentication",
                                model.SqlServerName, model.SqlDatabaseName,
                                model.SqlServerUsername, model.SqlServerPassword);
                        }

                        if (model.SqlServerCreateDatabase)
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                //create database
                                var collation             = model.UseCustomCollation ? model.Collation : "";
                                var errorCreatingDatabase = CreateDatabase(connectionString, collation);
                                if (errorCreatingDatabase.HasValue())
                                {
                                    return(UpdateResult(x =>
                                    {
                                        x.Errors.Add(errorCreatingDatabase);
                                        x.Completed = true;
                                        x.Success = false;
                                        x.RedirectUrl = null;
                                        Logger.Error(errorCreatingDatabase);
                                    }));
                                }
                                else
                                {
                                    // Database cannot be created sometimes. Weird! Seems to be Entity Framework issue
                                    // that's just wait 3 seconds
                                    Thread.Sleep(3000);

                                    shouldDeleteDbOnFailure = true;
                                }
                            }
                        }
                        else
                        {
                            //check whether database exists
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                return(UpdateResult(x =>
                                {
                                    x.Errors.Add(_locService.GetResource("DatabaseNotExists"));
                                    x.Completed = true;
                                    x.Success = false;
                                    x.RedirectUrl = null;
                                    Logger.Error(x.Errors.Last());
                                }));
                            }
                        }
                    }
                    else
                    {
                        // SQL CE
                        string databaseFileName = "SmartStore.Db.sdf";
                        string databasePath     = @"|DataDirectory|\Tenants\{0}\{1}".FormatInvariant(DataSettings.Current.TenantName, databaseFileName);
                        connectionString = "Data Source=" + databasePath + "; Persist Security Info=False";

                        // drop database if exists
                        string databaseFullPath = HostingEnvironment.MapPath(DataSettings.Current.TenantPath.EnsureEndsWith("/")) + databaseFileName;
                        if (System.IO.File.Exists(databaseFullPath))
                        {
                            System.IO.File.Delete(databaseFullPath);
                        }

                        shouldDeleteDbOnFailure = true;
                    }

                    // save settings
                    var dataProvider = model.DataProvider;
                    var settings     = DataSettings.Current;
                    settings.AppVersion           = SmartStoreVersion.Version;
                    settings.DataProvider         = dataProvider;
                    settings.DataConnectionString = connectionString;
                    settings.Save();

                    // init data provider
                    var dataProviderInstance = scope.Resolve <IEfDataProvider>();

                    // Although obsolete we have no other chance than using this here.
                    // Delegating this to DbConfiguration is not possible during installation.
#pragma warning disable 618
                    Database.DefaultConnectionFactory = dataProviderInstance.GetConnectionFactory();
#pragma warning restore 618

                    // resolve SeedData instance from primary language
                    var lazyLanguage = _locService.GetAppLanguage(model.PrimaryLanguage);
                    if (lazyLanguage == null)
                    {
                        return(UpdateResult(x =>
                        {
                            x.Errors.Add(_locService.GetResource("Install.LanguageNotRegistered").FormatInvariant(model.PrimaryLanguage));
                            x.Completed = true;
                            x.Success = false;
                            x.RedirectUrl = null;
                            Logger.Error(x.Errors.Last());
                        }));
                    }

                    // create the DataContext
                    dbContext = new SmartObjectContext();

                    // AuditableHook must run during install
                    dbContext.DbHookHandler = new DefaultDbHookHandler(new[]
                    {
                        new Lazy <IDbHook, HookMetadata>(() => new AuditableHook(), HookMetadata.Create <AuditableHook>(typeof(IAuditable), true), false)
                    });

                    // IMPORTANT: Migration would run way too early otherwise
                    Database.SetInitializer <SmartObjectContext>(null);

                    // create Language domain object from lazyLanguage
                    var languages       = dbContext.Set <Language>();
                    var primaryLanguage = languages.Create();                     // create a proxied type, resources cannot be saved otherwise
                    primaryLanguage.Name              = lazyLanguage.Metadata.Name;
                    primaryLanguage.LanguageCulture   = lazyLanguage.Metadata.Culture;
                    primaryLanguage.UniqueSeoCode     = lazyLanguage.Metadata.UniqueSeoCode;
                    primaryLanguage.FlagImageFileName = lazyLanguage.Metadata.FlagImageFileName;

                    // Build the seed configuration model
                    var seedConfiguration = new SeedDataConfiguration
                    {
                        DefaultUserName     = model.AdminEmail,
                        DefaultUserPassword = model.AdminPassword,
                        SeedSampleData      = model.InstallSampleData,
                        Data                    = lazyLanguage.Value,
                        Language                = primaryLanguage,
                        StoreMediaInDB          = model.MediaStorage == "db",
                        ProgressMessageCallback = msg => UpdateResult(x => x.ProgressMessage = _locService.GetResource(msg))
                    };

                    var seeder = new InstallDataSeeder(seedConfiguration, Logger);
                    Database.SetInitializer(new InstallDatabaseInitializer()
                    {
                        DataSeeders = new[] { seeder }
                    });

                    UpdateResult(x =>
                    {
                        x.ProgressMessage = _locService.GetResource("Progress.BuildingDatabase");
                        Logger.Info(x.ProgressMessage);
                    });
                    // ===>>> actually performs the installation by calling "InstallDataSeeder.Seed()" internally
                    dbContext.Database.Initialize(true);

                    // install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = scope.Resolve <IPluginFinder>();
                    var plugins      = pluginFinder.GetPlugins <IPlugin>(false)
                                       //.ToList()
                                       .OrderBy(x => x.PluginDescriptor.Group)
                                       .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                                       .ToList();

                    var ignoredPluginsSetting            = CommonHelper.GetAppSetting <string>("sm:PluginsIgnoredDuringInstallation");
                    var pluginsIgnoredDuringInstallation = String.IsNullOrEmpty(ignoredPluginsSetting) ?
                                                           new List <string>() :
                                                           ignoredPluginsSetting
                                                           .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .Select(x => x.Trim())
                                                           .ToList();

                    if (pluginsIgnoredDuringInstallation.Count > 0)
                    {
                        plugins = plugins.Where(x => !pluginsIgnoredDuringInstallation.Contains(x.PluginDescriptor.SystemName, StringComparer.OrdinalIgnoreCase)).ToList();
                    }

                    var pluginsCount = plugins.Count;
                    var idx          = 0;

                    using (var dbScope = new DbContextScope(autoDetectChanges: false, hooksEnabled: false)) {
                        foreach (var plugin in plugins)
                        {
                            try
                            {
                                idx++;
                                UpdateResult(x =>
                                {
                                    x.ProgressMessage = _locService.GetResource("Progress.InstallingPlugins").FormatInvariant(idx, pluginsCount);
                                    Logger.InfoFormat("Installing plugin '{0}'.", plugin.PluginDescriptor.FriendlyName ?? plugin.PluginDescriptor.SystemName);
                                });
                                plugin.Install();
                                dbScope.Commit();
                            }
                            catch (Exception ex)
                            {
                                Logger.Error(ex);

                                if (plugin.PluginDescriptor.Installed)
                                {
                                    PluginManager.MarkPluginAsUninstalled(plugin.PluginDescriptor.SystemName);
                                }
                            }
                        }
                    }

                    UpdateResult(x =>
                    {
                        x.ProgressMessage = _locService.GetResource("Progress.Finalizing");
                        Logger.Info(x.ProgressMessage);
                    });

                    // Register default permissions
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        dynamic provider = Activator.CreateInstance(providerType);
                        scope.Resolve <IPermissionService>().InstallPermissions(provider);
                    }

                    // do not ignore settings migrated by data seeder (e.g. default media storage provider)
                    scope.Resolve <ISettingService>().ClearCache();

                    // SUCCESS: Redirect to home page
                    return(UpdateResult(x =>
                    {
                        x.Completed = true;
                        x.Success = true;
                        x.RedirectUrl = Url.Action("Index", "Home");
                        Logger.Info("Installation completed successfully");
                    }));
                }
                catch (Exception exception)
                {
                    Logger.Error(exception);

                    // Clear provider settings if something got wrong
                    DataSettings.Delete();

                    // Delete Db if it was auto generated
                    if (dbContext != null && shouldDeleteDbOnFailure)
                    {
                        try
                        {
                            Logger.Debug("Deleting database");
                            dbContext.Database.Delete();
                        }
                        catch { }
                    }

                    var msg           = exception.Message;
                    var realException = exception;
                    while (realException.InnerException != null)
                    {
                        realException = realException.InnerException;
                    }

                    if (!Object.Equals(exception, realException))
                    {
                        msg += " (" + realException.Message + ")";
                    }

                    return(UpdateResult(x =>
                    {
                        x.Errors.Add(string.Format(_locService.GetResource("SetupFailed"), msg));
                        x.Success = false;
                        x.Completed = true;
                        x.RedirectUrl = null;
                    }));
                }
                finally
                {
                    if (dbContext != null)
                    {
                        dbContext.Dispose();
                    }
                }
            }
        }
Esempio n. 45
0
        private void ConfigureAuthServices(IServiceCollection services)
        {
            services.AddIdentity <ApplicationUser, IdentityRole <int> >(
                options => { options.Lockout.AllowedForNewUsers = false; })
            .AddEntityFrameworkStores <BuildAssetRegistryContext>();

            services.AddContextAwareAuthenticationScheme(o =>
            {
                o.SelectScheme = p => p.StartsWithSegments("/api") ? PersonalAccessTokenDefaults.AuthenticationScheme : IdentityConstants.ApplicationScheme;
            });

            services.AddAuthentication()
            .AddGitHubOAuth(Configuration.GetSection("GitHubAuthentication"), GitHubScheme)
            .AddPersonalAccessToken <ApplicationUser>(
                options =>
            {
                options.Events = new PersonalAccessTokenEvents <ApplicationUser>
                {
                    OnSetTokenHash = async context =>
                    {
                        var dbContext = context.HttpContext.RequestServices
                                        .GetRequiredService <BuildAssetRegistryContext>();
                        int userId = context.User.Id;
                        var token  = new ApplicationUserPersonalAccessToken
                        {
                            ApplicationUserId = userId,
                            Name    = context.Name,
                            Hash    = context.Hash,
                            Created = DateTimeOffset.UtcNow
                        };
                        await dbContext.Set <ApplicationUserPersonalAccessToken>().AddAsync(token);
                        await dbContext.SaveChangesAsync();

                        return(token.Id);
                    },
                    OnGetTokenHash = async context =>
                    {
                        var dbContext = context.HttpContext.RequestServices
                                        .GetRequiredService <BuildAssetRegistryContext>();
                        ApplicationUserPersonalAccessToken token = await dbContext
                                                                   .Set <ApplicationUserPersonalAccessToken>()
                                                                   .Where(t => t.Id == context.TokenId)
                                                                   .Include(t => t.ApplicationUser)
                                                                   .FirstOrDefaultAsync();
                        if (token != null)
                        {
                            context.Success(token.Hash, token.ApplicationUser);
                        }
                    },
                    OnValidatePrincipal = async context =>
                    {
                        ApplicationUser user = context.User;
                        var dbContext        = context.HttpContext.RequestServices
                                               .GetRequiredService <BuildAssetRegistryContext>();
                        var userManager = context.HttpContext.RequestServices
                                          .GetRequiredService <UserManager <ApplicationUser> >();
                        var signInManager = context.HttpContext.RequestServices
                                            .GetRequiredService <SignInManager <ApplicationUser> >();

                        await UpdateUserIfNeededAsync(user, dbContext, userManager, signInManager);

                        ClaimsPrincipal principal = await signInManager.CreateUserPrincipalAsync(user);
                        context.ReplacePrincipal(principal);
                    }
                };
            });
            services.ConfigureExternalCookie(
                options =>
            {
                options.ExpireTimeSpan     = TimeSpan.FromMinutes(30);
                options.ReturnUrlParameter = "returnUrl";
                options.LoginPath          = "/Account/SignIn";
                options.Events             = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = ctx =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api"))
                        {
                            ctx.Response.StatusCode = 401;
                            return(Task.CompletedTask);
                        }

                        ctx.Response.Redirect(ctx.RedirectUri);
                        return(Task.CompletedTask);
                    },
                    OnRedirectToAccessDenied = ctx =>
                    {
                        ctx.Response.StatusCode = 403;
                        return(Task.CompletedTask);
                    },
                };
            });
            services.ConfigureApplicationCookie(
                options =>
            {
                options.ExpireTimeSpan    = LoginCookieLifetime;
                options.SlidingExpiration = true;
                options.Events            = new CookieAuthenticationEvents
                {
                    OnSigningIn = async ctx =>
                    {
                        var dbContext = ctx.HttpContext.RequestServices
                                        .GetRequiredService <BuildAssetRegistryContext>();
                        var signInManager = ctx.HttpContext.RequestServices
                                            .GetRequiredService <SignInManager <ApplicationUser> >();
                        var userManager = ctx.HttpContext.RequestServices
                                          .GetRequiredService <UserManager <ApplicationUser> >();
                        ExternalLoginInfo info = await signInManager.GetExternalLoginInfoAsync();

                        var user = await userManager.GetUserAsync(ctx.Principal);
                        await UpdateUserTokenAsync(dbContext, userManager, user, info);

                        IdentityOptions identityOptions = ctx.HttpContext.RequestServices
                                                          .GetRequiredService <IOptions <IdentityOptions> >()
                                                          .Value;

                        // replace the ClaimsPrincipal we are about to serialize to the cookie with a reference
                        Claim claim = ctx.Principal.Claims.Single(
                            c => c.Type == identityOptions.ClaimsIdentity.UserIdClaimType);
                        Claim[] claims = { claim };
                        var identity   = new ClaimsIdentity(claims, IdentityConstants.ApplicationScheme);
                        ctx.Principal  = new ClaimsPrincipal(identity);
                    },
                    OnValidatePrincipal = async ctx =>
                    {
                        var dbContext = ctx.HttpContext.RequestServices
                                        .GetRequiredService <BuildAssetRegistryContext>();
                        var userManager = ctx.HttpContext.RequestServices
                                          .GetRequiredService <UserManager <ApplicationUser> >();
                        var signInManager = ctx.HttpContext.RequestServices
                                            .GetRequiredService <SignInManager <ApplicationUser> >();


                        // extract the userId from the ClaimsPrincipal and read the user from the Db
                        ApplicationUser user = await userManager.GetUserAsync(ctx.Principal);
                        if (user == null)
                        {
                            ctx.RejectPrincipal();
                        }
                        else
                        {
                            await UpdateUserIfNeededAsync(user, dbContext, userManager, signInManager);

                            ClaimsPrincipal principal = await signInManager.CreateUserPrincipalAsync(user);
                            ctx.ReplacePrincipal(principal);
                        }
                    }
                };
            });

            services.AddAuthorization(
                options =>
            {
                options.AddPolicy(
                    MsftAuthorizationPolicyName,
                    policy =>
                {
                    policy.RequireAuthenticatedUser();
                    if (!HostingEnvironment.IsDevelopment())
                    {
                        policy.RequireRole("github:team:dotnet:dnceng", "github:team:dotnet:arcade-contrib");
                    }
                });
            });

            services.Configure <MvcOptions>(
                options =>
            {
                options.Conventions.Add(new DefaultAuthorizeActionModelConvention(MsftAuthorizationPolicyName));
            });
        }
        protected override void Load(ContainerBuilder builder)
        {
            bool     enableLocalization               = true;
            string   absoluteFileName                 = HostingEnvironment.MapPath("~/Mvc.sitemap");
            TimeSpan absoluteCacheExpiration          = TimeSpan.FromMinutes(5);
            bool     visibilityAffectsDescendants     = true;
            bool     useTitleIfDescriptionNotProvided = true;



            bool securityTrimmingEnabled = false;

            string[] includeAssembliesForScan = new string[] { "PhotoSharingApp" };


            var currentAssembly             = this.GetType().Assembly;
            var siteMapProviderAssembly     = typeof(SiteMaps).Assembly;
            var allAssemblies               = new Assembly[] { currentAssembly, siteMapProviderAssembly };
            var excludeTypes                = new Type[] {
// Use this array to add types you wish to explicitly exclude from convention-based
// auto-registration. By default all types that either match I[TypeName] = [TypeName] or
// I[TypeName] = [TypeName]Adapter will be automatically wired up as long as they don't
// have the [ExcludeFromAutoRegistrationAttribute].
//
// If you want to override a type that follows the convention, you should add the name
// of either the implementation name or the interface that it inherits to this list and
// add your manual registration code below. This will prevent duplicate registrations
// of the types from occurring.

// Example:
// typeof(SiteMap),
// typeof(SiteMapNodeVisibilityProviderStrategy)
            };
            var multipleImplementationTypes = new Type[] {
                typeof(ISiteMapNodeUrlResolver),
                typeof(ISiteMapNodeVisibilityProvider),
                typeof(IDynamicNodeProvider)
            };

// Matching type name (I[TypeName] = [TypeName]) or matching type name + suffix Adapter (I[TypeName] = [TypeName]Adapter)
// and not decorated with the [ExcludeFromAutoRegistrationAttribute].
            CommonConventions.RegisterDefaultConventions(
                (interfaceType, implementationType) => builder.RegisterType(implementationType).As(interfaceType).SingleInstance(),
                new Assembly[] { siteMapProviderAssembly },
                allAssemblies,
                excludeTypes,
                string.Empty);

// Multiple implementations of strategy based extension points (and not decorated with [ExcludeFromAutoRegistrationAttribute]).
            CommonConventions.RegisterAllImplementationsOfInterface(
                (interfaceType, implementationType) => builder.RegisterType(implementationType).As(interfaceType).SingleInstance(),
                multipleImplementationTypes,
                allAssemblies,
                excludeTypes,
                string.Empty);

// Registration of internal controllers
            CommonConventions.RegisterAllImplementationsOfInterface(
                (interfaceType, implementationType) => builder.RegisterType(implementationType).As(interfaceType).AsSelf().InstancePerDependency(),
                new Type[] { typeof(IController) },
                new Assembly[] { siteMapProviderAssembly },
                new Type[0],
                string.Empty);

// Visibility Providers
            builder.RegisterType <SiteMapNodeVisibilityProviderStrategy>()
            .As <ISiteMapNodeVisibilityProviderStrategy>()
            .WithParameter("defaultProviderName", string.Empty);

// Pass in the global controllerBuilder reference
            builder.RegisterInstance(ControllerBuilder.Current)
            .As <ControllerBuilder>();

            builder.RegisterType <ControllerTypeResolverFactory>()
            .As <IControllerTypeResolverFactory>()
            .WithParameter("areaNamespacesToIgnore", new string[0]);

// Configure Security
            builder.RegisterType <AuthorizeAttributeAclModule>()
            .Named <IAclModule>("authorizeAttributeAclModule");
            builder.RegisterType <XmlRolesAclModule>()
            .Named <IAclModule>("xmlRolesAclModule");
            builder.RegisterType <CompositeAclModule>()
            .As <IAclModule>()
            .WithParameter(
                (p, c) => p.Name == "aclModules",
                (p, c) => new[]
            {
                c.ResolveNamed <IAclModule>("authorizeAttributeAclModule"),
                c.ResolveNamed <IAclModule>("xmlRolesAclModule")
            });



            builder.RegisterInstance(System.Runtime.Caching.MemoryCache.Default)
            .As <System.Runtime.Caching.ObjectCache>();

            builder.RegisterGeneric(typeof(RuntimeCacheProvider <>))
            .As(typeof(ICacheProvider <>));

            builder.RegisterType <RuntimeFileCacheDependency>()
            .Named <ICacheDependency>("cacheDependency1")
            .WithParameter("fileName", absoluteFileName);

            builder.RegisterType <CacheDetails>()
            .Named <ICacheDetails>("cacheDetails1")
            .WithParameter("absoluteCacheExpiration", absoluteCacheExpiration)
            .WithParameter("slidingCacheExpiration", TimeSpan.MinValue)
            .WithParameter(
                (p, c) => p.Name == "cacheDependency",
                (p, c) => c.ResolveNamed <ICacheDependency>("cacheDependency1"));

// Configure the visitors
            builder.RegisterType <UrlResolvingSiteMapNodeVisitor>()
            .As <ISiteMapNodeVisitor>();

// Prepare for our node providers
            builder.RegisterType <FileXmlSource>()
            .Named <IXmlSource>("xmlSource1")
            .WithParameter("fileName", absoluteFileName);

            builder.RegisterType <ReservedAttributeNameProvider>()
            .As <IReservedAttributeNameProvider>()
            .WithParameter("attributesToIgnore", new string[0]);


// Register the sitemap node providers
            builder.RegisterType <XmlSiteMapNodeProvider>()
            .Named <ISiteMapNodeProvider>("xmlSiteMapNodeProvider1")
            .WithParameter("includeRootNode", true)
            .WithParameter("useNestedDynamicNodeRecursion", false)
            .WithParameter(
                (p, c) => p.Name == "xmlSource",
                (p, c) => c.ResolveNamed <IXmlSource>("xmlSource1"));

            builder.RegisterType <ReflectionSiteMapNodeProvider>()
            .Named <ISiteMapNodeProvider>("reflectionSiteMapNodeProvider1")
            .WithParameter("includeAssemblies", includeAssembliesForScan)
            .WithParameter("excludeAssemblies", new string[0]);

            builder.RegisterType <CompositeSiteMapNodeProvider>()
            .Named <ISiteMapNodeProvider>("siteMapNodeProvider1")
            .WithParameter(
                (p, c) => p.Name == "siteMapNodeProviders",
                (p, c) => new[]
            {
                c.ResolveNamed <ISiteMapNodeProvider>("xmlSiteMapNodeProvider1"),
                c.ResolveNamed <ISiteMapNodeProvider>("reflectionSiteMapNodeProvider1")
            });

// Register the sitemap builders
            builder.RegisterType <SiteMapBuilder>()
            .Named <ISiteMapBuilder>("siteMapBuilder1")
            .WithParameter(
                (p, c) => p.Name == "siteMapNodeProvider",
                (p, c) => c.ResolveNamed <ISiteMapNodeProvider>("siteMapNodeProvider1"));

// Configure the builder sets
            builder.RegisterType <SiteMapBuilderSet>()
            .Named <ISiteMapBuilderSet>("builderSet1")
            .WithParameter("instanceName", "default")
            .WithParameter("securityTrimmingEnabled", securityTrimmingEnabled)
            .WithParameter("enableLocalization", enableLocalization)
            .WithParameter("visibilityAffectsDescendants", visibilityAffectsDescendants)
            .WithParameter("useTitleIfDescriptionNotProvided", useTitleIfDescriptionNotProvided)
            .WithParameter(
                (p, c) => p.Name == "siteMapBuilder",
                (p, c) => c.ResolveNamed <ISiteMapBuilder>("siteMapBuilder1"))
            .WithParameter(
                (p, c) => p.Name == "cacheDetails",
                (p, c) => c.ResolveNamed <ICacheDetails>("cacheDetails1"));

            builder.RegisterType <SiteMapBuilderSetStrategy>()
            .As <ISiteMapBuilderSetStrategy>()
            .WithParameter(
                (p, c) => p.Name == "siteMapBuilderSets",
                (p, c) => c.ResolveNamed <IEnumerable <ISiteMapBuilderSet> >("builderSet1"));
        }
Esempio n. 47
0
        public override void Load()
        {
            var configuration = new ConfigurationService();

            Bind <ConfigurationService>()
            .ToMethod(context => configuration);
            Bind <IAppConfiguration>()
            .ToMethod(context => configuration.Current);
            Bind <PoliteCaptcha.IConfigurationSource>()
            .ToMethod(context => configuration);

            Bind <Lucene.Net.Store.Directory>()
            .ToMethod(_ => LuceneCommon.GetDirectory(configuration.Current.LuceneIndexLocation))
            .InSingletonScope();

            Bind <ISearchService>()
            .To <LuceneSearchService>()
            .InRequestScope();

            if (!String.IsNullOrEmpty(configuration.Current.AzureStorageConnectionString))
            {
                Bind <ErrorLog>()
                .ToMethod(_ => new TableErrorLog(configuration.Current.AzureStorageConnectionString))
                .InSingletonScope();
            }
            else
            {
                Bind <ErrorLog>()
                .ToMethod(_ => new SqlErrorLog(configuration.Current.SqlConnectionString))
                .InSingletonScope();
            }

            Bind <ICacheService>()
            .To <HttpContextCacheService>()
            .InRequestScope();

            Bind <IContentService>()
            .To <ContentService>()
            .InSingletonScope();

            Bind <IEntitiesContext>()
            .ToMethod(context => new EntitiesContext(configuration.Current.SqlConnectionString, readOnly: configuration.Current.ReadOnlyMode))
            .InRequestScope();

            Bind <IEntityRepository <User> >()
            .To <EntityRepository <User> >()
            .InRequestScope();

            Bind <IEntityRepository <CuratedFeed> >()
            .To <EntityRepository <CuratedFeed> >()
            .InRequestScope();

            Bind <IEntityRepository <CuratedPackage> >()
            .To <EntityRepository <CuratedPackage> >()
            .InRequestScope();

            Bind <IEntityRepository <PackageRegistration> >()
            .To <EntityRepository <PackageRegistration> >()
            .InRequestScope();

            Bind <IEntityRepository <Package> >()
            .To <EntityRepository <Package> >()
            .InRequestScope();

            Bind <IEntityRepository <PackageDependency> >()
            .To <EntityRepository <PackageDependency> >()
            .InRequestScope();

            Bind <IEntityRepository <PackageStatistics> >()
            .To <EntityRepository <PackageStatistics> >()
            .InRequestScope();

            Bind <IEntityRepository <Credential> >()
            .To <EntityRepository <Credential> >()
            .InRequestScope();

            Bind <ICuratedFeedService>()
            .To <CuratedFeedService>()
            .InRequestScope();

            Bind <IUserService>()
            .To <UserService>()
            .InRequestScope();

            Bind <IPackageService>()
            .To <PackageService>()
            .InRequestScope();

            Bind <EditPackageService>().ToSelf();

            Bind <IFormsAuthenticationService>()
            .To <FormsAuthenticationService>()
            .InSingletonScope();

            Bind <IControllerFactory>()
            .To <NuGetControllerFactory>()
            .InRequestScope();

            Bind <IIndexingService>()
            .To <LuceneIndexingService>()
            .InRequestScope();

            Bind <INuGetExeDownloaderService>()
            .To <NuGetExeDownloaderService>()
            .InRequestScope();

            var mailSenderThunk = new Lazy <IMailSender>(
                () =>
            {
                var settings = Kernel.Get <ConfigurationService>();
                if (settings.Current.SmtpUri != null && settings.Current.SmtpUri.IsAbsoluteUri)
                {
                    var smtpUri = new SmtpUri(settings.Current.SmtpUri);

                    var mailSenderConfiguration = new MailSenderConfiguration
                    {
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Host           = smtpUri.Host,
                        Port           = smtpUri.Port,
                        EnableSsl      = smtpUri.Secure
                    };

                    if (!String.IsNullOrWhiteSpace(smtpUri.UserName))
                    {
                        mailSenderConfiguration.UseDefaultCredentials = false;
                        mailSenderConfiguration.Credentials           = new NetworkCredential(
                            smtpUri.UserName,
                            smtpUri.Password);
                    }

                    return(new MailSender(mailSenderConfiguration));
                }
                else
                {
                    var mailSenderConfiguration = new MailSenderConfiguration
                    {
                        DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                        PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
                    };

                    return(new MailSender(mailSenderConfiguration));
                }
            });

            Bind <IMailSender>()
            .ToMethod(context => mailSenderThunk.Value);

            Bind <IMessageService>()
            .To <MessageService>();

            Bind <IPrincipal>().ToMethod(context => HttpContext.Current.User);

            switch (configuration.Current.StorageType)
            {
            case StorageType.FileSystem:
            case StorageType.NotSpecified:
                ConfigureForLocalFileSystem();
                break;

            case StorageType.AzureStorage:
                ConfigureForAzureStorage(configuration);
                break;
            }

            Bind <IFileSystemService>()
            .To <FileSystemService>()
            .InSingletonScope();

            Bind <IPackageFileService>()
            .To <PackageFileService>();

            Bind <IEntityRepository <PackageOwnerRequest> >()
            .To <EntityRepository <PackageOwnerRequest> >()
            .InRequestScope();

            Bind <IUploadFileService>()
            .To <UploadFileService>();

            // todo: bind all package curators by convention
            Bind <IAutomaticPackageCurator>()
            .To <WebMatrixPackageCurator>();
            Bind <IAutomaticPackageCurator>()
            .To <Windows8PackageCurator>();

            // todo: bind all commands by convention
            Bind <IAutomaticallyCuratePackageCommand>()
            .To <AutomaticallyCuratePackageCommand>()
            .InRequestScope();

            Bind <IAggregateStatsService>()
            .To <AggregateStatsService>()
            .InRequestScope();
            Bind <IPackageIdsQuery>()
            .To <PackageIdsQuery>()
            .InRequestScope();
            Bind <IPackageVersionsQuery>()
            .To <PackageVersionsQuery>()
            .InRequestScope();
        }