示例#1
0
        public MapViewerForm()
        {
            InitializeComponent();

            _mainUnitOfWork   = ContainerManager.GetContainer(ContainerNames.Main).Resolve <IUnitOfWork>();
            _componentBuilder = ContainerManager.GetContainer(ContainerNames.Main).Resolve <IComponentBuilder>();
            IServiceProvider serviceProvider = new DelegateServiceLocator(GetServiceByTypeAndName, GetAllServicesByType);

            _componentContext = new ComponentContext(serviceProvider, components);

            BindToMap();
            _engineEditor    = new EngineEditorClass();
            _eventAggregator = ContainerManager.GetContainer().Resolve <IEventAggregator>();
            InitEvent();//订阅事件
        }
示例#2
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            var basePath = Context.Server.MapPath("~/");
            TemplateVirtualPathProvider.Bootstrap(basePath);

            // 使ってみたかったんだよ。
            var serviceLocator = new DelegateServiceLocator();
            serviceLocator.Entry<ITemplateStore>(
                () => new HttpContextTemplateStore(new HttpContextWrapper(HttpContext.Current))
            );
            DependencyResolver.SetResolver(serviceLocator);
        }
示例#3
0
        protected void Application_Start(object sender, EventArgs e)
        {
            var rootDir = new DirectoryInfo(this.Server.MapPath("~/bin"));

            var config = new IniFileConfigRepository(filePath: Path.Combine(rootDir.FullName, "config.ini"),
                                                     isReadOnly: false);

            // ServiceLocator
            {
                this.GlobalCompositionCatalog = new AggregateCatalog();

                // assemblies
                {
                    var asms = new HashSet <Assembly>();
                    asms.Add(typeof(global::MarcelJoachimKloubert.ServerAdmin.IServerAdminObject).Assembly);
                    asms.Add(this.GetType().Assembly);

                    foreach (var a in asms)
                    {
                        this.GlobalCompositionCatalog.Catalogs.Add(new AssemblyCatalog(a));
                    }
                }

                this.GlobalCompositionContainer = new CompositionContainer(this.GlobalCompositionCatalog, true);
                this.GlobalCompositionContainer.ComposeExportedValue <global::MarcelJoachimKloubert.CLRToolbox.Configuration.IConfigRepository>(config.MakeReadOnly());
                this.GlobalCompositionContainer.ComposeExportedValue <global::System.Web.HttpApplication>(this);

                var innerLocator = new ExportProviderServiceLocator(this.GlobalCompositionContainer);

                this.GlobalServiceLocator = new DelegateServiceLocator(innerLocator);

                this.GlobalCompositionContainer.ComposeExportedValue <global::MarcelJoachimKloubert.CLRToolbox.ServiceLocation.IServiceLocator>(this.GlobalServiceLocator);
                this.GlobalCompositionContainer.ComposeExportedValue <global::MarcelJoachimKloubert.CLRToolbox.ServiceLocation.Impl.DelegateServiceLocator>(this.GlobalServiceLocator);
                this.GlobalCompositionContainer.ComposeExportedValue <global::MarcelJoachimKloubert.CLRToolbox.ServiceLocation.Impl.ExportProviderServiceLocator>(innerLocator);

                ServiceLocator.SetLocator(this.GlobalServiceLocator);
            }
        }
示例#4
0
        // Public Methods (2) 

        /// <summary>
        /// Reloads the list of plugins.
        /// </summary>
        public void ReloadPlugIns()
        {
            try
            {
                var loadedPlugIns = new List <IPlugIn>();

                var plugInDir = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "PlugIns"));
                if (plugInDir.Exists)
                {
                    foreach (var file in plugInDir.GetFiles("*.dll"))
                    {
                        try
                        {
                            var asmBlob = File.ReadAllBytes(file.FullName);
                            var asm     = Assembly.Load(asmBlob);

                            var catalog = new AssemblyCatalog(asm);

                            var ctx = new PlugInContext();
                            ctx.Assembly     = asm;
                            ctx.AssemblyFile = file.FullName;

                            var container = new CompositionContainer(catalog,
                                                                     isThreadSafe: true);
                            container.ComposeExportedValue <global::MarcelJoachimKloubert.DragNBatch.PlugIns.IPlugInContext>(ctx);

                            var instances = new MultiInstanceComposer <IPlugIn>(container);
                            instances.RefeshIfNeeded();

                            // service locator
                            {
                                var mefLocator = new ExportProviderServiceLocator(container);

                                var sl = new DelegateServiceLocator(mefLocator);

                                ctx.ServiceLocator = sl;
                            }

                            var initializedPlugIns = new List <IPlugIn>();
                            foreach (var i in instances.Instances)
                            {
                                try
                                {
                                    i.Initialize(ctx);

                                    initializedPlugIns.Add(i);
                                }
                                catch (Exception ex)
                                {
                                    this.OnError(ex);
                                }
                            }

                            ctx.PlugIns = initializedPlugIns.ToArray();
                            loadedPlugIns.AddRange(initializedPlugIns);
                        }
                        catch (Exception ex)
                        {
                            this.OnError(ex);
                        }
                    }
                }

                this.PlugIns.Clear();
                this.PlugIns.AddRange(loadedPlugIns);
            }
            catch (Exception ex)
            {
                this.OnError(ex);
            }
        }
示例#5
0
        protected void Application_Start(object sender, EventArgs e)
        {
            var rootDir = new DirectoryInfo(this.Server.MapPath("~/bin"));

            // app context
            var app = new CloudApp();
            {
                IConfigRepository config;
                var configIni = new FileInfo(Path.Combine(rootDir.FullName,
                                                          "config.ini"));
                if (configIni.Exists)
                {
                    config = new IniFileConfigRepository(configIni);
                }
                else
                {
                    config = new KeyValuePairConfigRepository();
                }

                app.Config = config.MakeReadOnly();
            }

            // principal repository
            var pricRepo = new PrincipalRepository();

            {
                pricRepo.LocalDataDirectory = rootDir.FullName;
                {
                    string temp;
                    if (app.Config.TryGetValue <string>("Data", out temp, "Directories") &&
                        string.IsNullOrWhiteSpace(temp) == false)
                    {
                        pricRepo.LocalDataDirectory = temp.Trim();
                    }
                }

                var iniFile = new FileInfo(Path.Combine(rootDir.FullName, "users.ini"));
                if (iniFile.Exists)
                {
                    pricRepo.UserRepository = new IniFileConfigRepository(iniFile);
                }

                pricRepo.Reload();
            }

            // URL routes
            {
                // files
                RouteTable.Routes.Add(new Route
                                      (
                                          "files",
                                          new FilesHttpHandler()
                                      ));

                // messages
                RouteTable.Routes.Add(new Route
                                      (
                                          "messages",
                                          new MessagesHttpHandler()
                                      ));
            }

            // ServiceLocator
            {
                this.GlobalCompositionCatalog = new AggregateCatalog();
                this.GlobalCompositionCatalog.Catalogs.Add(new AssemblyCatalog(typeof(global::MarcelJoachimKloubert.CloudNET.Classes.ICloudApp).Assembly));

                this.GlobalCompositionContainer = new CompositionContainer(this.GlobalCompositionCatalog, true);
                this.GlobalCompositionContainer.ComposeExportedValue <global::MarcelJoachimKloubert.CloudNET.Classes.ICloudApp>(app);
                this.GlobalCompositionContainer.ComposeExportedValue <global::MarcelJoachimKloubert.CloudNET.Classes.Security.IPrincipalRepository>(pricRepo);
                this.GlobalCompositionContainer.ComposeExportedValue <global::System.Web.HttpApplication>(this);

                var innerLocator = new ExportProviderServiceLocator(this.GlobalCompositionContainer);

                this.GlobalServiceLocator = new DelegateServiceLocator(innerLocator);

                this.GlobalCompositionContainer.ComposeExportedValue <global::MarcelJoachimKloubert.CLRToolbox.ServiceLocation.IServiceLocator>(this.GlobalServiceLocator);
                this.GlobalCompositionContainer.ComposeExportedValue <global::MarcelJoachimKloubert.CLRToolbox.ServiceLocation.Impl.DelegateServiceLocator>(this.GlobalServiceLocator);
                this.GlobalCompositionContainer.ComposeExportedValue <global::MarcelJoachimKloubert.CLRToolbox.ServiceLocation.Impl.ExportProviderServiceLocator>(innerLocator);

                ServiceLocator.SetLocator(this.GlobalServiceLocator);
            }

            this.Application[APP_VAR_APPCONTEXT] = app;
            this.Application[APP_VAR_PRINCIPALS] = pricRepo;
        }
        private void StartServer()
        {
            const string LOG_TAG_PREFIX = "ApplicationServer::StartServer::";

            AggregateException ex = null;

            this.ReinitTrustedCompositionCatalog();

            // assemblies with services
            {
                var serviceDir = new DirectoryInfo(Path.Combine(this.WorkingDirectory, "services")).CreateDirectoryDeep();

                this.LoadAndAddTrustedAssemblies(serviceDir.GetFiles("*.dll"),
                                                 LOG_TAG_PREFIX);
            }

            // assemblies with functions
            {
                var funcDir = new DirectoryInfo(Path.Combine(this.WorkingDirectory, "funcs")).CreateDirectoryDeep();

                this.LoadAndAddTrustedAssemblies(funcDir.GetFiles("*.dll"),
                                                 LOG_TAG_PREFIX);
            }

            // web interface
            {
                IList <Assembly> webInterfaceAssemblies = new SynchronizedCollection <Assembly>();

                var webDir = new DirectoryInfo(Path.Combine(this.WorkingDirectory, "web")).CreateDirectoryDeep();
                this.LoadAndAddTrustedAssemblies(webDir.GetFiles("*.dll"),
                                                 LOG_TAG_PREFIX);

                try
                {
                    this.DisposeOldWebInterfaceServer();

                    //TODO read from configuration
                    var newWebInterfaceServer = ServiceLocator.Current.GetInstance <IHttpServer>();
                    {
                        // HTTPs ?
                        {
                            bool?useHttps;
                            this.StartupConfig
                            .TryGetValue <bool?>(category: CONFIG_CATEGORY_WEBINTERFACE,
                                                 name: CONFIG_VALUE_USE_HTTPS,
                                                 value: out useHttps,
                                                 defaultVal: DEFAULT_CONFIG_VALUE_USE_HTTPS);

                            newWebInterfaceServer.UseSecureHttp = useHttps ?? DEFAULT_CONFIG_VALUE_USE_HTTPS;
                        }

                        // TCP port
                        {
                            int?port;
                            this.StartupConfig
                            .TryGetValue <int?>(category: CONFIG_CATEGORY_WEBINTERFACE,
                                                name: CONFIG_VALUE_PORT,
                                                value: out port,
                                                defaultVal: DEFAULT_CONFIG_VALUE_WEBINTERFACE_PORT);

                            newWebInterfaceServer.Port = port ?? DEFAULT_CONFIG_VALUE_WEBINTERFACE_PORT;
                        }

                        if (newWebInterfaceServer.UseSecureHttp)
                        {
                            // SSL thumbprint
                            {
                                newWebInterfaceServer.SetSslCertificateByThumbprint(this.StartupConfig
                                                                                    .GetValue <IEnumerable <char> >(category: CONFIG_CATEGORY_WEBINTERFACE,
                                                                                                                    name: CONFIG_VALUE_SSL_THUMBPRINT));
                            }
                        }
                    }

                    var newHandler = new WebInterfaceHandler(this, newWebInterfaceServer);
                    this._webHandler = newHandler;

                    newHandler.Start();
                }
                catch (Exception e)
                {
                    this.Logger
                    .Log(msg: e.GetBaseException() ?? e,
                         tag: LOG_TAG_PREFIX + "WebInterface",
                         categories: LoggerFacadeCategories.Errors);

                    this.DisposeOldWebInterfaceServer();
                }
            }

            var moduleList = this.Modules;

            if (moduleList != null)
            {
                ex = moduleList.OfType <global::System.IDisposable>()
                     .ForAllAsync(ctx =>
                {
                    var m         = ctx.Item;
                    var doDispose = true;

                    var dispObj = m as ITMDisposable;
                    if (dispObj != null)
                    {
                        doDispose = !dispObj.IsDisposed;
                    }

                    if (doDispose)
                    {
                        m.Dispose();
                    }
                }, throwExceptions: false);
            }

            if (ex != null)
            {
                this.Logger
                .Log(msg: ex,
                     tag: LOG_TAG_PREFIX + "UnloadOldModules",
                     categories: LoggerFacadeCategories.Errors);
            }

            IList <IAppServerModule> newModules = new SynchronizedCollection <IAppServerModule>();

            var modDir = new DirectoryInfo(Path.Combine(this.WorkingDirectory, "modules")).CreateDirectoryDeep();
            {
                ex = modDir.GetFiles("*.dll")
                     .ForAllAsync(ctx =>
                {
                    var f = ctx.Item;

                    var trustedCatalog = ctx.State.CompositionCatalog.Clone(cloneCatalogData: true);
                    var asmName        = AssemblyName.GetAssemblyName(f.FullName);
                    if (!trustedCatalog.IsTrustedAssembly(asmName))
                    {
#if DEBUG
                        var s = string.Format("INSERT INTO [Security].[TrustedAssemblies] (TrustedAssemblyKey, Name) VALUES (0x{0}, N'{1}');",
                                              asmName.GetPublicKey().AsHexString(),
                                              asmName.FullName);
#endif
                        ctx.State
                        .Logger
                        .Log(categories: LoggerFacadeCategories.Warnings,
                             msg: string.Format("'{0}' is no trusted module!",
                                                f.FullName));

                        return;
                    }

                    var asmBlob = File.ReadAllBytes(f.FullName);
                    var asm     = Assembly.Load(asmBlob);

                    trustedCatalog.AddAssembly(asm);

                    CompositionContainer container;
                    DelegateServiceLocator serviceLocator;
                    {
                        var catalog = new AggregateCatalog();
                        catalog.Catalogs.Add(trustedCatalog);

                        container = new CompositionContainer(catalog,
                                                             isThreadSafe: true);

                        serviceLocator = new DelegateServiceLocator(new ExportProviderServiceLocator(container));
                    }

                    var modules = serviceLocator.GetAllInstances <IAppServerModule>().AsArray();
                    if (modules.Length == 1)
                    {
                        CompositionHelper.ComposeExportedValueEx(container,
                                                                 modules[0]);
                    }
                    else
                    {
                        foreach (var m in modules)
                        {
                            CompositionHelper.ComposeExportedValue(container,
                                                                   m,
                                                                   m.GetType());
                        }
                    }

                    modules.ForAll(ctx2 =>
                    {
                        var m = ctx2.Item;
                        if (m.IsInitialized)
                        {
                            // no need to initialize
                            return;
                        }

                        //TODO: add implementation(s)
                        var logger = new AggregateLogger();

                        var moduleRootDir = new DirectoryInfo(Path.Combine(ctx2.State.ModuleDirectory,
                                                                           m.Name)).CreateDirectoryDeep();

                        var moduleCtx    = new SimpleAppServerModuleContext(m);
                        moduleCtx.Config = new IniFileConfigRepository(Path.Combine(moduleRootDir.FullName,
                                                                                    "config.ini"));
                        moduleCtx.InnerServiceLocator = ctx2.State.ServiceLocator;
                        moduleCtx.Logger       = logger;
                        moduleCtx.OtherModules = ctx2.State.AllModules
                                                 .Where(CreateWherePredicateForExtractingOtherModules(m));
                        moduleCtx.SetAssemblyFile(ctx2.State.AssemblyFile.FullName);

                        var moduleInitCtx           = new SimpleAppServerModuleInitContext();
                        moduleInitCtx.ModuleContext = moduleCtx;
                        moduleInitCtx.RootDirectory = moduleRootDir.FullName;

                        m.Initialize(moduleInitCtx);

                        ctx2.State
                        .NewModules
                        .Add(m);
                    }, actionState: new
                    {
                        AllModules      = modules,
                        AssemblyFile    = f,
                        ModuleDirectory = ctx.State.ModuleDirectory,
                        NewModules      = ctx.State.NewModules,
                        ServiceLocator  = serviceLocator,
                    }, throwExceptions: true);
                }, actionState: new
                {
                    CompositionCatalog = this.TrustedCompositionCatalog
                                         .Clone(cloneCatalogData: false),
                    Logger          = this.Logger,
                    ModuleDirectory = modDir.FullName,
                    NewModules      = newModules,
                }, throwExceptions: false);

                if (ex != null)
                {
                    this.Logger
                    .Log(msg: ex,
                         tag: LOG_TAG_PREFIX + "LoadModules",
                         categories: LoggerFacadeCategories.Errors);
                }
            }

            this.Modules = newModules.Where(m => m.IsInitialized)
                           .ToArray();

            if (this.Modules.Length > 0)
            {
                this.Logger
                .Log(msg: string.Format("{0} modules were loaded.", this.Modules.Length),
                     tag: LOG_TAG_PREFIX + "LoadModules",
                     categories: LoggerFacadeCategories.Information);
            }
            else
            {
                this.Logger
                .Log(msg: "No module was loaded.",
                     tag: LOG_TAG_PREFIX + "LoadModules",
                     categories: LoggerFacadeCategories.Warnings);
            }

            this.RefreshEntityAssemblyList();

            ex = newModules.Where(m => m.CanStart &&
                                  m.IsInitialized)
                 .ForAllAsync(ctx =>
            {
                var m = ctx.Item;

                m.Start();
            }, throwExceptions: false);

            if (ex != null)
            {
                this.Logger
                .Log(msg: ex,
                     tag: LOG_TAG_PREFIX + "StartModules",
                     categories: LoggerFacadeCategories.Errors);
            }
        }
        // Protected Methods (3) 

        /// <summary>
        ///
        /// </summary>
        /// <see cref="AppServerBase.OnInitialize(IAppServerInitContext, ref bool)" />
        protected override void OnInitialize(IAppServerInitContext initContext, ref bool isInitialized)
        {
            this.Arguments = (initContext.Arguments ?? Enumerable.Empty <string>()).OfType <string>()
                             .ToArray();

            this.WorkingDirectory = initContext.WorkingDirectory;
            if (string.IsNullOrWhiteSpace(this.WorkingDirectory))
            {
                this.WorkingDirectory = Environment.CurrentDirectory;
            }

            this.StartupConfig = new IniFileConfigRepository(Path.Combine(this.WorkingDirectory,
                                                                          "config.ini"),
                                                             false);

            var trustedAssemblyKeys = this.LoadTrustedAssemblyKeyList();

            this.EntityAssemblies = new SynchronizedCollection <Assembly>();
            this.RefreshEntityAssemblyList();

            // service locator
            CompositionContainer   compContainer;
            AggregateCatalog       compCatalog;
            DelegateServiceLocator serviceLocator;
            {
                compCatalog = new AggregateCatalog();
                compCatalog.Catalogs
                .Add(this.TrustedCompositionCatalog = new StrongNamedAssemblyPartCatalog(trustedAssemblyKeys));

                this.ReinitTrustedCompositionCatalog();

                compContainer = new CompositionContainer(compCatalog,
                                                         isThreadSafe: true);

                var mefServiceLocator = new ExportProviderServiceLocator(compContainer);
                serviceLocator = new DelegateServiceLocator(mefServiceLocator);

                serviceLocator.RegisterSingleProvider <global::MarcelJoachimKloubert.CLRToolbox.Templates.Text.Html.IHtmlTemplate>(WebInterfaceHandler.GetHtmlTemplate);
            }

            // logger
            AggregateLogger logger;
            DelegateLogger  loggerFuncs;

            {
                loggerFuncs = new DelegateLogger();

                logger = new AggregateLogger();
                logger.Add(loggerFuncs);

                var outerLogger = initContext.Logger;
                if (outerLogger != null)
                {
                    logger.Add(outerLogger);
                }

                serviceLocator.RegisterMultiProvider(this.GetAllLoggers, false);

                compContainer.ComposeExportedValue <global::MarcelJoachimKloubert.CLRToolbox.Diagnostics.ILoggerFacade>(new AsyncLogger(logger));
            }

            this.LoggerFuncs = loggerFuncs;
            this.Logger      = logger;

            this.GlobalCompositionCatalog   = compCatalog;
            this.GlobalCompositionContainer = compContainer;

            compContainer.ComposeExportedValue <global::MarcelJoachimKloubert.ApplicationServer.ApplicationServer>(this);
            compContainer.ComposeExportedValue <global::MarcelJoachimKloubert.ApplicationServer.IAppServer>(this);

            this.GlobalServiceLocator = serviceLocator;
            ServiceLocator.SetLocatorProvider(this.GetGlobalServiceLocator);
        }