示例#1
0
        ShellContext IShellContextFactory.CreateShellContext(
            ShellSettings settings)
        {
            var sw = Stopwatch.StartNew();
            _logger.LogInformation("Creating shell context for tenant {0}", settings.Name);

            var blueprint = _compositionStrategy.Compose(settings, MinimumShellDescriptor());
            var provider = _shellContainerFactory.CreateContainer(settings, blueprint);

            try {
                var shellcontext = new ShellContext {
                    Settings = settings,
                    Blueprint = blueprint,
                    LifetimeScope = provider,
                    Shell = provider.GetRequiredService<IOrchardShell>()
                };

                _logger.LogVerbose("Created shell context for tenant {0} in {1}ms", settings.Name, sw.ElapsedMilliseconds);

                return shellcontext;
            }
            catch (Exception ex) {
                _logger.LogError("Cannot create shell context", ex);
                throw;
            }
        }
        ShellContext IShellContextFactory.CreateSetupContext(ShellSettings settings)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("No shell settings available. Creating shell context for setup");
            }
            var descriptor = new ShellDescriptor
            {
                SerialNumber = -1,
                Features = new[] {
                    new ShellFeature { Name = "Orchard.Logging.Console" },
                    new ShellFeature { Name = "Orchard.Setup" },
                },
            };

            var blueprint = _compositionStrategy.Compose(settings, descriptor);
            var provider = _shellContainerFactory.CreateContainer(settings, blueprint);

            return new ShellContext
            {
                Settings = settings,
                Blueprint = blueprint,
                ServiceProvider = provider
            };
        }
示例#3
0
 public RoutePublisher(
     IRouteBuilder routeBuilder,
     ShellSettings shellSettings)
 {
     _routeBuilder = routeBuilder;
     _shellSettings = shellSettings;
 }
        ShellContext IShellContextFactory.CreateShellContext(ShellSettings settings)
        {
            var sw = Stopwatch.StartNew();
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Creating shell context for tenant {0}", settings.Name);
            }
            var blueprint = _compositionStrategy.Compose(settings, MinimumShellDescriptor());
            var provider = _shellContainerFactory.CreateContainer(settings, blueprint);

            try
            {
                var shellcontext = new ShellContext
                {
                    Settings = settings,
                    Blueprint = blueprint,
                    ServiceProvider = provider
                };

                if (_logger.IsEnabled(LogLevel.Verbose))
                {
                    _logger.LogVerbose("Created shell context for tenant {0} in {1}ms", settings.Name, sw.ElapsedMilliseconds);
                }
                return shellcontext;
            }
            catch (Exception ex)
            {
                _logger.LogError("Cannot create shell context", ex);
                throw;
            }
        }
        public static ShellSettings ParseSettings2(string text)
        {
            using (var settings = new StringReader(text))
            {
                var shellSettings = new ShellSettings();
                string setting;
                while ((setting = settings.ReadLine()) != null)
                {
                    if (string.IsNullOrWhiteSpace(setting))
                        continue;

                    var separatorIndex = setting.IndexOf(Separator);
                    if (separatorIndex == -1)
                        continue;

                    var key = setting.Substring(0, separatorIndex).Trim();
                    var value = setting.Substring(separatorIndex + 1).Trim();

                    //值等于空值则跳过。
                    if (value.Equals(EmptyValue, StringComparison.OrdinalIgnoreCase))
                        continue;

                    shellSettings[key] = value;
                }

                return shellSettings;
            }
        }
        /// <summary>
        /// 将外壳设置信息组成文本。
        /// </summary>
        /// <param name="settings">外壳设置信息。</param>
        /// <returns>文本。</returns>
        /// <exception cref="ArgumentNullException"><paramref name="settings"/> 为null。</exception>
        public static string ComposeSettings(ShellSettings settings)
        {
            var sb = new StringBuilder();
            foreach (var key in settings.Keys)
                sb.AppendLine(key + AppendSeparator + (settings[key] ?? EmptyValue));

            return sb.ToString();
        }
示例#7
0
        public SetupController(ISetupService setupService,
            ShellSettings shellSettings)
        {
            _setupService = setupService;
            _shellSettings = shellSettings;

            T = NullLocalizer.Instance;
        }
        public SessionConfigurationCache(ShellSettings shellSettings, ShellBlueprint shellBlueprint, IAppDataFolder appDataFolder)
        {
            _shellSettings = shellSettings;
            _shellBlueprint = shellBlueprint;
            _appDataFolder = appDataFolder;
            _currentConfig = null;

            Logger = NullLogger.Instance;
        }
 public DbContextFactoryHolder(
     ShellSettings shellSettings,
     IDataServicesProviderFactory dataServicesProviderFactory,
     IAppDataFolder appDataFolder)
 {
     _shellSettings = shellSettings;
     _dataServicesProviderFactory = dataServicesProviderFactory;
     _appDataFolder = appDataFolder;
 }
示例#10
0
        /// <summary>
        /// Creates a shell context based on shell settings
        /// </summary>
        public ShellContext CreateShellContext(ShellSettings settings)
        {
            if (settings.State == TenantState.Uninitialized) {
                _logger.LogDebug("Creating shell context for tenant {0} setup", settings.Name);
                return _shellContextFactory.CreateSetupContext(settings);
            }

            _logger.LogDebug("Creating shell context for tenant {0}", settings.Name);
            return _shellContextFactory.CreateShellContext(settings);
        }
示例#11
0
 public ShellSettings(ShellSettings settings)
 {
     Name = settings.Name;
     DataProvider = settings.DataProvider;
     DataConnectionString = settings.DataConnectionString;
     DataTablePrefix = settings.DataTablePrefix;
     RequestUrlHost = settings.RequestUrlHost;
     RequestUrlPrefix = settings.RequestUrlPrefix;
     State = settings.State;
 }
示例#12
0
        ShellContext IShellContextFactory.CreateShellContext(ShellSettings settings)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Creating shell context for tenant {0}", settings.Name);
            }

            var knownDescriptor = MinimumShellDescriptor();
            return CreateDescribedContext(settings, knownDescriptor);
        }
 public XElement Convert(ShellSettings state)
 {
     var root = new XElement(new XElement(Structure.Root));
     root.Add(new XElement(Structure.WindowsState, state.State));
     root.Add(new XElement(Structure.Top, state.Top));
     root.Add(new XElement(Structure.Left, state.Left));
     root.Add(new XElement(Structure.Width, state.Width));
     root.Add(new XElement(Structure.Height, state.Height));
     return root;
 }
 public ShellDescriptorManager(
     ShellSettings shellSettings,
     IEventBus eventBus,
     ISession session,
     ILogger<ShellDescriptorManager> logger)
 {
     _shellSettings = shellSettings;
     _eventBus = eventBus;
     _session = session;
     _logger = logger;
 }
 public ShellDescriptorManager(
     ShellSettings shellSettings,
     //IEventNotifier eventNotifier,
     ILoggerFactory loggerFactory,
     ISession session)
 {
     _shellSettings = shellSettings;
     //_eventNotifier = eventNotifier;
     _session = session;
     _logger = loggerFactory.CreateLogger<ShellDescriptorManager>();
 }
示例#16
0
 public ShellDescriptorManager(
     ShellSettings shellSettings,
     //IEventNotifier eventNotifier,
     ISession session,
     ILogger<ShellDescriptorManager> logger)
 {
     _shellSettings = shellSettings;
     //_eventNotifier = eventNotifier;
     _session = session;
     _logger = logger;
 }
示例#17
0
 public OrchardShell(
     IEnumerable<IRouteProvider> routeProviders,
     IRoutePublisher routePublisher,
     IEnumerable<IMiddlewareProvider> middlewareProviders,
     ShellSettings shellSettings,
     IServiceProvider serviceProvider)
 {
     _routeProviders = routeProviders;
     _routePublisher = routePublisher;
     _middlewareProviders = middlewareProviders;
     _shellSettings = shellSettings;
     _serviceProvider = serviceProvider;
 }
 public ShellSettings(ShellSettings settings) {
     Name = settings.Name;
     DataProvider = settings.DataProvider;
     DataConnectionString = settings.DataConnectionString;
     DataTablePrefix = settings.DataTablePrefix;
     RequestUrlHost = settings.RequestUrlHost;
     RequestUrlPrefix = settings.RequestUrlPrefix;
     EncryptionAlgorithm = settings.EncryptionAlgorithm;
     EncryptionKey = settings.EncryptionKey;
     HashAlgorithm = settings.HashAlgorithm;
     HashKey = settings.HashKey;
     State = settings.State;
 }
示例#19
0
        public SessionFactoryHolder(
			ShellSettings shellSettings,
			ShellBlueprint shellBlueprint,
			IDataServicesProviderFactory dataServicesProviderFactory,
			IAppDataFolder appDataFolder,
			ISessionConfigurationCache sessionConfigurationCache)
        {
            _shellSettings = shellSettings;
            _shellBlueprint = shellBlueprint;
            _dataServicesProviderFactory = dataServicesProviderFactory;
            _appDataFolder = appDataFolder;
            _sessionConfigurationCache = sessionConfigurationCache;

            Logger = NullLogger.Instance;
        }
示例#20
0
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            // Sure this is right?
            serviceCollection.AddInstance(_loggerFactory);

            IServiceCollection moduleServiceCollection = new ServiceCollection();
            foreach (var dependency in blueprint.Dependencies
                .Where(t => typeof(IModule).IsAssignableFrom(t.Type))) {

                moduleServiceCollection.AddScoped(typeof(IModule), dependency.Type);
            }

            var moduleServiceProvider = moduleServiceCollection.BuildShellServiceProviderWithHost(_serviceProvider);
            foreach (var service in moduleServiceProvider.GetServices<IModule>()) {
                service.Configure(serviceCollection);
            }

            foreach (var dependency in blueprint.Dependencies
                .Where(t => !typeof(IModule).IsAssignableFrom(t.Type))) {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                    .Where(itf => typeof(IDependency).IsAssignableFrom(itf))) {
                    _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            return serviceCollection.BuildShellServiceProviderWithHost(_serviceProvider);
        }
示例#21
0
        ShellContext IShellContextFactory.CreateSetupContext(ShellSettings settings)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("No shell settings available. Creating shell context for setup");
            }
            var descriptor = new ShellDescriptor
            {
                SerialNumber = -1,
                Features = new[] {
                    new ShellFeature { Name = "Orchard.Logging.Console" },
                    new ShellFeature { Name = "Orchard.Setup" },
                },
            };

            return CreateDescribedContext(settings, descriptor);
        }
示例#22
0
        public ShellContext CreateDescribedContext(ShellSettings settings, ShellDescriptor shellDescriptor)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Creating described context for tenant {0}", settings.Name);
            }

            var blueprint = _compositionStrategy.Compose(settings, shellDescriptor);
            var provider = _shellContainerFactory.CreateContainer(settings, blueprint);

            return new ShellContext
            {
                Settings = settings,
                Blueprint = blueprint,
                ServiceProvider = provider
            };
        }
示例#23
0
        public string Setup(SetupContext context)
        {
            string executionId = Guid.NewGuid().ToString();

            // The vanilla Orchard distibution has the following features enabled.
            string[] hardcoded = {
                // Framework
                "Orchard.Hosting",
                // Core
                "Settings",
                // Test Modules
                "Orchard.Demo", "Orchard.Test1"
                };

            context.EnabledFeatures = hardcoded.Union(context.EnabledFeatures ?? Enumerable.Empty<string>()).Distinct().ToList();

            var shellSettings = new ShellSettings(_shellSettings);

            if (string.IsNullOrEmpty(shellSettings.DataProvider)) {
                shellSettings.DataProvider = context.DatabaseProvider;
                shellSettings.DataConnectionString = context.DatabaseConnectionString;
                shellSettings.DataTablePrefix = context.DatabaseTablePrefix;
            }

            // TODO: Add Encryption Settings in

            var shellDescriptor = new ShellDescriptor {
                Features = context.EnabledFeatures.Select(name => new ShellFeature { Name = name })
            };

            // creating a standalone environment.
            // in theory this environment can be used to resolve any normal components by interface, and those
            // components will exist entirely in isolation - no crossover between the safemode container currently in effect

            // must mark state as Running - otherwise standalone enviro is created "for setup"
            shellSettings.State = TenantState.Running;

            // TODO: Remove and mirror Orchard Setup
            shellSettings.RequestUrlHost = _httpContextAccessor.HttpContext.Request.Host.Value;
            shellSettings.DataProvider = "InMemory";

            _shellSettingsManager.SaveSettings(shellSettings);

            return executionId;
        }
示例#24
0
 public SetupService(
     ShellSettings shellSettings,
     IOrchardHost orchardHost,
     IShellSettingsManager shellSettingsManager,
     IShellContainerFactory shellContainerFactory,
     ICompositionStrategy compositionStrategy,
     IExtensionManager extensionManager,
     IHttpContextAccessor httpContextAccessor)
 {
     _shellSettings = shellSettings;
     _orchardHost = orchardHost;
     _shellSettingsManager = shellSettingsManager;
     _shellContainerFactory = shellContainerFactory;
     _compositionStrategy = compositionStrategy;
     _extensionManager = extensionManager;
     _httpContextAccessor = httpContextAccessor;
     T = NullLocalizer.Instance;
 }
示例#25
0
        IEnumerable<ShellSettings> IShellSettingsManager.LoadSettings()
        {
            var tenantPaths = _appDataFolder
                .ListDirectories("Sites")
                .Select(path => _appDataFolder.MapPath(path));

            var shellSettings = new List<ShellSettings>();

            foreach (var tenantPath in tenantPaths) {
                _logger.LogInformation("ShellSettings found in '{0}', attempting to load.", tenantPath);

                var configurationContainer =
                    new ConfigurationBuilder()
                        .AddJsonFile(_appDataFolder.Combine(tenantPath, string.Format(SettingsFileNameFormat, "json")),
                            true)
                        .AddXmlFile(_appDataFolder.Combine(tenantPath, string.Format(SettingsFileNameFormat, "xml")),
                            true)
                        .Add(
                            new DefaultFileConfigurationSource(
                                _appDataFolder.Combine(tenantPath, string.Format(SettingsFileNameFormat, "txt")), false));

                var config = configurationContainer.Build();

                var shellSetting = new ShellSettings {
                    Name = config["Name"],
                    DataConnectionString = config["DataConnectionString"],
                    DataProvider = config["DataProvider"],
                    DataTablePrefix = config["DataTablePrefix"],
                    RequestUrlHost = config["RequestUrlHost"],
                    RequestUrlPrefix = config["RequestUrlPrefix"]
                };

                TenantState state;
                shellSetting.State = Enum.TryParse(config["State"], true, out state)
                    ? state
                    : TenantState.Uninitialized;

                shellSettings.Add(shellSetting);

                _logger.LogInformation("Loaded ShellSettings for tenant '{0}'", shellSetting.Name);
            }

            return shellSettings;
        }
示例#26
0
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            foreach (var dependency in blueprint.Dependencies
                .Where(t => typeof(IModule).IsAssignableFrom(t.Type))) {

                _logger.LogDebug("IModule Type: {0}", dependency.Type);

                ((IModule)ActivatorUtilities
                    .CreateInstance(_serviceProvider, dependency.Type))
                    .Configure(serviceCollection);
            }

            foreach (var dependency in blueprint.Dependencies
                .Where(t => !typeof(IModule).IsAssignableFrom(t.Type))) {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                    .Where(itf => typeof(IDependency).IsAssignableFrom(itf))) {
                    _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            return new WrappingServiceProvider(_serviceProvider, serviceCollection);
        }
示例#27
0
        ShellContext IShellContextFactory.CreateShellContext(
            ShellSettings settings)
        {
            _logger.LogInformation("Creating shell context for tenant {0}", settings.Name);

            var blueprint = _compositionStrategy.Compose(settings, MinimumShellDescriptor());
            var provider = _shellContainerFactory.CreateContainer(settings, blueprint);

            try {
                return new ShellContext {
                    Settings = settings,
                    Blueprint = blueprint,
                    LifetimeScope = provider,
                    Shell = provider.GetRequiredService<IOrchardShell>()
                };
            }
            catch (Exception ex) {
                _logger.LogError("Cannot create shell context", ex);
                throw;
            }
        }
        /// <summary>
        /// 保存一个外壳设置。
        /// </summary>
        /// <param name="settings">外壳设置信息。</param>
        void IShellSettingsManager.SaveSettings(ShellSettings settings)
        {
            settings.NotNull("settings");

            if (string.IsNullOrWhiteSpace(settings.Name))
                throw new ArgumentException("外壳设置信息中的 Name 属性不能为空。", "settings");

            Logger.Debug("保存租户 '{0}' 的外壳设置信息...", settings.Name);
            var filePath = Path.Combine(SettingsDirectoryName, settings.Name, SettingsFileName);

            Task.Factory.StartNew(
                () => _appDataFolder.CreateFile(filePath, ShellSettingsSerializer.ComposeSettings(settings)));

            Logger.Debug("外壳设置信息保存成功,标记租户 '{0}' 需要重新启动。", settings.Name);
            //使缓存失效。
            _simpleToken.IsCurrent = false;
            if (_events == null)
                return;
            foreach (var @event in _events.Value)
                @event.Saved(settings);
        }
示例#29
0
        ShellContext IShellContextFactory.CreateSetupContext(ShellSettings settings)
        {
            _logger.LogDebug("No shell settings available. Creating shell context for setup");

            var descriptor = new ShellDescriptor {
                SerialNumber = -1,
                Features = new[] {
                    new ShellFeature { Name = "Orchard.Logging.Console" },
                    new ShellFeature { Name = "Orchard.Setup" },
                },
            };

            var blueprint = _compositionStrategy.Compose(settings, descriptor);
            var provider = _shellContainerFactory.CreateContainer(settings, blueprint);

            return new ShellContext {
                Settings = settings,
                Blueprint = blueprint,
                LifetimeScope = provider,
                Shell = provider.GetService<IOrchardShell>()
            };
        }
示例#30
0
        ShellContext IShellContextFactory.CreateShellContext(ShellSettings settings)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Creating shell context for tenant {0}", settings.Name);
            }

            var describedContext = CreateDescribedContext(settings, MinimumShellDescriptor());

            ShellDescriptor currentDescriptor;
            using (var scope = describedContext.CreateServiceScope())
            {
                var shellDescriptorManager = scope.ServiceProvider.GetService<IShellDescriptorManager>();
                currentDescriptor = shellDescriptorManager.GetShellDescriptorAsync().Result;
            }

            if (currentDescriptor != null)
            {
                return CreateDescribedContext(settings, currentDescriptor);
            }

            return describedContext;
        }
示例#31
0
 public ShellContext GetShellContext(ShellSettings settings)
 {
     return(_shellContexts[settings.Name]);
 }
示例#32
0
        public StartupLogEntriesCollector(ShellSettings shellSettings)
        {
            _shellSettings = shellSettings;

            Logger = NullLogger.Instance;
        }
 public void UpdateTenant(ShellSettings settings)
 {
     _shellSettingsManager.SaveSettings(settings);
 }
示例#34
0
 public Startup(ShellSettings shellSettings, IShellConfiguration configuration, ILogger <Startup> logger)
 {
     _tenant        = shellSettings.Name;
     _configuration = configuration;
     _logger        = logger;
 }
示例#35
0
 public Startup(ShellSettings shellSettings, IOptions <IdentityOptions> options)
 {
     _options      = options.Value;
     _tenantName   = shellSettings.Name;
     _tenantPrefix = "/" + shellSettings.RequestUrlPrefix;
 }
示例#36
0
        /// <summary>
        /// Creates a child scope from the current one.
        /// </summary>
        public static Task <ShellScope> CreateChildScopeAsync(ShellSettings settings)
        {
            var shellHost = ShellScope.Services.GetRequiredService <IShellHost>();

            return(shellHost.GetScopeAsync(settings));
        }
示例#37
0
 private string GetMediaPath(ShellOptions shellOptions, ShellSettings shellSettings, string assetsPath)
 {
     return(PathExtensions.Combine(shellOptions.ShellsApplicationDataPath, shellOptions.ShellsContainerName, shellSettings.Name, assetsPath));
 }
示例#38
0
 public AzureBlobStorageProvider(ShellSettings shellSettings, IMimeTypeProvider mimeTypeProvider, IPlatformConfigurationAccessor pca)
     : this(pca.GetSetting(Constants.MediaStorageStorageConnectionStringSettingName, shellSettings.Name, null),
            Constants.MediaStorageContainerName, shellSettings.Name, mimeTypeProvider,
            pca.GetSetting(Constants.MediaStoragePublicHostName, shellSettings.Name, null))
 {
 }
示例#39
0
 void IShellSettingsManagerEventHandler.Saved(ShellSettings settings)
 {
     TouchFile();
 }
示例#40
0
 public Startup(ShellSettings shellSettings)
 {
     _tenantName = shellSettings.Name;
 }
示例#41
0
        /// <summary>
        /// Removes the routes associated with a shell
        /// </summary>
        public void ReleaseShell(ShellSettings shellSettings)
        {
            IList <RouteBase> routes;

            _routesByShell.TryRemove(shellSettings.Name, out routes);
        }
示例#42
0
        private static SHELLEXECUTEINFO GetShellExecuteInfo(string fileName, string arguments, [NotNull] ShellSettings settings)
        {
            fileName = PathHelper.Trim(fileName);
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            SHELLEXECUTEINFO info = GetShellExecuteInfo(settings);

            info.lpFile = fileName;
            if (!string.IsNullOrWhiteSpace(arguments))
            {
                info.lpParameters = arguments.ToNullIfEmpty();
            }
            if (PathHelper.IsUnc(fileName))
            {
                info.fMask |= (int)ShellExecuteMaskFlagsEnum.SEE_MASK_CONNECTNETDRV;
            }
            return(info);
        }
示例#43
0
 public static Process ShellExec([NotNull] string fileName, ShellSettings settings)
 {
     return(ShellExec(fileName, null, settings));
 }
示例#44
0
 private string GetContentRoot(ShellOptions shellOptions, ShellSettings shellSettings)
 {
     return(Path.Combine(shellOptions.ShellsApplicationDataPath, shellOptions.ShellsContainerName, shellSettings.Name, AssetsPath));
 }
示例#45
0
 /// <summary>
 /// Execute a delegate using a child scope created from the current one.
 /// </summary>
 public static async Task UsingChildScopeAsync(ShellSettings settings, Func <ShellScope, Task> execute)
 {
     await(await CreateChildScopeAsync(settings)).UsingAsync(execute);
 }
        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 concreteRegistrationNames = new ConcurrentDictionary <Type, ConcurrentBag <NamedRegistration> >();

                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]);
                }

                var itemsToBeRegistered = new ConcurrentQueue <ItemToBeRegistered>();
                var decorators = new ConcurrentQueue <DecoratorRegistration>();

                foreach (var item in blueprint.Dependencies.Where(t => typeof(IDependency).IsAssignableFrom(t.Type)))
                {
                    // Determine if this service is an IEventHandler
                    var isEventHandler = typeof(IEventHandler).IsAssignableFrom(item.Type);

                    // Harvest any interfaces that this service decorates
                    var decoratingTypes = item.Type.GetInterfaces()
                                          .Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IDecorator <>))
                                          .Select(t => t.GetGenericArguments().First());

                    var isDecorator = decoratingTypes != null && decoratingTypes.Any();

                    if (isDecorator && isEventHandler)
                    {
                        Logger.Error(string.Format("Type `{0}` is an IDecorator, but is also an IEventHandler. Decorating IEventHandlers is not currently supported. This decorator will not be registered.", item.Type.FullName));

                        continue;
                    }

                    if (isDecorator)
                    {
                        // If this service is a decorator, we need to determine which types it decorates
                        foreach (var itemToBeRegistered in itemsToBeRegistered)
                        {
                            foreach (var interfaceType in decoratingTypes)
                            {
                                if (itemToBeRegistered.InterfaceTypes.Contains(interfaceType))
                                {
                                    if (itemToBeRegistered.DecoratedTypes == null)
                                    {
                                        itemToBeRegistered.DecoratedTypes = new List <Type>();
                                    }

                                    // Add to the collection of interfaces that are decorated only if this interface type has not previously been added
                                    if (!itemToBeRegistered.DecoratedTypes.Contains(interfaceType))
                                    {
                                        itemToBeRegistered.DecoratedTypes.Add(interfaceType);
                                    }
                                }
                            }
                        }
                    }

                    itemsToBeRegistered.Enqueue(new ItemToBeRegistered {
                        Item = item, InterfaceTypes = GetInterfacesFromBlueprint(item), DecoratingTypes = decoratingTypes, IsEventHandler = isEventHandler
                    });
                }

                foreach (var itemToBeRegistered in itemsToBeRegistered)
                {
                    var registration = RegisterType(builder, itemToBeRegistered.Item)
                                       .AsSelf()
                                       .EnableDynamicProxy(dynamicProxyContext)
                                       .InstancePerLifetimeScope();

                    var registrationName = registration.ActivatorData.ImplementationType.FullName;

                    registration.Named(registrationName, itemToBeRegistered.Item.Type);

                    foreach (var interfaceType in itemToBeRegistered.InterfaceTypes)
                    {
                        registration = SetRegistrationScope(interfaceType, registration);

                        var itemIsDecorator = itemToBeRegistered.IsDecorator(interfaceType);
                        var itemIsDecorated = itemToBeRegistered.IsDecorated(interfaceType);

                        if (!itemIsDecorated && !itemIsDecorator)
                        {
                            // This item is not decorated by another implementation of this interface type and is not a decorator.
                            // It should be registered as the implementation of this interface. The ensures that Autofac will resolve only a single implementation should there be one or more decorators.
                            registration = registration.As(interfaceType);
                        }

                        if (itemIsDecorator)
                        {
                            // This item decorates the interface currently being registered.
                            // It needs to be added to the list of decorators so that is can be registered once all of the concrete implementations have been registered.
                            decorators.Enqueue(new DecoratorRegistration(interfaceType, itemToBeRegistered, itemIsDecorated));
                        }
                        else
                        {
                            // This item is not a decorator.
                            // We need to add it to the list of concrete implementations. This allows us to know the names of the implementations that need to be decorated should a decorator for this interface exist.
                            AddConcreteRegistrationName(registrationName, interfaceType, itemToBeRegistered.Item.Type, concreteRegistrationNames);
                        }
                    }

                    if (itemToBeRegistered.IsEventHandler)
                    {
                        var interfaces = itemToBeRegistered.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 itemToBeRegistered.Item.Parameters)
                    {
                        registration = registration
                                       .WithParameter(parameter.Name, parameter.Value)
                                       .WithProperty(parameter.Name, parameter.Value);
                    }
                }

                foreach (var decorator in decorators)
                {
                    // We need to ensure that there is an implementation of this service that can be decorated
                    if (!concreteRegistrationNames.ContainsKey(decorator.InterfaceType) || concreteRegistrationNames[decorator.InterfaceType] == null || !concreteRegistrationNames[decorator.InterfaceType].Any())
                    {
                        var exception = new SystemFatalException(T("The only registered implementations of `{0}` are decorators. In order to avoid circular dependenices, there must be at least one implementation that is not marked with the `OrchardDecorator` attribute.", decorator.InterfaceType.FullName));
                        Logger.Fatal(exception, "Could not complete dependency registration as a circular dependency chain has been found.");

                        throw exception;
                    }

                    var decoratorNames = new ConcurrentBag <NamedRegistration>();

                    // For every implementation that can be decorated
                    foreach (var namedRegistration in concreteRegistrationNames[decorator.InterfaceType])
                    {
                        var registration = RegisterType(builder, decorator.ItemToBeRegistered.Item)
                                           .AsSelf()
                                           .EnableDynamicProxy(dynamicProxyContext)
                                           .InstancePerLifetimeScope();

                        registration = SetRegistrationScope(decorator.InterfaceType, registration);

                        // Create a unique name for the decorator
                        var decoratorName = string.Format("{0}-{1}", namedRegistration.Name, decorator.ItemToBeRegistered.Item.Type.FullName);
                        registration = registration.Named(decoratorName, decorator.ItemToBeRegistered.Item.Type);

                        // Tell Autofac to resolve the decorated service with the implementation that has already been registered
                        registration = registration.WithParameter(
                            (p, c) => p.ParameterType == decorator.InterfaceType,
                            (p, c) => c.ResolveNamed(namedRegistration.Name, namedRegistration.ImplementationType));

                        if (!decorator.IsDecorated)
                        {
                            // This is the last decorator in the stack, so register it as the implmentation of the interface that it is decorating
                            registration = registration.As(decorator.InterfaceType);
                        }

                        decoratorNames.Add(new NamedRegistration(decoratorName, decorator.ItemToBeRegistered.Item.Type));
                    }

                    // Update the collection of implmentation names that can be decorated to contain only the decorators (this allows us to stack decorators)
                    concreteRegistrationNames[decorator.InterfaceType] = decoratorNames;
                }

                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(ConfigurationSettingsReaderFactory.CreateConfigurationSettingsReader(optionalShellByNameConfig));
                }
                else
                {
                    var optionalShellConfig = HostingEnvironment.MapPath("~/Config/Sites.config");
                    if (File.Exists(optionalShellConfig))
                    {
                        builder.RegisterModule(ConfigurationSettingsReaderFactory.CreateConfigurationSettingsReader(optionalShellConfig));
                    }
                }

                var optionalComponentsConfig = HostingEnvironment.MapPath("~/Config/HostComponents.config");
                if (File.Exists(optionalComponentsConfig))
                {
                    builder.RegisterModule(new HostComponentsConfigModule(optionalComponentsConfig));
                }
            }));
        }
示例#47
0
 public Migrations(Lazy <ICRMSetup> crmSetup, IRepository <StatusRecord> statusRepository, ShellSettings shellSettings)
 {
     this.shellSettings    = shellSettings;
     this.crmSetup         = crmSetup;
     this.statusRepository = statusRepository;
 }
示例#48
0
        /// <summary>
        /// 创建一个外壳容器。
        /// </summary>
        /// <param name="settings">外壳设置。</param>
        /// <param name="blueprint">外壳蓝图。</param>
        /// <returns>外壳容器。</returns>
        public ILifetimeScope CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            var intermediateScope = _lifetimeScope.BeginLifetimeScope(
                builder =>
            {
                //TODO:CollectionOrderModule、CacheModule 等Module是公共的,需要验证 Root 范围注册了子级生命范围是否生效,如果生效则在外壳容器中忽略掉这些Module
                foreach (var item in blueprint.Dependencies.Where(t => typeof(IModule).IsAssignableFrom(t.Type)))
                {
                    RegisterType(builder, item)
                    .Keyed <IModule>(item.Type)
                    .InstancePerDependency();
                }
            });

            return(intermediateScope.BeginLifetimeScope(
                       "shell",
                       builder =>
            {
                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)
                                       .InstancePerLifetimeScope();

                    foreach (var interfaceType in item.Type.GetInterfaces()
                             .Where(itf => typeof(IDependency).IsAssignableFrom(itf) &&
                                    !typeof(IEventHandler).IsAssignableFrom(itf)))
                    {
                        registration = registration.As(interfaceType);
                        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))
                    {
                        continue;
                    }
                    var interfaces = item.Type.GetInterfaces();
                    foreach (var interfaceType in interfaces)
                    {
                        if (interfaceType.GetInterface(typeof(IEventHandler).Name) != null)
                        {
                            registration = registration.Named <IEventHandler>(interfaceType.Name);
                        }
                    }
                }

                _shellContainerRegistrationses.Invoke(i => i.Registrations(builder, blueprint), NullLogger.Instance);
            }));
        }
示例#49
0
        public async Task ShouldFilterByContentItemIndexWhenSqlTablePrefixIsUsed()
        {
            await _initializeTask;

            _prefixedStore.RegisterIndexes <AnimalIndexProvider>();

            using (var services = new FakeServiceCollection())
            {
                services.Populate(new ServiceCollection());
                services.Services.AddScoped(x => _prefixedStore.CreateSession());

                var shellSettings = new ShellSettings();
                shellSettings["TablePrefix"] = _prefix;

                services.Services.AddScoped(x => shellSettings);
                services.Build();

                var returnType = new ListGraphType <StringGraphType>();
                returnType.ResolvedType = new StringGraphType()
                {
                    Name = "Animal"
                };

                var animalWhereInput = new AnimalPartWhereInput();
                var inputs           = new FieldType {
                    Name = "Inputs", Arguments = new QueryArguments {
                        new QueryArgument <WhereInputObjectGraphType> {
                            Name = "where", Description = "filters the animals", ResolvedType = animalWhereInput
                        }
                    }
                };

                var context = new ResolveFieldContext
                {
                    Arguments   = new Dictionary <string, object>(),
                    UserContext = new GraphQLContext
                    {
                        ServiceProvider = services
                    },
                    ReturnType      = returnType,
                    FieldDefinition = inputs
                };

                var ci = new ContentItem {
                    ContentType = "Animal", Published = true, ContentItemId = "1", ContentItemVersionId = "1"
                };
                ci.Weld(new AnimalPart {
                    Name = "doug"
                });

                var session = ((GraphQLContext)context.UserContext).ServiceProvider.GetService <ISession>();
                session.Save(ci);
                await session.CommitAsync();

                var type = new ContentItemsFieldType("Animal", new Schema(), Options.Create(new GraphQLContentOptions()), Options.Create(new GraphQLSettings {
                    DefaultNumberOfResults = 10
                }));

                context.Arguments["where"] = JObject.Parse("{ contentItemId: \"1\" }");
                var dogs = await((AsyncFieldResolver <IEnumerable <ContentItem> >)type.Resolver).Resolve(context);

                Assert.Single(dogs);
                Assert.Equal("doug", dogs.First().As <AnimalPart>().Name);
            }
        }
示例#50
0
 public static bool ShellExecAndWaitFor([NotNull] string execName, ShellSettings settings, CancellationToken token = default(CancellationToken))
 {
     return(ShellExecAndWaitFor(execName, null, settings, token));
 }
示例#51
0
 public Startup(IOptions <AdminOptions> adminOptions, ShellSettings shellSettings)
 {
     _adminOptions = adminOptions.Value;
     _tenantName   = shellSettings.Name;
 }
示例#52
0
        private bool TryMatchInternal(string host, string appRelativePath, bool fallbackToDefault, out ShellSettings result)
        {
            // We can skip some checks for port matching if we know the host doesn't contain one
            var hasPort = host.Contains(':');

            // 1. Search for Host:Port + Prefix match

            if (!hasPort || !_shellsByHostAndPrefix.TryGetValue(GetHostAndPrefix(host, appRelativePath, true), out result))
            {
                // 2. Search for Host + Prefix match

                if (!_shellsByHostAndPrefix.TryGetValue(GetHostAndPrefix(host, appRelativePath, false), out result))
                {
                    // 3. Search for Host:Port only match

                    if (!hasPort || !_shellsByHostAndPrefix.TryGetValue(GetHostAndPrefix(host, "/", true), out result))
                    {
                        // 4. Search for Host only match

                        if (!_shellsByHostAndPrefix.TryGetValue(GetHostAndPrefix(host, "/", false), out result))
                        {
                            // 5. Search for Prefix only match

                            if (!_shellsByHostAndPrefix.TryGetValue(GetHostAndPrefix("", appRelativePath, false), out result))
                            {
                                result = null;
                                return(false);
                            }
                        }
                    }
                }
            }

            return(true);
        }
示例#53
0
        public static ShellSettings ParseSettings(string text)
        {
            var shellSettings = new ShellSettings();

            if (String.IsNullOrEmpty(text))
            {
                return(shellSettings);
            }

            var    settings = new StringReader(text);
            string setting;

            while ((setting = settings.ReadLine()) != null)
            {
                if (string.IsNullOrWhiteSpace(setting))
                {
                    continue;
                }
                var separatorIndex = setting.IndexOf(Separator);
                if (separatorIndex == -1)
                {
                    continue;
                }
                string key   = setting.Substring(0, separatorIndex).Trim();
                string value = setting.Substring(separatorIndex + 1).Trim();

                if (!value.Equals(EmptyValue, StringComparison.OrdinalIgnoreCase))
                {
                    switch (key)
                    {
                    case "Name":
                        shellSettings.Name = value;
                        break;

                    case "DataProvider":
                        shellSettings.DataProvider = value;
                        break;

                    case "State":
                        TenantState state;
                        shellSettings.State = Enum.TryParse(value, true, out state) ? state : TenantState.Invalid;
                        break;

                    case "DataConnectionString":
                        shellSettings.DataConnectionString = value;
                        break;

                    case "RequestUrlHost":
                        shellSettings.RequestUrlHost = value;
                        break;

                    case "RequestUrlPrefix":
                        shellSettings.RequestUrlPrefix = value;
                        break;

                    case "EncryptionAlgorithm":
                        shellSettings.EncryptionAlgorithm = value;
                        break;

                    case "EncryptionKey":
                        shellSettings.EncryptionKey = value;
                        break;

                    case "HashAlgorithm":
                        shellSettings.HashAlgorithm = value;
                        break;

                    case "HashKey":
                        shellSettings.HashKey = value;
                        break;

                    case "Themes":
                        shellSettings.Themes = value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        break;

                    default:
                        shellSettings[key] = value;
                        break;
                    }
                }
            }

            return(shellSettings);
        }
示例#54
0
 public TenantContext(ShellSettings settings)
 {
     _settings = settings;
 }
示例#55
0
 public static bool ShellExecAndWaitFor([NotNull] string execName, string arguments, ShellSettings settings, CancellationToken token = default(CancellationToken))
 {
     token.ThrowIfCancellationRequested();
     return(ShellExecAndWaitFor(execName, arguments, settings, token.WaitHandle));
 }
示例#56
0
        private bool TryMatchStarMapping(string host, string appRelativePath, bool fallbackToDefault, out ShellSettings result)
        {
            if (TryMatchInternal("*." + host, appRelativePath, fallbackToDefault, out result))
            {
                return(true);
            }

            var index = -1;

            // Take the longest subdomain and look for a mapping
            while (-1 != (index = host.IndexOf('.', index + 1)))
            {
                if (TryMatchInternal("*" + host.Substring(index), appRelativePath, fallbackToDefault, out result))
                {
                    return(true);
                }
            }

            result = null;
            return(false);
        }
示例#57
0
 public static bool ShellExecAndWaitFor([NotNull] string fileName, ShellSettings settings, WaitHandle awaitableHandle)
 {
     return(ShellExecAndWaitFor(fileName, null, settings, awaitableHandle));
 }
示例#58
0
        public static bool ShellExecAndWaitFor([NotNull] string fileName, string arguments, ShellSettings settings, WaitHandle awaitableHandle)
        {
            fileName = fileName.Trim();
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException(nameof(fileName));
            }
            settings ??= ShellSettings.Default;

            SHELLEXECUTEINFO info = GetShellExecuteInfo(fileName, arguments, settings);

            using (Process process = InternalShellExec(info))
            {
                if (process == null)
                {
                    return(false);
                }
                if (!settings.JobHandle.IsInvalidHandle())
                {
                    ProcessJob.AddProcess(settings.JobHandle, process);
                }

                if (!awaitableHandle.IsAwaitable())
                {
                    process.WaitForExit();
                    return(true);
                }

                bool processReallyExited = false;
                process.Exited += (_, _) => processReallyExited = true;

                SafeWaitHandle   waitHandle           = null;
                ManualResetEvent processFinishedEvent = null;

                try
                {
                    waitHandle = new SafeWaitHandle(process.Handle, false);
                    if (!waitHandle.IsAwaitable())
                    {
                        return(false);
                    }
                    processFinishedEvent = new ManualResetEvent(false)
                    {
                        SafeWaitHandle = waitHandle
                    };
                    if (!awaitableHandle.IsAwaitable())
                    {
                        return(false);
                    }

                    WaitHandle[] waitHandles =
                    {
                        processFinishedEvent,
                        awaitableHandle
                    };

                    int ndx = waitHandles.WaitAny();
                    if (ndx != 0)
                    {
                        return(false);
                    }

                    if (!processReallyExited && process.IsAwaitable())
                    {
                        if (!process.WaitForExit(TimeSpanHelper.HALF))
                        {
                            ndx = -1;
                        }
                    }

                    process.Die();
                    return(ndx == 0);
                }
                finally
                {
                    processFinishedEvent?.Close();
                    ObjectHelper.Dispose(ref processFinishedEvent);
                    waitHandle?.Close();
                    ObjectHelper.Dispose(ref waitHandle);
                }
            }
        }
示例#59
0
        public void Add(RouteBase route, ShellSettings shellSettings)
        {
            var routes = _routesByShell.GetOrAdd(shellSettings.Name, key => new List <RouteBase>());

            routes.Add(route);
        }
 public void SaveSettings(ShellSettings settings)
 {
     _shellSettings.AddOrUpdate(settings.Name, settings, (key, existing) => settings);
 }