Exemplo n.º 1
0
        private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options)
        {
            SystemEvents.SessionEnding += SystemEvents_SessionEnding;

            // Allow all https requests
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });

            var fileSystem = new CommonFileSystem(logManager.GetLogger("FileSystem"), false, true);

            var nativeApp = new NativeApp();

            _appHost = new ApplicationHost(appPaths, logManager, options, fileSystem, "MBServer.Mono", nativeApp);

            if (options.ContainsOption("-v"))
            {
                Console.WriteLine(_appHost.ApplicationVersion.ToString());
                return;
            }

            Console.WriteLine("appHost.Init");

            var initProgress = new Progress<double>();

            var task = _appHost.Init(initProgress);
            Task.WaitAll(task);

            Console.WriteLine("Running startup tasks");

            task = _appHost.RunStartupTasks();
            Task.WaitAll(task);

            task = ApplicationTaskCompletionSource.Task;

            Task.WaitAll(task);
        }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            var applicationPath = Assembly.GetEntryAssembly().Location;

            var options = new StartupOptions();

            // Allow this to be specified on the command line.
            var customProgramDataPath = options.GetOption("-programdata");

            var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath);

            var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");

            logManager.ReloadLogger(LogSeverity.Info);
            logManager.AddConsoleOutput();

            var logger = _logger = logManager.GetLogger("Main");

            ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            try
            {
                RunApplication(appPaths, logManager, options);
            }
            finally
            {
                logger.Info("Shutting down");

                _appHost.Dispose();
            }
        }
Exemplo n.º 3
0
        public virtual void FixtureInitialize()
        {
            String virDir      = GetVirtualDir();
            String physicalDir = GetPhysicalDir();

            if (!Path.IsPathRooted(physicalDir))
            {
                DirectoryInfo dinfo = new DirectoryInfo(Path.Combine(
                                                            AppDomain.CurrentDomain.SetupInformation.ApplicationBase, physicalDir));

                physicalDir = dinfo.FullName;
            }

            if (!Directory.Exists(Path.Combine(physicalDir, "bin")) ||
                !File.Exists(Path.Combine(physicalDir, "web.config")))
            {
                String message = String.Format("The path specified for the " +
                                               "web project doesnt look as a web project dir (bin directory or web.config missing): {0}", physicalDir);
                throw new ConfigurationException(message);
            }

            host = (WebAppHost)ApplicationHost.CreateApplicationHost(
                typeof(WebAppHost), virDir, physicalDir);

            host.Configure(virDir, physicalDir);
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            ApplicationHost host = new ApplicationHost();

            log.Info("search for features");
            foreach (IFeature feature in FeatureSeeker.Seek(Assembly.GetExecutingAssembly()))
            {
                log.Info("register feature: " + feature.GetType());
                host.RegisterService(feature);
            }

            host.Build();

            MainForm form = host.GetService<MainForm>();
            if (args.Length == 1)
            {
                host.GetService<ICoverageReportService>().LoadFromFile(args[0]);
            }

            Application.Run(form);

            host.Destroy();
        }
Exemplo n.º 5
0
        private static LibraryOptions LoadLibraryOptions(string path)
        {
            try
            {
                var result = XmlSerializer.DeserializeFromFile(typeof(LibraryOptions), GetLibraryOptionsPath(path)) as LibraryOptions;
                if (result == null)
                {
                    return(new LibraryOptions());
                }

                foreach (var mediaPath in result.PathInfos)
                {
                    if (!string.IsNullOrEmpty(mediaPath.Path))
                    {
                        mediaPath.Path = ApplicationHost.ExpandVirtualPath(mediaPath.Path);
                    }
                }

                return(result);
            }
            catch (FileNotFoundException)
            {
                return(new LibraryOptions());
            }
            catch (IOException)
            {
                return(new LibraryOptions());
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error loading library options");

                return(new LibraryOptions());
            }
        }
Exemplo n.º 6
0
        public void Start()
        {
            Host = (HttpListenerAspNetHost)ApplicationHost.CreateApplicationHost(
                typeof(HttpListenerAspNetHost), _virtualDir, _physicalDir);

            Host.Configure(_prefixes, _virtualDir, _physicalDir);
            Host.Start();
        }
Exemplo n.º 7
0
        public virtual void Start()
        {
            Console.WriteLine("ApplicationHost.GetInstance().BeginStart();");
            ApplicationHost.GetInstance().Start();
            ApplicationHost.GetInstance().Exit += new EventHandler(TestBase_OnExit);

            JXL.Workplace.PaymentExtension.PaymentSources.Initialize();
        }
Exemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the UIViewControllerFactory class.
        /// </summary>
        /// <param name="applicationHost">The host for the current application.</param>
        /// <param name="viewControllerTypes">A list of known view controller types and their associated view models.</param>
        public UIViewControllerFactory(ApplicationHost applicationHost, ViewControllerTypes viewControllerTypes)
        {
            Throw.IfArgumentNull(applicationHost, nameof(applicationHost));
            Throw.IfArgumentNull(viewControllerTypes, nameof(viewControllerTypes));

            this.applicationHost     = applicationHost;
            this.viewControllerTypes = viewControllerTypes;
        }
Exemplo n.º 9
0
        protected virtual void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            ApplicationHost.GetInstance().Start();
            PaymentSources.Initialize();
        }
Exemplo n.º 10
0
        protected internal virtual ICertificateResolver CreateCertificateResolver()
        {
            var applicationDomain        = new ApplicationHost(AppDomain.CurrentDomain, this.HostEnvironment);
            var fileCertificateResolver  = new FileCertificateResolver(applicationDomain);
            var storeCertificateResolver = new StoreCertificateResolver();

            return(new CertificateResolver(fileCertificateResolver, storeCertificateResolver));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="App" /> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        public App(ApplicationHost appHost, ILogger logger, bool isRunningAsService)
        {
            _appHost = appHost;
            _logger = logger;
            IsRunningAsService = isRunningAsService;

            InitializeComponent();
        }
Exemplo n.º 12
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="onwer"></param>
 /// <param name="args"></param>
 public void OnStop(ApplicationHost onwer, CommandArguments args)
 {
     this.WaitForMainAppExit();
     foreach (var item in this.extensions)
     {
         item.OnStop(this.ApplicationHost, this.CommandArguments);
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Creates a new instance of the specified view model.
        /// </summary>
        /// <param name="applicationHost">The global application host.</param>
        /// <param name="navigation">Used to handle navigation between screens.</param>
        /// <param name="parameter">An optional parameter used to initialize the view model.</param>
        public static TViewModel Create <TViewModel>(ApplicationHost applicationHost, INavigation navigation, object parameter = null)
            where TViewModel : ViewModel
        {
            TViewModel viewModel = (TViewModel)ViewModelFactory.Create(typeof(TViewModel));

            viewModel.Initialize(applicationHost, navigation, parameter);
            return(viewModel);
        }
Exemplo n.º 14
0
 private static void CreateAspApplicationHost()
 {
     //创建并配置用于承载 ASP.NET 的应用程序域。
     _appHost = (AspApplicationHost)ApplicationHost.CreateApplicationHost(typeof(AspApplicationHost), "/", _pPath);
     _appHost.SetRequestBroker(_broker);
     //请求执行委托
     _appFunc = new AppFunc(_appHost.Process);
 }
Exemplo n.º 15
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        public static void Main(string[] args)
        {
            var options = new StartupOptions(Environment.GetCommandLineArgs());

            var environmentInfo = new EnvironmentInfo();

            var    baseDirectory = System.AppContext.BaseDirectory;
            string archPath      = baseDirectory;

            if (environmentInfo.SystemArchitecture == MediaBrowser.Model.System.Architecture.X64)
            {
                archPath = Path.Combine(archPath, "x64");
            }
            else if (environmentInfo.SystemArchitecture == MediaBrowser.Model.System.Architecture.X86)
            {
                archPath = Path.Combine(archPath, "x86");
            }
            else
            {
                archPath = Path.Combine(archPath, "arm");
            }

            //Wand.SetMagickCoderModulePath(architecturePath);

            if (environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
            {
                SetDllDirectory(archPath);
            }

            var appPaths = CreateApplicationPaths(baseDirectory);

            SetSqliteProvider();

            var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");

            logManager.ReloadLogger(LogSeverity.Debug);
            logManager.AddConsoleOutput();

            var logger = _logger = logManager.GetLogger("Main");

            ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            //if (IsAlreadyRunning(applicationPath, currentProcess))
            //{
            //    logger.Info("Shutting down because another instance of Emby Server is already running.");
            //    return;
            //}

            if (PerformUpdateIfNeeded(appPaths, logger))
            {
                logger.Info("Exiting to perform application update.");
                return;
            }

            RunApplication(appPaths, logManager, options, environmentInfo);
        }
Exemplo n.º 16
0
        public void OnStart(ApplicationHost onwer, CommandArguments args)
        {
            foreach (var item in this.extensions)
            {
                item.OnStart(this.ApplicationHost, this.CommandArguments);
            }

            var hostConfig    = ObjectIOCFactory.GetSingleton <ServiceHostConfig>();
            var targetAppName = this.fileManager.GetRunAppFileName(hostConfig.App.ExeFile);
            var targetAppPath = Path.Combine(hostConfig.Host.RunDirectory, targetAppName);

            this.DisabledApp = false;

            var mainProcess = new Process();

            mainProcess.EnableRaisingEvents = true;
            mainProcess.Exited             += new EventHandler(mainApp_Exited);
            mainProcess.StartInfo.FileName  = targetAppPath;
            mainProcess.StartInfo.Arguments = this.GetAppArguments();

            var enableDebug = false;

            if (hostConfig.Host.RunInService == false && hostConfig.App.Debug == true)
            {
                enableDebug = true;
            }

            if (enableDebug)
            {
                mainProcess.StartInfo.WindowStyle    = ProcessWindowStyle.Normal;
                mainProcess.StartInfo.CreateNoWindow = false;
            }
            else
            {
                mainProcess.StartInfo.WindowStyle    = ProcessWindowStyle.Hidden;
                mainProcess.StartInfo.CreateNoWindow = true;
            }

            Console.WriteLine("[{0}]{1}", mainProcess.StartInfo.FileName, mainProcess.StartInfo.Arguments);

            try
            {
                mainProcess.Start();
            }
            catch (Exception ex)
            {
                new FatalException(string.Concat(ex.Message, " - ", targetAppPath, " - ", mainProcess.StartInfo.Arguments), ex)
                .HandleException();

                ApplicationHost.GetInstance(null).Stop();
            }

            if (null != this.MainAppHandle)
            {
                this.MainAppHandle.Refresh();
            }
            this.MainAppHandle = mainProcess;
        }
Exemplo n.º 17
0
        public void Load(ApplicationHost host)
        {
            if (host == null)
                throw new ArgumentNullException("host");

            Host = host;

            Initialize();
        }
Exemplo n.º 18
0
        private static JobApplicationHost CreateAppHost(string path)
        {
            var result = ApplicationHost.CreateApplicationHost(
                typeof(JobApplicationHost),
                "/",
                path);

            return((JobApplicationHost)result);
        }
Exemplo n.º 19
0
        void IExtensionApplication.OnStop(ApplicationHost onwer, CommandArguments args)
        {
            this.IsRunning = false;

            if (this.CommandArguments.HostProcessId > 0)
            {
                LogHelper.AppInfo(this.CommandArguments.SessionId, "Stoped In Host[{0}]", this.CommandArguments.HostProcessId);
            }
        }
Exemplo n.º 20
0
        void IExtensionApplication.OnStart(ApplicationHost onwer, M2SA.AppGenome.AppHub.CommandArguments args)
        {
            LogManager.GetLogger().Debug("---------- TaskProcessor.Start... ----------");

            ThreadStart ts = new ThreadStart(this.Process);
            Thread      t  = new Thread(ts);

            t.Start();
        }
Exemplo n.º 21
0
        public void Constructor_SerializableType()
        {
            object o = ApplicationHost.CreateApplicationHost(typeof(MySerializable), "/app", Environment.CurrentDirectory);

            Assert.AreEqual(typeof(MySerializable), o.GetType(), "C2");
            MySerializable m = (MySerializable)o;

            Assert.AreEqual(m.GetDomainName(), AppDomain.CurrentDomain.FriendlyName, "C4");
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            MySimpleHost msh = (MySimpleHost)ApplicationHost.CreateApplicationHost(typeof(MySimpleHost), "/", Directory.GetCurrentDirectory());



            Console.WriteLine("Running...");
            Console.ReadKey();
        }
Exemplo n.º 23
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            AccessTokenContainer.Register(ConstValue.WeiXinConfig.AppId, ConstValue.WeiXinConfig.AppSecret);
            ApplicationHost.GetInstance().Start();
        }
Exemplo n.º 24
0
        public HieEngine()
        {
            // The HIE Applicatoin Host

            _applicationHost = new ApplicationHost();

            Application application = CreateHl7Application(_applicationHost);

            _applicationHost.Deploy(application);
        }
Exemplo n.º 25
0
        private readonly AppDomainProxy _appDomainProxy; // The gateway to the ASP.NET-enabled .NET appdomain

        private AppHost(string appPhysicalDirectory, string virtualDirectory = "/")
        {
            _appDomainProxy = (AppDomainProxy)ApplicationHost.CreateApplicationHost(typeof(AppDomainProxy), virtualDirectory, appPhysicalDirectory);
            _appDomainProxy.RunCodeInAppDomain(() =>
            {
                InitializeApplication();
                FilterProviders.Providers.Add(new InterceptionFilterProvider());
                LastRequestData.Reset();
            });
        }
Exemplo n.º 26
0
        public MainForm(ILogger logger, ITheaterConfigurationManager config, ApplicationHost appHost, Process electronProcess)
        {
            _logger = logger;
            _config = config;
            _appHost = appHost;
            _electronProcess = electronProcess;
            InitializeComponent();

            SetWindowState();
        }
Exemplo n.º 27
0
 public void createHost()
 {
     //if (WebServerHost.isNull())
     {
         var o2Timer = new O2Timer("Creating WebServer host").start();
         WebServerHost = (WebServerHost)ApplicationHost.CreateApplicationHost(typeof(WebServerHost), "/", WebRootDir);
         //WebServerHost = ApplicationHost.CreateApplicationHost(typeof(WebServerHost), "/", WebRootDir);
         o2Timer.stop();
     }
 }
Exemplo n.º 28
0
        public MainForm(ILogger logger, ITheaterConfigurationManager config, ApplicationHost appHost, Process electronProcess)
        {
            _logger          = logger;
            _config          = config;
            _appHost         = appHost;
            _electronProcess = electronProcess;
            InitializeComponent();

            SetWindowState();
        }
Exemplo n.º 29
0
        /// <summary>
        /// Called when [plugin installed].
        /// </summary>
        /// <param name="package">The package.</param>
        private void OnPluginInstalled(PackageVersionInfo package)
        {
            _logger.Info("New plugin installed: {0} {1} {2}", package.name, package.version, package.classification);

            EventHelper.QueueEventIfNotNull(PluginInstalled, this, new GenericEventArgs <PackageVersionInfo> {
                Argument = package
            }, _logger);

            ApplicationHost.NotifyPendingRestart();
        }
Exemplo n.º 30
0
        /// <summary>
        /// Called when [plugin updated].
        /// </summary>
        /// <param name="plugin">The plugin.</param>
        /// <param name="newVersion">The new version.</param>
        private void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion)
        {
            _logger.Info("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.version, newVersion.classification);

            EventHelper.QueueEventIfNotNull(PluginUpdated, this, new GenericEventArgs <Tuple <IPlugin, PackageVersionInfo> > {
                Argument = new Tuple <IPlugin, PackageVersionInfo>(plugin, newVersion)
            }, _logger);

            ApplicationHost.NotifyPendingRestart();
        }
        public async Task <IActionResult> Create([Bind("HostId,TradingName,ConnectionString,ApiRoot")] ApplicationHost applicationHost)
        {
            if (ModelState.IsValid)
            {
                _context.Add(applicationHost);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(applicationHost));
        }
 public WebSocketEntryPoint(ISessionManager session, IApiClient apiClient, IJsonSerializer json, ILogManager logManager, IApplicationHost appHost, INavigationService nav, IPlaybackManager playbackManager, IPresentationManager presentation)
 {
     _session = session;
     _apiClient = apiClient;
     _json = json;
     _logger = logManager.GetLogger(GetType().Name);
     _appHost = (ApplicationHost)appHost;
     _nav = nav;
     _playbackManager = playbackManager;
     _presentation = presentation;
 }
Exemplo n.º 33
0
 public WebSocketEntryPoint(ISessionManager session, IApiClient apiClient, IJsonSerializer json, ILogManager logManager, IApplicationHost appHost, INavigationService nav, IPlaybackManager playbackManager, IPresentationManager presentation)
 {
     _session         = session;
     _apiClient       = apiClient;
     _json            = json;
     _logger          = logManager.GetLogger(GetType().Name);
     _appHost         = (ApplicationHost)appHost;
     _nav             = nav;
     _playbackManager = playbackManager;
     _presentation    = presentation;
 }
Exemplo n.º 34
0
    public static void Main(String[] arguments)
    {
        ASPX2HTML host = (ASPX2HTML)ApplicationHost.CreateApplicationHost(typeof(ASPX2HTML), "/foo",
                                                                          Directory.CurrentDirectory);

        foreach (String aspx in arguments)
        {
            Console.Out.WriteLine("file:" + aspx);
            host.ProcessRequest(aspx);
        }
    }
Exemplo n.º 35
0
 public void Echo(string message, CLREnumValueWrapper <EchoStatus> status = null)
 {
     if (status == null)
     {
         ApplicationHost.Echo(message);
     }
     else
     {
         ApplicationHost.Echo(message, status.UnderlyingObject);
     }
 }
Exemplo n.º 36
0
        public AppHost(string appPhysicalDirectory, string virtualDirectory)
        {
            appDomainProxy = (AppDomainProxy)ApplicationHost.CreateApplicationHost(typeof(AppDomainProxy), virtualDirectory, appPhysicalDirectory);

            appDomainProxy.RunCodeInAppDomain(() => {
                InitializeApplication();
                var filters = System.Web.Mvc.GlobalFilters.Filters;
                filters.Add(new InterceptionFilter(), int.MaxValue);
                LastRequestData.Reset();
            });
        }
 public WebSocketEntryPoint(ISessionManager sessionManager, ILogManager logManager, IApplicationHost appHost, IImageManager imageManager, INavigationService navigationService, IPlaybackManager playbackManager, IPresentationManager presentationManager, ICommandManager commandManager, IUserInputManager userInputManager, IConnectionManager connectionManager)
 {
     _sessionManager = sessionManager;
     _logger = logManager.GetLogger(GetType().Name);
     _appHost = (ApplicationHost)appHost;
     _imageManager = imageManager;
     _navigationService = navigationService;
     _playbackManager = playbackManager;
     _presentationManager = presentationManager;
     _commandManager = commandManager;
     _userInputManager = userInputManager;
     _connectionManager = connectionManager;
 }
Exemplo n.º 38
0
		public void BasicFileEndpointTest()
		{
			// A new application
			Application application = new Application();

			// Add endpoints
			string filePath = "test-file.txt";
			FileReaderEndpoint fileReaderEndpoint = new FileReaderEndpoint(filePath, 100, Encoding.Default);
			application.Ports.Add(new Port { Endpoint = fileReaderEndpoint });

			string fileOutPath = "test-file-out.txt";
			FileWriterEndpoint fileWriterEndpoint = new FileWriterEndpoint(fileOutPath, true, Encoding.Default, true);
			application.Ports.Add(new Port { Endpoint = fileWriterEndpoint });

			// Add a channel
			Channel channel = new Channel();
			application.Channels.Add(channel);

			// Source setup
			Source source = new Source();
			channel.Source = source;

			Destination destination = new Destination();
			destination.Target = fileWriterEndpoint;
			channel.Destinations.Add(destination);

			// Host
			ApplicationHost applicationHost = new ApplicationHost();
			applicationHost.Deploy(application);

			// Start the processing
			applicationHost.StartProcessing();
			fileReaderEndpoint.WaitForMessage();
			fileReaderEndpoint.WaitForMessage();

			// Check that endpoint wrote the message

			using (StreamReader reader = new StreamReader(fileOutPath))
			{
				string text = reader.ReadToEnd();
				Assert.AreEqual("Hello world!\nHello world!", text.Trim().Replace("\r\n", "\n"));
				reader.Close();
			}
		}
Exemplo n.º 39
0
        private static bool LaunchApplication(ApplicationPaths appPaths, NlogManager logManager)
        {
#if !DEBUG
            ILogger logger = logManager.GetLogger("App");
            try {
#endif
            using (var appHost = new ApplicationHost(appPaths, logManager)) {
                appHost.Init(new Progress<double>()).Wait();

                if (!appHost.TheaterConfigurationManager.Configuration.IsStartupWizardCompleted) {
                    bool completed = appHost.RunStartupWizard();

                    if (completed) {
                        appHost.TheaterConfigurationManager.Configuration.IsStartupWizardCompleted = true;
                        appHost.TheaterConfigurationManager.SaveConfiguration();

                        appHost.Restart().Wait();
                    } else {
                        appHost.Shutdown().Wait();
                    }
                } else {
                    appHost.RunUserInterface();
                }

                return appHost.RestartOnExit;
            }
#if !DEBUG
            } catch (Exception ex) {
                logger.ErrorException("Error launching application", ex);

                MessageBox.Show("There was an error launching Media Browser Theater: " + ex.Message);
                
                // Shutdown the app with an error code
                Environment.Exit(1);
                return false;
            }
#endif
        }
Exemplo n.º 40
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var host = new ApplicationHost();

            log.Info("search for features");
            foreach (var feature in FeatureSeeker.seek(Assembly.GetExecutingAssembly()))
            {
                log.Info("register feature: " + feature.GetType());
                host.registerService(feature);
            }

            host.build();

            var mainForm = host.getService<MainForm>();

            var reportName = FindReportArgument();
            if (!String.IsNullOrEmpty(reportName))
            {
                if (System.IO.File.Exists(reportName))
                {
                    log.Debug("open form with report argument: " + reportName);
                    mainForm.OpenReport(reportName);
                }
                else
                {
                    // todo: should we report this to the user?
                    log.Debug("report argument file does not exist: " + reportName);
                }
            }
            
            Application.Run(mainForm);

            host.destroy();
        }
Exemplo n.º 41
0
        /// <summary>
        /// Runs the application.
        /// </summary>
        /// <param name="appPaths">The app paths.</param>
        /// <param name="logManager">The log manager.</param>
        /// <param name="runService">if set to <c>true</c> [run service].</param>
        private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService)
        {
            SystemEvents.SessionEnding += SystemEvents_SessionEnding;
            SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;

            _appHost = new ApplicationHost(appPaths, logManager);

            _app = new App(_appHost, _appHost.LogManager.GetLogger("App"), runService);

            if (runService)
            {
                _app.AppStarted += (sender, args) => StartService(logManager);
            }
            else
            {
                // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
                SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
                             ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
            }

            _app.Run();
        }
Exemplo n.º 42
0
        private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger)
        {
            // Reference 
            // http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed

            try
            {
                var subkey = Environment.Is64BitProcess
                    ? "SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x64"
                    : "SOFTWARE\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x86";

                using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
                    .OpenSubKey(subkey))
                {
                    if (ndpKey != null && ndpKey.GetValue("Version") != null)
                    {
                        var installedVersion = ((string)ndpKey.GetValue("Version")).TrimStart('v');
                        if (installedVersion.StartsWith("12", StringComparison.OrdinalIgnoreCase))
                        {
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error getting .NET Framework version", ex);
                return;
            }

            try
            {
                await InstallVcredist2013().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
            }
        }
Exemplo n.º 43
0
        /// <summary>
        /// Runs the application.
        /// </summary>
        /// <param name="appPaths">The app paths.</param>
        /// <param name="logManager">The log manager.</param>
        /// <param name="runService">if set to <c>true</c> [run service].</param>
        private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService)
        {
            _appHost = new ApplicationHost(appPaths, logManager, true, runService);

            var initProgress = new Progress<double>();

            if (!runService)
            {
                ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
                
                // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
                SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
                             ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
            }


            var task = _appHost.Init(initProgress);
            task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()));

            if (runService)
            {
                StartService(logManager);
            }
            else
            {
                Task.WaitAll(task);

                SystemEvents.SessionEnding += SystemEvents_SessionEnding;
                SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
   
                HideSplashScreen();

                ShowTrayIcon();
                
                task = ApplicationTaskCompletionSource.Task;
                Task.WaitAll(task);
            }
        }
Exemplo n.º 44
0
        /// <summary>
        /// Runs the application.
        /// </summary>
        /// <param name="appPaths">The app paths.</param>
        /// <param name="logManager">The log manager.</param>
        /// <param name="runService">if set to <c>true</c> [run service].</param>
        /// <param name="options">The options.</param>
        private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
        {
            var fileSystem = new NativeFileSystem(logManager.GetLogger("FileSystem"), false);

            var nativeApp = new WindowsApp(fileSystem)
            {
                IsRunningAsService = runService
            };

            _appHost = new ApplicationHost(appPaths,
                logManager,
                options,
                fileSystem,
                "MBServer",
                nativeApp);
            
            var initProgress = new Progress<double>();

            if (!runService)
            {
                if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));

                // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
                SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
                             ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
            }


            var task = _appHost.Init(initProgress);
            task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()));

            if (runService)
            {
                StartService(logManager);
            }
            else
            {
                Task.WaitAll(task);

                SystemEvents.SessionEnding += SystemEvents_SessionEnding;
                SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;

                HideSplashScreen();

                ShowTrayIcon();

                task = ApplicationTaskCompletionSource.Task;
                Task.WaitAll(task);
            }
        }
Exemplo n.º 45
0
		/// <summary>
		/// Runs the application.
		/// </summary>
		/// <param name="appPaths">The app paths.</param>
		/// <param name="logManager">The log manager.</param>
		/// <param name="options">The options.</param>
		private static void StartApplication(ServerApplicationPaths appPaths, 
			ILogManager logManager, 
			StartupOptions options)
		{
			SystemEvents.SessionEnding += SystemEvents_SessionEnding;

			// Allow all https requests
			ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });

			var fileSystem = new ManagedFileSystem(new PatternsLogger(logManager.GetLogger("FileSystem")), false, true);
            fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));

			var nativeApp = new NativeApp(logManager.GetLogger("App"));

			AppHost = new ApplicationHost(appPaths, logManager, options, fileSystem, "Emby.Server.Mac.pkg", nativeApp);

			if (options.ContainsOption("-v")) {
				Console.WriteLine (AppHost.ApplicationVersion.ToString());
				return;
			}

			Console.WriteLine ("appHost.Init");

			Task.Run (() => StartServer(CancellationToken.None));
		}
Exemplo n.º 46
0
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            bool createdNew;

            _singleInstanceMutex = new Mutex(true, @"Local\" + typeof(Program).Assembly.GetName().Name, out createdNew);

            if (!createdNew)
            {
                _singleInstanceMutex = null;
                return;
            }

            var appPath = Process.GetCurrentProcess().MainModule.FileName;

            // Look for the existence of an update archive
            var appPaths = new ApplicationPaths(GetProgramDataPath(appPath), appPath);
            var logManager = new NlogManager(appPaths.LogDirectoryPath, "theater");
            logManager.ReloadLogger(LogSeverity.Debug);

            var updateArchive = Path.Combine(appPaths.TempUpdatePath, UpdatePackageName);

            if (File.Exists(updateArchive))
            {
                ReleaseMutex();

                // Update is there - execute update
                try
                {
                    new ApplicationUpdater().UpdateApplication(appPaths, updateArchive,
                        logManager.GetLogger("ApplicationUpdater"));

                    // And just let the app exit so it can update
                    return;
                }
                catch (Exception e)
                {
                    MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}",
                        e.GetType().Name, e.Message));
                }
            }

            _logger = logManager.GetLogger("App");

            bool supportsTransparency;

            try
            {
                 supportsTransparency = NativeWindowMethods.DwmIsCompositionEnabled();
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error in DwmIsCompositionEnabled", ex);
                supportsTransparency = true;
            }

            _logger.Info("OS Supports window transparency?: {0}", supportsTransparency);

            try
            {
                _appHost = new ApplicationHost(appPaths, logManager);

                var initTask = _appHost.Init(new Progress<Double>());
                Task.WaitAll(initTask);

                var electronTask = StartElectron(appPaths, supportsTransparency);
                Task.WaitAll(electronTask);

                var electronProcess = electronTask.Result;

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                _mainForm = new MainForm(_logger, _appHost.TheaterConfigurationManager, _appHost, electronProcess);
                Application.Run(_mainForm);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error launching application", ex);

                MessageBox.Show("There was an error launching Emby: " + ex.Message);

                // Shutdown the app with an error code
                Environment.Exit(1);
            }
            finally
            {
                ReleaseMutex();
            }
        }
Exemplo n.º 47
0
 public static ApplicationHost CreateApplicationHost(global::System.Guid ID, global::System.Guid stampId)
 {
     ApplicationHost applicationHost = new ApplicationHost();
     applicationHost.ID = ID;
     applicationHost.StampId = stampId;
     return applicationHost;
 }
 public MyShellImplementationModel()
 {
     host = new ApplicationHost(this);
 }
Exemplo n.º 49
0
        private static async Task InstallVcredistIfNeeded(ApplicationHost appHost, ILogger logger)
        {
            try
            {
                var version = ImageMagickEncoder.GetVersion();
                return;
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error loading ImageMagick", ex);
            }

            try
            {
                await InstallVcredist().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
            }
        }
Exemplo n.º 50
0
        /// <summary>
        /// Loads the kernel.
        /// </summary>
        protected async void LoadKernel()
        {
            try
            {
                CompositionRoot = new ApplicationHost();

                Logger = CompositionRoot.LogManager.GetLogger("App");

                var splash = new SplashWindow(CompositionRoot.ApplicationVersion);

                splash.Show();
                
                await CompositionRoot.Init();

                splash.Hide();

                var task = CompositionRoot.RunStartupTasks();

                new MainWindow(CompositionRoot.LogManager, CompositionRoot, CompositionRoot.ServerConfigurationManager, CompositionRoot.UserManager, CompositionRoot.LibraryManager, CompositionRoot.JsonSerializer, CompositionRoot.DisplayPreferencesRepository).Show();

                await task.ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error launching application", ex);

                MessageBox.Show("There was an error launching Media Browser: " + ex.Message);

                // Shutdown the app with an error code
                Shutdown(1);
            }
        }
Exemplo n.º 51
0
		private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager)
		{
			SystemEvents.SessionEnding += SystemEvents_SessionEnding;

			// Allow all https requests
			ServicePointManager.ServerCertificateValidationCallback = _ignoreCertificates;

			_appHost = new ApplicationHost(appPaths, logManager);

			Console.WriteLine ("appHost.Init");

			var initProgress = new Progress<double>();

			var task = _appHost.Init(initProgress);
			Task.WaitAll (task);

			Console.WriteLine ("Running startup tasks");

			task = _appHost.RunStartupTasks();
			Task.WaitAll (task);

			task = _applicationTaskCompletionSource.Task;

			Task.WaitAll (task);
		}
Exemplo n.º 52
0
        /// <summary>
        /// Loads the kernel.
        /// </summary>
        protected async void LoadApplication()
        {
            try
            {
                _appHost = new ApplicationHost(_appPaths, _logManager);

                _logger = _appHost.LogManager.GetLogger("App");

                await _appHost.Init(new Progress<double>());

                LoadListBoxItemResourceFile();

                // Load default theme
                await _appHost.ThemeManager.LoadDefaultTheme();

                _appHost.TheaterConfigurationManager.ConfigurationUpdated += TheaterConfigurationManager_ConfigurationUpdated;

                ShowApplicationWindow();
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error launching application", ex);

                MessageBox.Show("There was an error launching Media Browser: " + ex.Message);

                // Shutdown the app with an error code
                Shutdown(1);
            }
        }
Exemplo n.º 53
0
		private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager)
		{
			// TODO: Show splash here

			SystemEvents.SessionEnding += SystemEvents_SessionEnding;

			// Allow all https requests
			ServicePointManager.ServerCertificateValidationCallback = _ignoreCertificates;

			_appHost = new ApplicationHost(appPaths, logManager);

			var task = _appHost.Init();
			Task.WaitAll (task);

			task = _appHost.RunStartupTasks();
			Task.WaitAll (task);

			// TODO: Hide splash here
			_mainWindow = new MainWindow ();

			// Creation of the Icon
			// Creation of the Icon
			trayIcon = new StatusIcon(new Pixbuf ("tray.png"));
			trayIcon.Visible = true;

			// When the TrayIcon has been clicked.
			trayIcon.Activate += delegate { };
			// Show a pop up menu when the icon has been right clicked.
			trayIcon.PopupMenu += OnTrayIconPopup;

			// A Tooltip for the Icon
			trayIcon.Tooltip = "Media Browser Server";

			_mainWindow.ShowAll ();
			_mainWindow.Visible = false;

			Application.Run ();
		}
Exemplo n.º 54
0
        /// <summary>
        /// Runs the application.
        /// </summary>
        /// <param name="appPaths">The app paths.</param>
        /// <param name="logManager">The log manager.</param>
        /// <param name="runService">if set to <c>true</c> [run service].</param>
        /// <param name="options">The options.</param>
        private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
        {
            var fileSystem = new WindowsFileSystem(new PatternsLogger(logManager.GetLogger("FileSystem")));
            fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
            //fileSystem.AddShortcutHandler(new LnkShortcutHandler(fileSystem));

            var nativeApp = new WindowsApp(fileSystem, _logger)
            {
                IsRunningAsService = runService
            };

            _appHost = new ApplicationHost(appPaths,
                logManager,
                options,
                fileSystem,
                "emby.windows.zip",
                nativeApp);

            var initProgress = new Progress<double>();

            if (!runService)
            {
                if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));

                // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
                SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
                             ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
            }

            var task = _appHost.Init(initProgress);
            Task.WaitAll(task);

            task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);

            if (runService)
            {
                StartService(logManager);
            }
            else
            {
                Task.WaitAll(task);

                task = InstallVcredist2013IfNeeded(_appHost, _logger);
                Task.WaitAll(task);

                SystemEvents.SessionEnding += SystemEvents_SessionEnding;
                SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;

                HideSplashScreen();

                ShowTrayIcon();

                task = ApplicationTaskCompletionSource.Task;
                Task.WaitAll(task);
            }
        }
Exemplo n.º 55
0
        /// <summary>
        /// Loads the kernel.
        /// </summary>
        protected async void LoadKernel()
        {
            try
            {
                _appHost = new ApplicationHost(_appPaths, _logManager);

                _logger = _appHost.LogManager.GetLogger("App");

                await _appHost.Init();

                // Load default theme
                await _appHost.ThemeManager.LoadDefaultTheme();

                HiddenWindow = new HiddenWindow(_logManager.GetLogger("HiddenWindow"));
                HiddenWindow.Show();

                ShowApplicationWindow();

                _appHost.StartEntryPoints();

                await LoadInitialPresentation().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error launching application", ex);

                MessageBox.Show("There was an error launching Media Browser: " + ex.Message);

                // Shutdown the app with an error code
                Shutdown(1);
            }
        }
Exemplo n.º 56
0
        /// <summary>
        /// Loads the kernel.
        /// </summary>
        protected async void LoadKernel()
        {
            try
            {
                CompositionRoot = new ApplicationHost();

                Logger = CompositionRoot.LogManager.GetLogger("App");

                await CompositionRoot.Init();

                OnKernelLoaded();

                InstantiateMainWindow().Show();

                ShowApplicationWindow();

                await ApplicationWindow.LoadInitialUI().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error launching application", ex);

                MessageBox.Show("There was an error launching Media Browser: " + ex.Message);

                // Shutdown the app with an error code
                Shutdown(1);
            }
        }
Exemplo n.º 57
0
 public void SetUp ()
 {
     factoryMock = new DynamicMock(typeof(IConfigurableListableObjectFactory));
     factory = (IConfigurableListableObjectFactory) factoryMock.Object;
     host = NewApplicationHost (AppDomain.CurrentDomain, factory);
 }