/// <summary> /// Initializes a new instance of the <see cref="App" /> class. /// </summary> public App(ApplicationPaths appPaths, ILogManager logManager) { _appPaths = appPaths; _logManager = logManager; InitializeComponent(); }
public static Menu CreateMenu(IObservable <Optional <AbsoluteFilePath> > path) { var sublimeTextPath = ApplicationPaths.SublimeTextPath(); return(path .SelectPerElement(project => project.ContainingDirectory) .Select(dir => new [] { Menu.Item( name: "Open in Sublime", command: Command.Create( isEnabled: dir.HasValue && sublimeTextPath.HasValue, action: () => Task.Run(() => { if (Platform.OperatingSystem == OS.Mac) { ExternalApplication.FromAppBundle(sublimeTextPath.Value).Open(dir.Value); } else { var ps = new ProcessStartInfo() { FileName = (sublimeTextPath.Value / new FileName("sublime_text.exe")).NativePath, Arguments = "\"" + dir.Value.NativePath + "\"", UseShellExecute = false }; ps.UpdatePathEnvironment(); Process.Start(ps); } }))), }) .Concat()); }
private void InitializeConfigDirectory(string configDirectory) { if (!String.IsNullOrEmpty(configDirectory)) { this.configDirectory = configDirectory; } else if (String.IsNullOrEmpty(this.configDirectory)) { this.configDirectory = ApplicationPaths.AppDataPath(); } }
static AbsoluteDirectoryPath GetVsCodePath() { var vsCodePath = ApplicationPaths.VsCodePath(); if (!vsCodePath.HasValue) { throw new Exception("Failed to find Visual Studio Code path. Is Visual Studio Code installed?"); } return(Platform.OperatingSystem == OS.Windows ? vsCodePath.Value / "bin" / "code.cmd" : vsCodePath.Value / "Contents" / "Resources" / "app" / "bin" / "code"); }
private void ClearDefaultValues() { if (workingApplicationConfiguration.LogFilePath.Equals(ApplicationPaths.AppDataPath())) { workingApplicationConfiguration.LogFilePath = String.Empty; } if (workingPathConfiguration.SharedConfigPath.Equals(ApplicationPaths.AppDataPath())) { workingPathConfiguration.SharedConfigPath = String.Empty; } }
static ApplicationRuntime() { appPaths = new ApplicationPaths(); appParams = new ApplicationParameters(); ApplicationService. InitApplicationConfiguration(appPaths, appParams); InitializeInfinityFiles(); InitializeCriticalControls(); RichTextBoxLink.InitializeStaticPatterns(); }
public void Atom_ManualTest() { var path = ApplicationPaths.AtomPath(); if (Platform.OperatingSystem == OS.Windows) { Assert.AreEqual(@"C:\Users\knatten\AppData\Local\atom\app-1.19.4", path.Value.NativePath); } else { Assert.AreEqual(@"TODO", path.Value.NativePath); } }
private void CopyLogFilesIfChanged() { string originalPath = applicationConfiguration.LogFilePath; if (string.IsNullOrEmpty(originalPath)) { originalPath = ApplicationPaths.AppDataPath(); } if (!originalPath.Equals(workingApplicationConfiguration.LogFilePath, StringComparison.OrdinalIgnoreCase)) { FileCopier.CopyFilesToFolder(originalPath, workingApplicationConfiguration.LogFilePath, "*.json"); } }
public void VsCode_ManualTest() { var path = ApplicationPaths.VsCodePath(); if (Platform.OperatingSystem == OS.Windows) { Assert.AreEqual(@"C:\Program Files\Microsoft VS Code", path.Value.NativePath); } else { Assert.AreEqual(@"TODO", path.Value.NativePath); } }
public void Sublime_ManualTest() { var path = ApplicationPaths.SublimeTextPath(); if (Platform.OperatingSystem == OS.Windows) { Assert.AreEqual(@"C:\Program Files\Sublime Text 3", path.Value.NativePath); } else { Assert.AreEqual(@"TODO", path.Value.NativePath); } }
private static Logger BuildLogger() { return(new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File( formatter: new JsonFormatter(), path: ApplicationPaths.GetLogFileNameTemplateWithPath(GetDataFolderPath()), rollingInterval: RollingInterval.Day, retainedFileCountLimit: 4) .CreateLogger()); }
public static void SetApplicationPaths(ApplicationPaths paths, IReadOnlyCollection <string> commandLineArgs) { string?currentDomainBaseDirectory = AppDomain.CurrentDomain.BaseDirectory; if (WindowsServiceHelper.IsRunningAsService(commandLineArgs)) { TempLogger.WriteLine( $"Switching current directory from {Directory.GetCurrentDirectory()} to {currentDomainBaseDirectory}"); Directory.SetCurrentDirectory(currentDomainBaseDirectory); } paths.BasePath ??= currentDomainBaseDirectory; paths.ContentBasePath ??= Directory.GetCurrentDirectory(); }
private static Task <App <T> > BuildAppAsync(CancellationTokenSource cancellationTokenSource, string[] commandLineArgs, IReadOnlyDictionary <string, string> environmentVariables, IReadOnlyCollection <Assembly> scanAssemblies, params object[] instances) { MultiSourceKeyValueConfiguration startupConfiguration = ConfigurationInitialization.InitializeStartupConfiguration(commandLineArgs, environmentVariables, scanAssemblies); ConfigurationInstanceHolder configurationInstanceHolder = GetConfigurationRegistrations(startupConfiguration, scanAssemblies); var assemblyResolver = new InstanceApplicationAssemblyResolver(scanAssemblies.SafeToImmutableArray()); configurationInstanceHolder.AddInstance(assemblyResolver); configurationInstanceHolder.AddInstance(configurationInstanceHolder); foreach (object instance in instances.NotNull()) { configurationInstanceHolder.AddInstance(instance); } var loggingLevelSwitch = new LoggingLevelSwitch(); configurationInstanceHolder.AddInstance(loggingLevelSwitch); configurationInstanceHolder.AddInstance(cancellationTokenSource); ApplicationPaths paths = configurationInstanceHolder.GetInstances <ApplicationPaths>().SingleOrDefault().Value ?? new ApplicationPaths(); AppPathHelper.SetApplicationPaths(paths, commandLineArgs); if (paths.BasePath is null) { throw new InvalidOperationException("Base path is not set"); } var startupLoggerConfigurationHandlers = assemblyResolver.GetAssemblies() .GetLoadablePublicConcreteTypesImplementing < IStartupLoggerConfigurationHandler>() .Select(type => configurationInstanceHolder.Create(type) as IStartupLoggerConfigurationHandler) .Where(item => item is { }).ToImmutableArray();
/// <summary> /// Runs the application. /// </summary> private static void RunApplication(ApplicationPaths appPaths, ILogManager logManager, IEnvironmentInfo environmentInfo, StartupOptions options) { var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, appPaths.TempDirectory); FileSystem = fileSystem; INetworkManager networkManager = new NetworkManager(logManager.GetLogger("NetworkManager")); using (var appHost = new ApplicationHost(appPaths, logManager, options, fileSystem, null, UpdatePackageName, environmentInfo, new Emby.Theater.App.SystemEvents(logManager.GetLogger("SystemEvents")), networkManager)) { var initProgress = new Progress <double>(); Func <IHttpClient> httpClient = () => appHost.HttpClient; using (new ElectronApp(_logger, appPaths, httpClient, environmentInfo)) { var task = appHost.Init(initProgress); Task.WaitAll(task); //task = InstallVcredist2015IfNeeded(appHost.HttpClient, _logger); //Task.WaitAll(task); task = InstallCecDriver(appPaths, appHost.HttpClient); Task.WaitAll(task); using (var server = new TheaterServer(_logger, appHost)) { task = appHost.RunStartupTasks(); Task.WaitAll(task); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new AppContext(server)); } } } }
public static void Main() { bool createdNew; _singleInstanceMutex = new Mutex(true, @"Local\" + typeof(App).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, "MBTheater" + ".zip"); if (File.Exists(updateArchive)) { // Update is there - execute update try { new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logManager.GetLogger("ApplicationUpdater"), string.Empty); // 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)); } } var application = new App(appPaths, logManager); application.Run(); }
public AdvancedSettingsForm(Application applicationConfiguration, Paths pathConfiguration) { InitializeComponent(); this.applicationConfiguration = applicationConfiguration; workingApplicationConfiguration = ObjectCopier.CloneObject <Application, Application>(applicationConfiguration); this.pathConfiguration = pathConfiguration; workingPathConfiguration = ObjectCopier.CloneObject <Paths, Paths>(pathConfiguration); if (String.IsNullOrEmpty(workingApplicationConfiguration.LogFilePath)) { workingApplicationConfiguration.LogFilePath = ApplicationPaths.AppDataPath(); } if (String.IsNullOrEmpty(workingPathConfiguration.SharedConfigPath)) { workingPathConfiguration.SharedConfigPath = ApplicationPaths.AppDataPath(); } }
static AbsoluteDirectoryPath GetApmPath() { if (Platform.OperatingSystem == OS.Windows) { var atomPath = ApplicationPaths.AtomPath(); if (!atomPath.HasValue) { //It's not possible to detect the Atom path on Windows 7, so show a message in that case var os = Environment.OSVersion; var win7Info = (os.Platform == PlatformID.Win32NT && os.Version.Major == 6 && os.Version.Minor == 0) ? " Note that we are unable to detect the Atom installation path on Windows 7." : ""; throw new Exception("Failed to find Atom path. Is Atom installed?" + win7Info); } return(atomPath.Value / ".." / "bin" / "apm.cmd"); } else { return(AbsoluteDirectoryPath.Parse("apm")); } }
public static void Init(KernelLoadDirective directives, ConfigData config) { lock (sync) { // we must set up some paths as well as a side effect (should be refactored) if (!string.IsNullOrEmpty(config.UserSettingsPath) && Directory.Exists(config.UserSettingsPath)) { ApplicationPaths.SetUserSettingsPath(config.UserSettingsPath); } // its critical to have the logger initialized early so initialization routines can use the right logger. Logger.LoggerInstance = GetDefaultLogger(config); var kernel = GetDefaultKernel(config, directives); Kernel.Instance = kernel; // add the podcast home var podcastHome = kernel.GetItem <Folder>(kernel.ConfigData.PodcastHome); if (podcastHome != null && podcastHome.Children.Count > 0) { kernel.RootFolder.AddVirtualChild(podcastHome); } } }
static void Main() { ApplicationPath = Assembly.GetEntryAssembly().Location; var environmentInfo = GetEnvironmentInfo(); var appPaths = new ApplicationPaths(GetProgramDataPath(ApplicationPath), ApplicationPath); _appPaths = appPaths; using (var logManager = new SimpleLogManager(appPaths.LogDirectoryPath, "theater")) { _logManager = logManager; logManager.ReloadLogger(LogSeverity.Debug); logManager.AddConsoleOutput(); var logger = _logger = logManager.GetLogger("Main"); logger.Info("Application path: {0}", ApplicationPath); ApplicationHost.LogEnvironmentInfo(logger, appPaths, true); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Mutex credit: https://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567 // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", "EmbyTheater"); // Need a place to store a return value in Mutex() constructor call bool createdNew; // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen using (var mutex = new Mutex(false, mutexId, out createdNew)) { // edited by acidzombie24 var hasHandle = false; try { // note, you may want to time out here instead of waiting forever // edited by acidzombie24 hasHandle = mutex.WaitOne(5000, false); if (hasHandle == false) { logger.Info("Exiting because another instance is already running."); return; } } catch (AbandonedMutexException) { // Log the fact that the mutex was abandoned in another process, // it will still get acquired hasHandle = true; logger.Info("Mutex was abandoned in another process."); } using (new MutexHandle(mutex, hasHandle, _logger)) { if (PerformUpdateIfNeeded(appPaths, environmentInfo, logger)) { logger.Info("Exiting to perform application update."); return; } RunApplication(appPaths, logManager, environmentInfo, new StartupOptions(Environment.GetCommandLineArgs())); } } logger.Info("Shutdown complete"); if (_restartOnShutdown) { // This is artificial, but add some delay to ensure sockets are released. var delay = environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows ? 5000 : 60000; var task = Task.Delay(delay); Task.WaitAll(task); logger.Info("Starting new server process"); var restartCommandLine = GetRestartCommandLine(); Process.Start(restartCommandLine.Item1, restartCommandLine.Item2); } } }
private static string NetworkDevicesConfigurationFileName() { return(Path.Combine(ApplicationPaths.AppDataPath(), "NetworkDevicesConfiguration.xml")); }
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"); try { var task = InstallVcredistIfNeeded(_appHost, _logger); Task.WaitAll(task); _appHost = new ApplicationHost(appPaths, logManager); var initTask = _appHost.Init(new Progress <Double>()); Task.WaitAll(initTask); var electronTask = StartElectron(appPaths); 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(); } }
private static string PathConfigurationFileName() { return(Path.Combine(ApplicationPaths.AppDataPath(), "PathConfiguration.xml")); }
protected override InstallStatus CheckStatus() { return(ApplicationPaths.SublimeTextPath().HasValue ? InstallStatus.Installed : InstallStatus.NotInstalled); }
private static string DeviceConfigurationsFileName() { return(Path.Combine(ApplicationPaths.AppDataPath(), "DeviceConfigurations.xml")); }
public static void Init(KernelLoadDirective directives, ConfigData config) { lock (sync) { // we must set up some paths as well as a side effect (should be refactored) if (!string.IsNullOrEmpty(config.UserSettingsPath) && Directory.Exists(config.UserSettingsPath)) { ApplicationPaths.SetUserSettingsPath(config.UserSettingsPath.Trim()); } // Its critical to have the logger initialized early so initialization // routines can use the right logger. if (Logger.LoggerInstance != null) { Logger.LoggerInstance.Dispose(); } Logger.LoggerInstance = GetDefaultLogger(config); var kernel = GetDefaultKernel(config, directives); Kernel.Instance = kernel; // setup IBN if not there string ibnLocation = Config.Instance.ImageByNameLocation; if (string.IsNullOrEmpty(ibnLocation)) { ibnLocation = Path.Combine(ApplicationPaths.AppConfigPath, "ImagesByName"); } if (!Directory.Exists(ibnLocation)) { try { Directory.CreateDirectory(ibnLocation); Directory.CreateDirectory(Path.Combine(ibnLocation, "Genre")); Directory.CreateDirectory(Path.Combine(ibnLocation, "People")); Directory.CreateDirectory(Path.Combine(ibnLocation, "Studio")); Directory.CreateDirectory(Path.Combine(ibnLocation, "Year")); Directory.CreateDirectory(Path.Combine(ibnLocation, "General")); Directory.CreateDirectory(Path.Combine(ibnLocation, "MediaInfo")); } catch (Exception e) { Logger.ReportException("Unable to create IBN location.", e); } } if (LoadContext == MBLoadContext.Core || LoadContext == MBLoadContext.Configurator) { Async.Queue("Start Service", () => { //start our service if its not already going if (!MBServiceController.IsRunning) { Logger.ReportInfo("Starting MB Service..."); MBServiceController.StartService(); } }); } if (LoadContext == MBLoadContext.Core) { //listen for commands if (!MBClientConnector.StartListening()) { //we couldn't start our listener - probably another instance going so we shut down Logger.ReportInfo("Could not start listener - assuming another instance of MB. Closing..."); Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication(); return; } MBServiceController.ConnectToService(); //set up for service to tell us to do things } // create filewatchers for each of our top-level folders (only if we are in MediaCenter, though) bool isMC = AppDomain.CurrentDomain.FriendlyName.Contains("ehExtHost"); if (isMC && config.EnableDirectoryWatchers) //only do this inside of MediaCenter as we don't want to be trying to refresh things if MB isn't actually running { Async.Queue("Create Filewatchers", () => { foreach (BaseItem item in kernel.RootFolder.Children) { Folder folder = item as Folder; if (folder != null) { folder.directoryWatcher = new MBDirectoryWatcher(folder, false); } } // create a watcher for the startup folder too - and watch all changes there kernel.RootFolder.directoryWatcher = new MBDirectoryWatcher(kernel.RootFolder, true); }); } // add the podcast home var podcastHome = kernel.GetItem <Folder>(kernel.ConfigData.PodcastHome); if (podcastHome != null && podcastHome.Children.Count > 0) { kernel.RootFolder.AddVirtualChild(podcastHome); } } }
public static void InitApplicationConfiguration(ApplicationPaths appPaths, ApplicationParameters appParams) { // Class to initialize XML file if necessary }