Example #1
0
        public void PermitApplicationCreation()
        {
            var application = Application.Default;

            var userData = new UserData(StringHelper.ValidString(), StringHelper.ValidString(), StringHelper.ValidString());
            var tbl      = new AzureTable <UserData>(CloudStorageAccount.DevelopmentStorageAccount);

            tbl.AddEntity(userData);

            var user = new User()
            {
                Identifier = userData.Id,
            };

            var row   = new UserPreferenceRow(application.Identifier, user.Identifier);
            var table = new AzureTable <UserPreferenceRow>(CloudStorageAccount.DevelopmentStorageAccount);

            table.AddEntity(row);
            var appCore = new ApplicationCore();

            appCore.PermitApplicationCreation(application, user);
        }
Example #2
0
        public void SaveApplicationInformationNullData()
        {
            var core = new ApplicationCore();
            var u    = new User()
            {
                Identifier = Guid.NewGuid(),
            };
            var app = new Application()
            {
                Identifier = Guid.NewGuid(),
            };
            var editor = new UserApplication()
            {
                User        = u,
                Application = app,
            };
            var userApp = new ApplicationInformation()
            {
                Identifier = Guid.NewGuid(),
            };

            core.Save((ApplicationInformation)null, editor, userApp);
        }
        public void Stop()
        {
            try
            {
                _systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                ServiceRegistration.IsShuttingDown = true;              // Block ServiceRegistration from trying to load new services in shutdown phase

                ServiceRegistration.Get <IImporterWorker>().Shutdown(); // needs to be shut down before MediaAccessor and plugins
                ServiceRegistration.Get <IMediaAccessor>().Shutdown();
                ServiceRegistration.Get <IPluginManager>().Shutdown();
                BackendExtension.ShutdownBackendServices();
                CloseIpc();
                ApplicationCore.StopCoreServices();
            }
            catch (Exception ex)
            {
                //ServiceRegistration.Get<ILogger.Critical("Error stopping application", e);
#if DEBUG
                ConsoleLogger log = new ConsoleLogger(LogLevel.All, false);
                log.Error(ex);
#else
                var pathManager         = ServiceRegistration.Get <IPathManager>();
                var logPath             = pathManager.GetPath("<LOG>");
                ServerCrashLogger crash = new ServerCrashLogger(logPath);
                crash.CreateLog(ex);
#endif
                _systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                ServiceRegistration.IsShuttingDown = true;
            }
            finally
            {
                BackendExtension.DisposeBackendServices();
                ApplicationCore.DisposeCoreServices();
                _systemStateService.SwitchSystemState(SystemState.Ending, false);
                _systemStateService.Dispose();
            }
        }
Example #4
0
        public void SaveApplicationInformationEmptyAppId()
        {
            var core = new ApplicationCore();
            var u    = new User()
            {
                Identifier = Guid.NewGuid(),
            };
            var app = new Application()
            {
                Identifier = Guid.NewGuid(),
            };
            var editor = new UserApplication()
            {
                User        = u,
                Application = app,
            };
            var userApp = new ApplicationInformation()
            {
                Identifier = Guid.Empty,
            };
            var info = this.Information();

            core.Save(info, editor, userApp);
        }
Example #5
0
        private static void TestRecording(string filename)
        {
            if (Directory.Exists("_Test"))
            {
                Directory.Delete("_Test", true);
            }

            ServiceRegistration.Set <IPathManager>(new PathManager());
            ServiceRegistration.Get <IPathManager>().SetPath("DATA", "_Test/Data");

            ServiceRegistration.Set <ILocalization>(new NoLocalization());
            ServiceRegistration.Set <ILogger>(new ConsoleLogger(LogLevel.All, true));

            ServiceRegistration.Set <IMediaAccessor>(new TestMediaAccessor());
            ServiceRegistration.Set <IMediaItemAspectTypeRegistration>(new MockMediaItemAspectTypeRegistration());

            ApplicationCore.RegisterDefaultMediaItemAspectTypes().Wait();

            ServiceRegistration.Set <SeriesTvDbMatcher>(new SeriesTvDbMatcher());

            IDictionary <Guid, IList <MediaItemAspect> > aspects = new Dictionary <Guid, IList <MediaItemAspect> >();

            string ext = StringUtils.TrimToEmpty(ProviderPathHelper.GetExtension(filename)).ToLowerInvariant();

            if (ext != ".xml")
            {
                Console.WriteLine("Filetype must be XML");
                return;
            }
            XmlSerializer serializer = new XmlSerializer(typeof(Tve3RecordingMetadataExtractor.Tags));

            using (Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                Tve3RecordingMetadataExtractor.Tags      tags = (Tve3RecordingMetadataExtractor.Tags)serializer.Deserialize(stream);
                Tve3RecordingMetadataExtractor.SimpleTag tag  = tags.Tag.Find(t => t.Name == "TITLE");
                MediaItemAspect.SetAttribute(aspects, MediaAspect.ATTR_TITLE, tag.Value);
            }

            IMediaItemAspectTypeRegistration registration = ServiceRegistration.Get <IMediaItemAspectTypeRegistration>();

            Console.WriteLine("Before extract:");
            ShowMIAs(aspects, registration);

            IMetadataExtractor extractor = new Tve3RecordingMetadataExtractor();
            IResourceAccessor  accessor  = new MockLocalFsResourceAccessor(ProviderPathHelper.ChangeExtension(filename, ".ts"));

            extractor.TryExtractMetadataAsync(accessor, aspects, false);

            Console.WriteLine("After extract:");
            ShowMIAs(aspects, registration);

            string value;

            if (MediaItemAspect.TryGetExternalAttribute(aspects, ExternalIdentifierAspect.SOURCE_TVDB, ExternalIdentifierAspect.TYPE_SERIES, out value))
            {
                SeriesInfo seriesInfo = new SeriesInfo()
                {
                    TvdbId = Int32.Parse(value)
                };
                SeriesTvDbMatcher.Instance.UpdateSeriesAsync(seriesInfo, false).Wait();
                Console.WriteLine("{0}: {1}", seriesInfo.SeriesName, seriesInfo.Description);
            }
        }
 public void User3DClickAt(object sender, ApplicationCore.ViewModels.Editors.World3DClickEventArgs e)
 {
 }
Example #7
0
        /// <summary>
        /// The main entry point for the MP 2 server application.
        /// </summary>
        private static void Main(params string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            // Parse Command Line options
            CommandLineOptions mpArgs = new CommandLineOptions();
            ICommandLineParser parser = new CommandLineParser(new CommandLineParserSettings(Console.Error));

            if (!parser.ParseArguments(args, mpArgs, Console.Out))
            {
                Environment.Exit(1);
            }

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Team MediaPortal\MP2-Server\Log");
#endif

            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);


            SystemStateService systemStateService = new SystemStateService();
            ServiceRegistration.Set <ISystemStateService>(systemStateService);
            systemStateService.SwitchSystemState(SystemState.Initializing, false);

            try
            {
                ILogger logger = null;
                try
                {
                    // Check if user wants to override the default Application Data location.
                    ApplicationCore.RegisterCoreServices(mpArgs.DataDirectory);
                    logger = ServiceRegistration.Get <ILogger>();

#if !DEBUG
                    IPathManager pathManager = ServiceRegistration.Get <IPathManager>();
                    logPath = pathManager.GetPath("<LOG>");
#endif

                    BackendExtension.RegisterBackendServices();
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.Critical("Error starting application", e);
                    }
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;

                    BackendExtension.DisposeBackendServices();
                    ApplicationCore.DisposeCoreServices();

                    throw;
                }

                // Start the core
                logger.Debug("ApplicationLauncher: Starting core");

                try
                {
                    IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
                    IPluginManager pluginManager = ServiceRegistration.Get <IPluginManager>();
                    pluginManager.Initialize();
                    pluginManager.Startup(false);
                    ApplicationCore.StartCoreServices();

                    BackendExtension.StartupBackendServices();
                    ApplicationCore.RegisterDefaultMediaItemAspectTypes(); // To be done after backend services are running

                    mediaAccessor.Initialize();

                    systemStateService.SwitchSystemState(SystemState.Running, true);
                    BackendExtension.ActivateImporterWorker(); // To be done after default media item aspect types are present and when the system is running (other plugins might also install media item aspect types)

                    Application.Run(new MainForm());

                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true; // Block ServiceRegistration from trying to load new services in shutdown phase

                    mediaAccessor.Shutdown();

                    pluginManager.Shutdown();

                    BackendExtension.ShutdownBackendServices();
                    ApplicationCore.StopCoreServices();
                }
                catch (Exception e)
                {
                    logger.Critical("Error executing application", e);
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;
                }
                finally
                {
                    BackendExtension.DisposeBackendServices();
                    ApplicationCore.DisposeCoreServices();
                    systemStateService.SwitchSystemState(SystemState.Ending, false);
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ConsoleLogger log = new ConsoleLogger(LogLevel.All, false);
                log.Error(ex);
#else
                ServerCrashLogger crash = new ServerCrashLogger(logPath);
                crash.CreateLog(ex);
#endif
                systemStateService.SwitchSystemState(SystemState.Ending, false);
                Application.Exit();
            }
        }
Example #8
0
        /// <summary>
        /// The main entry point for the MP2-ClientLauncher application.
        /// </summary>
        private static void Main(params string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

            // Check if another instance is already running
            if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
            {
                _mutex = null;
                // Stop current instance
                Console.Out.WriteLine("Application already running.");
                Environment.Exit(2);
            }

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                                          @"Team MediaPortal", "MP2-Client", "Log");
#endif

            //// todo: Make sure we're properly handling exceptions
            //DispatcherUnhandledException += OnUnhandledException;
            //AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;

            // Start core services
            ILogger logger = null;
            try
            {
                // Check if user wants to override the default Application Data location.
                ApplicationCore.RegisterVitalCoreServices(mpOptions.DataDirectory);

                logger = ServiceRegistration.Get <ILogger>();

#if !DEBUG
                logPath = ServiceRegistration.Get <IPathManager>().GetPath("<LOG>");
#endif
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.Critical("Error starting application", e);
                }

                ApplicationCore.DisposeCoreServices();

                throw;
            }

            // Start application
            logger.Info("Starting application");

            try
            {
                if (TerminateProcess("ehtray"))
                {
                    logger.Info("Terminating running instance(s) of ehtray.exe");
                }

                Remote.Transceivers.AddRange(GetTransceiverList());
                Remote.Click         += OnClick;
                Device.DeviceArrival += OnDeviceArrival;
                Device.DeviceRemoval += OnDeviceRemoval;

                if (!mpOptions.NoIcon)
                {
                    InitTrayIcon();
                }

                Application.Run();
            }
            catch (Exception e)
            {
                logger.Critical("Error executing application", e);
            }

            logger.Info("Exiting...");



            // Release mutex for single instance
            if (_mutex != null)
            {
                _mutex.ReleaseMutex();
            }

            Application.Exit();
        }
Example #9
0
 public RoutesDefaultsWithLanguage(ApplicationCore core) : base(core)
 {
     Language = core.Get <Core.Languages.Manager>().GetUserLanguage().ShortName;
 }
        public ClientWindowViewModel()
        {
            var core    = ((App)Application.Current).Core;
            var library = core.Library;

            var client = new Client(new LibraryFront(library), core).AddTo(this.Disposables);

            this.Client = client;
            this.Core   = core;

            this.KeyReceiver = new KeyReceiver <object>().AddTo(this.Disposables);

            this.WindowTitle = client.SelectedPage
                               .CombineLatest(client.ViewerDisplaying, (Page, Item) => new { Page, Item })
                               .Select(x =>
            {
                var file = (x.Page == PageType.Viewer) ? x.Item?.FileName : null;
                return((file == null) ? core.AppName : (file + " - " + core.AppName));
            })
                               .ToReadOnlyReactiveProperty()
                               .AddTo(this.Disposables);

            this.SelectedInformationPage = new ReactiveProperty <OptionPaneType>
                                               (core.IsViewerPageLeftBarFixed ? OptionPaneType.ItemInfo : OptionPaneType.None)
                                           .AddTo(this.Disposables);

            this.IsPaneOpen = new ReactiveProperty <bool>(core.IsViewerPageLeftBarFixed)
                              .AddTo(this.Disposables);


            this.IsPaneFixed = core
                               .ToReactivePropertyAsSynchronized(x => x.IsViewerPageLeftBarFixed)
                               .AddTo(this.Disposables);

            this.SelectedTab = client.SelectedPage
                               .Select(x =>
            {
                switch (x)
                {
                case PageType.Search:
                    return(0);

                case PageType.Catalog:
                    return(1);

                case PageType.Viewer:
                    return(2);

                default:
                    return(0);
                }
            })
                               .ToReactiveProperty(0)
                               .AddTo(this.Disposables);


            this.SelectedTab.Subscribe(x =>
            {
                if (this.IsPaneOpen.Value)
                {
                    if (this.IsPaneFixed.Value)
                    {
                        this.ShowInformationPane();
                    }
                    else
                    {
                        this.IsPaneOpen.Value = false;
                    }
                }
            })
            .AddTo(this.Disposables);

            this.Client.FeaturedGroupChanged.Subscribe(x =>
            {
                if (client.SelectedPage.Value == PageType.Catalog && this.IsPaneOpen.Value)
                {
                    this.ShowInformationPane();
                }
            })
            .AddTo(this.Disposables);


            this.PaneSelectedPath = new ReactiveProperty <string>((string)null)
                                    .AddTo(this.Disposables);
            this.PaneSelectedPath.Where(x => !string.IsNullOrWhiteSpace(x))
            .Subscribe(x => this.StartPathOrTagSearch(FileProperty.DirectoryPathStartsWith, x))
            .AddTo(this.Disposables);

            this.PaneSelectedTag = new ReactiveProperty <TagInformation>((TagInformation)null)
                                   .AddTo(this.Disposables);
            this.PaneSelectedTag.Where(x => x != null)
            .Subscribe(x => this.StartPathOrTagSearch(FileProperty.ContainsTag, x.Id))
            .AddTo(this.Disposables);

            this.DefaultPaneMode = client.SelectedPage
                                   .Select(x => (x == PageType.Viewer) ? PaneMode.HideInClosing
                    : PaneMode.AlwaysVisible)
                                   .ToReactiveProperty(PaneMode.AlwaysVisible)
                                   .AddTo(this.Disposables);



            this.IsOptionPageOpen = this.SelectedInformationPage
                                    .Select(x => x > 0)
                                    .ToReactiveProperty()
                                    .AddTo(this.Disposables);


            //情報
            this.IsInformationPaneOpen = this.SelectedInformationPage
                                         .Select(x => this.IsInformationPane(x))
                                         .ToReactiveProperty(false)
                                         .AddTo(this.Disposables);

            this.OpenInformationPaneCommand = new ReactiveCommand()
                                              .WithSubscribe(_ =>
            {
                if (this.IsInformationPaneOpen.Value)
                {
                    if (this.prevPaneSelected == OptionPaneType.None)
                    {
                        this.prevPaneSelected = OptionPaneType.NoInformation;
                    }
                    this.ShowInformationPane(true);
                }
                else
                {
                    if (this.SelectedInformationPage.Value != OptionPaneType.Setting)
                    {
                        this.SelectedInformationPage.Value = OptionPaneType.None;
                    }
                }
            }, this.Disposables);



            //設定
            this.IsSettingPaneOpen = this.SelectedInformationPage
                                     .Select(x => x == OptionPaneType.Setting)
                                     .ToReactiveProperty(false)
                                     .AddTo(this.Disposables);

            this.OpenSettingPaneCommand = new ReactiveCommand()
                                          .WithSubscribe(_ =>
            {
                if (this.IsSettingPaneOpen.Value)
                {
                    this.SelectedInformationPage.Value = OptionPaneType.Setting;
                    this.IsPaneOpen.Value = true;
                }
                else
                {
                    if (this.SelectedInformationPage.Value == OptionPaneType.Setting)
                    {
                        this.SelectedInformationPage.Value = OptionPaneType.None;
                    }
                }
            }, this.Disposables);



            //ヘルプ
            this.IsHelpPaneOpen = this.SelectedInformationPage
                                  .Select(x => x == OptionPaneType.Help)
                                  .ToReactiveProperty(false)
                                  .AddTo(this.Disposables);

            this.OpenHelpPaneCommand = new ReactiveCommand()
                                       .WithSubscribe(_ =>
            {
                if (this.IsHelpPaneOpen.Value)
                {
                    this.SelectedInformationPage.Value = OptionPaneType.Help;
                    this.IsPaneOpen.Value = true;
                }
                else
                {
                    if (this.SelectedInformationPage.Value == OptionPaneType.Help)
                    {
                        this.SelectedInformationPage.Value = OptionPaneType.None;
                    }
                }
            }, this.Disposables);



            this.OptionPaneVisibility = this.SelectedInformationPage
                                        .Select(x => VisibilityHelper.Set(x > 0))
                                        .ToReactiveProperty()
                                        .AddTo(this.Disposables);

            this.FrameWidth = new ReactiveProperty <double>(300).AddTo(this.Disposables);

            this.IsFullScreen = client.SelectedPage.Select(_ => false).ToReactiveProperty().AddTo(this.Disposables);

            this.PageChangedSubject = new Subject <SplitViewDisplayMode>().AddTo(this.Disposables);

            this.PaneDisplayMode = this.IsPaneFixed
                                   .CombineLatest(this.DefaultPaneMode,
                                                  (paneFixed, defaultMode) =>
                                                  (defaultMode == PaneMode.Disabled) ? SplitViewDisplayMode.Overlay
                    : (paneFixed) ? SplitViewDisplayMode.CompactInline
                    : (defaultMode == PaneMode.HideInClosing) ? SplitViewDisplayMode.Overlay
                    : SplitViewDisplayMode.CompactOverlay)
                                   .ToReactiveProperty()
                                   .AddTo(this.Disposables);

            this.IsPaneOpen
            .Subscribe(x =>
            {
                if (!x)
                {
                    this.IsPaneFixed.Value             = false;
                    this.SelectedInformationPage.Value = OptionPaneType.None;
                    if (this.PaneDisplayMode.Value == SplitViewDisplayMode.CompactInline)
                    {
                        this.PaneDisplayMode.Value = SplitViewDisplayMode.CompactOverlay;
                    }
                }
            })
            .AddTo(this.Disposables);


            this.PaneOpenButtonVisibility = new ReactiveProperty <Visibility>(Visibility.Collapsed)
                                            .ToReactiveProperty()
                                            .AddTo(this.Disposables);

            var isWide = this.FrameWidth.Select(y => y > middleWindowWidth).Publish().RefCount();

            this.PaneFixButtonVisibility = isWide.Select(y => VisibilityHelper.Set(y))
                                           .ToReactiveProperty().AddTo(this.Disposables);
            isWide.Where(y => !y).Skip(2).Subscribe(y => this.IsPaneFixed.Value = false).AddTo(this.Disposables);

            this.JumpListWidth = this.IsOptionPageOpen.Select(x => x ? compactPaneWidth : openPaneWidth)
                                 .ToReactiveProperty().AddTo(this.Disposables);

            this.IsOptionPageOpen.Subscribe(x =>
            {
                if (x && this.SelectedInformationPage.Value != OptionPaneType.NoInformation &&
                    !core.IsAutoInformationPaneDisabled)
                {
                    this.IsPaneOpen.Value = true;
                }
            }).AddTo(this.Disposables);



            this.OpenSettingWindowCommand = new ReactiveCommand()
                                            .WithSubscribe(_ => ((App)Application.Current).ShowSettingWindow(-1), this.Disposables);

            this.OptionPageCommand = new ReactiveCommand <string>().AddTo(this.Disposables);



            this.IsPopupOpen = new ReactiveProperty <bool>(false).AddTo(this.Disposables);

            this.IsPopupOpen
            .Subscribe(x => this.KeyReceiver.Mode
                           = (int)(x ? KeyReceiverMode.PopupIsOpened : KeyReceiverMode.Normal))
            .AddTo(this.Disposables);



            this.prevPaneMode     = this.PaneDisplayMode.Value;
            this.prevPaneOpen     = this.IsPaneOpen.Value;
            this.prevPaneSelected = (OptionPaneType)this.SelectedInformationPage.Value;

            this.SelectedItems.ObserveProperty(x => x.Count).Pairwise().Subscribe(x =>
            {
                var autoOpen = !core.IsAutoInformationPaneDisabled;

                if (x.OldItem <= 0 && x.NewItem > 0)
                {
                    this.prevPaneMode     = this.PaneDisplayMode.Value;
                    this.prevPaneOpen     = this.IsPaneOpen.Value;
                    this.prevPaneSelected = (OptionPaneType)this.SelectedInformationPage.Value;

                    if (autoOpen && this.FrameWidth.Value > wideWindowWidth)
                    {
                        this.PaneDisplayMode.Value = SplitViewDisplayMode.CompactInline;
                        this.IsPaneOpen.Value      = true;
                    }

                    this.ShowInformationPane();
                }
                else if (x.OldItem > 0 && x.NewItem > 0 &&
                         (this.FrameWidth.Value > wideWindowWidth || this.IsPaneOpen.Value))
                {
                    this.ShowInformationPane();
                }
                else if (x.OldItem > 0 && x.NewItem <= 0)
                {
                    if (autoOpen)
                    {
                        this.PaneDisplayMode.Value = this.prevPaneMode;
                    }

                    this.ShowInformationPane();

                    if (autoOpen)
                    {
                        this.IsPaneOpen.Value = this.prevPaneOpen;
                    }
                }
            })
            .AddTo(this.Disposables);


            this.IsPaneFixed
            .Subscribe(x =>
            {
                if (x)
                {
                    this.prevPaneMode = SplitViewDisplayMode.CompactInline;
                    this.prevPaneOpen = true;
                }
                else
                {
                    this.prevPaneMode = SplitViewDisplayMode.CompactOverlay;
                    this.prevPaneOpen = false;
                }
            })
            .AddTo(this.Disposables);

            this.TagSelectorSortMode = core
                                       .ToReactivePropertyAsSynchronized(x => x.TagSelectorSortMode)
                                       .AddTo(this.Disposables);

            this.ExifVisibilityCheck = new ReactiveProperty <bool>(false).AddTo(this.Disposables);
            this.ExifVisibilityCheck
            .Skip(1)
            .Subscribe(x => core.Library.ExifManager.EnableAll(x)).AddTo(this.Disposables);

            this.IsExifEnabled = core.Library.ExifManager.HasVisibleItem
                                 .ToReadOnlyReactiveProperty().AddTo(this.Disposables);


            this.BackCommand = client.BackHistoryCount
                               .Select(x => x > 0)
                               .ToReactiveCommand()
                               .WithSubscribe(_ => client.Back(), this.Disposables);

            this.MoveToSearchPageCommand = new ReactiveCommand()
                                           .WithSubscribe(x => client.MoveToSearch(), this.Disposables);

            this.OpenPaneCommand = new ReactiveCommand()
                                   .WithSubscribe(_ => this.TogglePane(OptionPaneType.None), this.Disposables);

            // ウインドウへのファイルのドラッグ&ドロップ
            this.FileDropCommand = new ReactiveCommand()
                                   .WithSubscribe(obj =>
            {
                var files = obj as string[];
                if (files != null)
                {
                    this.Client.ActivateFiles(files);
                }
            }, this.Disposables);

            this.MouseExButtonSubject = new Subject <bool>().AddTo(this.Disposables);

            this.MouseExButtonLeftCommand = new ReactiveCommand()
                                            .WithSubscribe(_ =>
            {
                if (core.UseExtendedMouseButtonsToSwitchImage &&
                    client.SelectedPage.Value == PageType.Viewer)
                {
                    this.MouseExButtonSubject.OnNext(false);
                }
                else
                {
                    client.Back();
                }
            }, this.Disposables);

            this.MouseExButtonRightCommand = new ReactiveCommand()
                                             .WithSubscribe(_ =>
            {
                if (core.UseExtendedMouseButtonsToSwitchImage &&
                    client.SelectedPage.Value == PageType.Viewer)
                {
                    this.MouseExButtonSubject.OnNext(true);
                }
                else
                {
                    client.Forward();
                }
            }, this.Disposables);


            //Keyboard
            this.RegisterKeyReceiver(client);

            this.Catalog = new CatalogPageViewModel(this).AddTo(this.Disposables);
            this.Viewer  = new ViewerPageViewModel(this).AddTo(this.Disposables);
            this.Search  = new SearchPageViewModel(this).AddTo(this.Disposables);
        }
Example #11
0
        static void Main(string[] args)
        {
            Gtk.Application.Init();
            GLib.ExceptionManager.UnhandledException += ExceptionManager_UnhandledException;
            var globalStyleSheet = @"
                                    .large-font{ font-size: 16px; }
                                    .medium-font{ font-size: 14px; }
                                    ";

            var screen   = Gdk.Screen.Default;
            var provider = new CssProvider();

            provider.LoadFromData(globalStyleSheet);
            Gtk.StyleContext.AddProviderForScreen(screen, provider, 800);
            //var screen = Gdk.Screen.Default;
            //var provider = new CssProvider();
            //provider.LoadFromData(@".dark
            //                                    {
            //                                        color: gray;
            //                                        background: rgb(36,41,46);
            //                                    }

            //                                    treeview.view :selected
            //                                    {
            //                                        background-color: rgb(10,106,182);
            //                                        color: white;
            //                                    }
            //.listt
            //{
            //font-family: Segoe UI;
            //}
            //                                    .dark2
            //                                    {
            //                                        color: gray;
            //                                        background: rgb(35,35,35);
            //                                        /*background: rgb(36,41,46);*/
            //                                    }
            //                                    .toolbar-border-dark
            //                                    {
            //                                        border-bottom: 1px solid rgb(20,20,20);
            //                                    }
            //                                    .toolbar-border-light
            //                                    {
            //                                        border-bottom: 2px solid rgb(240,240,240);
            //                                    }
            //                                  ");
            //Gtk.StyleContext.AddProviderForScreen(screen, provider, 800);

            ServicePointManager.ServerCertificateValidationCallback += (a, b, c, d) => true;
            ServicePointManager.DefaultConnectionLimit = 100;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault;

            AppContext.SetSwitch(DisableCachingName, true);
            AppContext.SetSwitch(DontEnableSchUseStrongCryptoName, true);

            TextResource.Load(Config.Instance.Language);

            var debugMode = Environment.GetEnvironmentVariable("XDM_DEBUG_MODE");

            if (!string.IsNullOrEmpty(debugMode) && debugMode == "1")
            {
                var logFile = System.IO.Path.Combine(Config.DataDir, "log.txt");
                Log.InitFileBasedTrace(System.IO.Path.Combine(Config.DataDir, "log.txt"));
            }
            Log.Debug("Application_Startup");

            if (Config.Instance.AllowSystemDarkTheme)
            {
                Gtk.Settings.Default.ThemeName = "Adwaita";
                Gtk.Settings.Default.ApplicationPreferDarkTheme = true;
            }

            var core = new ApplicationCore();
            var app  = new XDMApp();
            var win  = new MainWindow();

            ApplicationContext.Configurer()
            .RegisterApplicationWindow(win)
            .RegisterApplication(app)
            .RegisterApplicationCore(core)
            .RegisterCapturedVideoTracker(new VideoTracker())
            .RegisterClipboardMonitor(new ClipboardMonitor())
            .RegisterLinkRefresher(new LinkRefresher())
            .RegisterPlatformUIService(new GtkPlatformUIService())
            .Configure();

            var commandOptions = ArgsProcessor.ParseArgs(args, 0);

            if (!commandOptions.ContainsKey("-m"))
            {
                win.Show();
                if (commandOptions.ContainsKey("-i"))
                {
                    Config.Instance.RunOnLogon = true;
                    Config.SaveConfig();
                    ApplicationContext.PlatformUIService.ShowBrowserMonitoringDialog();
                }
            }

            //var t = new System.Threading.Thread(() =>
            //  {
            //      while (true)
            //      {
            //          System.Threading.Thread.Sleep(5000);
            //          Console.WriteLine("Trigger GC");
            //          GC.Collect();
            //      }
            //  });
            //t.Start();

            Gtk.Application.Run();

            //var app = new XDM.Core.XDM.Core();
            //var appWin = new AppWinPeer(app);
            //appWin.ShowAll();
            //Application.Run();


            //            Environment.SetEnvironmentVariable("PANGOCAIRO_BACKEND", "fc", EnvironmentVariableTarget.User);
            //            //Console.WriteLine(Environment.GetEnvironmentVariable("PANGOCAIRO_BACKEND"));
            //            //var arr = new string[] {  "PANGOCAIRO_BACKEND=fc" };
            //            Application.Init();// "app", ref arr);
            //            Gtk.Settings.Default.ThemeName = "Adwaita";
            //            Gtk.Settings.Default.ApplicationPreferDarkTheme = true;

            //            App app = new App();



            //            var appWin = new AppWin();
            //            Console.WriteLine("Starting show all");
            //            appWin.Show();
            //            Console.WriteLine("Finished show all");
            //            Application.Run();
        }
Example #12
0
        /// <summary>
        /// Either shows the application's main window or inits the application in the system tray.
        /// </summary>
        private void OnStartup(object sender, StartupEventArgs args)
        {
            Thread.CurrentThread.Name = "Main";
            Thread.CurrentThread.SetApartmentState(ApartmentState.STA);

            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args.Args, mpOptions, () => Environment.Exit(1));

            // Check if another instance is already running
            // If new instance was created by UacHelper previous one, assume that previous one is already closed.
            if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
            {
                _mutex = null;
                // Set focus on previously running app
                SingleInstanceHelper.SwitchToCurrentInstance(SingleInstanceHelper.SHOW_MP2_SERVICEMONITOR_MESSAGE);
                // Stop current instance
                Console.Out.WriteLine("Application already running.");
                Environment.Exit(2);
            }

            // Make sure we're properly handling exceptions
            DispatcherUnhandledException += OnUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;

            var systemStateService = new SystemStateService();

            ServiceRegistration.Set <ISystemStateService>(systemStateService);
            systemStateService.SwitchSystemState(SystemState.Initializing, false);

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Team MediaPortal\MP2-ServiceMonitor\Log");
#endif

            try
            {
                ILogger logger = null;
                try
                {
                    ApplicationCore.RegisterVitalCoreServices(true);
                    ApplicationCore.RegisterCoreServices();
                    logger = ServiceRegistration.Get <ILogger>();

                    logger.Debug("Starting Localization");
                    Localization localization = new Localization();
                    ServiceRegistration.Set <ILocalization>(localization);
                    localization.Startup();

                    //ApplicationCore.StartCoreServices();

                    logger.Debug("UiExtension: Registering ISystemResolver service");
                    ServiceRegistration.Set <ISystemResolver>(new SystemResolver());

                    logger.Debug("UiExtension: Registering IServerConnectionManager service");
                    ServiceRegistration.Set <IServerConnectionManager>(new ServerConnectionManager());

#if !DEBUG
                    logPath = ServiceRegistration.Get <IPathManager>().GetPath("<LOG>");
#endif
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.Critical("Error starting application", e);
                    }

                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;

                    ApplicationCore.DisposeCoreServices();

                    throw;
                }

                InitIpc();

                var appController = new AppController();
                ServiceRegistration.Set <IAppController>(appController);

                // Start the application
                logger.Debug("Starting application");
                try
                {
                    ServiceRegistration.Get <IServerConnectionManager>().Startup();
                    appController.StartUp(mpOptions);
                }
                catch (Exception e)
                {
                    logger.Critical("Error executing application", e);
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                var log = new ConsoleLogger(LogLevel.All, false);
                log.Error(ex);
#else
                ServerCrashLogger crash = new ServerCrashLogger(logPath);
                crash.CreateLog(ex);
#endif
                systemStateService.SwitchSystemState(SystemState.Ending, false);
                Current.Shutdown();
            }
        }
Example #13
0
        public void UserIsAssociatedNullApplication()
        {
            var core = new ApplicationCore();

            core.UserIsAssociated(this.UserApplication(Guid.NewGuid()), null);
        }
Example #14
0
        public void ApplicationCountNullUser()
        {
            var core = new ApplicationCore();

            core.ApplicationCount(null);
        }
 public FunctionEvaluatorState(ApplicationCore core)
     : base(core)
 {
     IsFunction = true;
 }
Example #16
0
 public ConsoleUi(ApplicationCore applicationCore)
 {
     this.applicationCore = applicationCore;
 }
        public EditSearchViewModel(ISqlSearch source)
        {
            var core = ((App)Application.Current).Core;

            this.library  = core.Library;
            this.settings = core;

            this.unsubscribers = new CompositeDisposable();


            this.PropertyList = FilePropertyManager.GetPropertyListToSearch()
                                .Select(x => new KeyValuePair <string, PropertyContainer>(x.Key, new PropertyContainer(x.Value)))
                                .ToList();

            if (!source.IsUnit)
            {
                this.PropertyList.Add
                    (new KeyValuePair <string, PropertyContainer>
                        (settings.GetResourceString("MatchAll"), new PropertyContainer(ComplexMode.And)));
                this.PropertyList.Add
                    (new KeyValuePair <string, PropertyContainer>
                        (settings.GetResourceString("MatchAny"), new PropertyContainer(ComplexMode.Or)));
            }

            this.PropertyComboBoxDefault = settings.GetResourceString("Property");
            this.TagComboBoxDefault      = settings.GetResourceString("Tag");


            this.CompareOperator = new List <KeyValuePair <string, CompareMode> >();
            this.AddCompareSymbol(CompareMode.Great);
            this.AddCompareSymbol(CompareMode.GreatEqual);
            this.AddCompareSymbol(CompareMode.Equal);
            this.AddCompareSymbol(CompareMode.LessEqual);
            this.AddCompareSymbol(CompareMode.Less);
            this.AddCompareSymbol(CompareMode.NotEqual);

            this.EqualitySelector = new ObservableCollection <string>()
            {
                "", ""
            };


            this.isSVO          = settings.IsSVOLanguage;
            this.BelowRefString = settings.GetResourceString("BelowRef");
            this.IsVString      = settings.GetResourceString("IsV");

            this.SourceItem = source;

            var unit = source.IsUnit ? (UnitSearch)source : null;

            this.Init(unit);


            this.IsEditing = new ReactiveProperty <bool>(true).AddTo(this.unsubscribers);

            this.OkCommand = this.PropertyListSelectedIndex
                             .Select(x => x >= 0)
                             .ToReactiveCommand()
                             .WithSubscribe(_ =>
            {
                this.Commit();
                this.IsEditing.Value = false;
            }, this.unsubscribers);
            this.CancelCommand = new ReactiveCommand()
                                 .WithSubscribe(_ => this.IsEditing.Value = false, this.unsubscribers);


            var propertyObserver = this.PropertyListSelectedIndex
                                   .Select(x =>
            {
                var container = this.GetProperty(x);
                return(new
                {
                    Property = container.Property,
                    Enable = (container.Complex == ComplexMode.None &&
                              container.IsValid)
                });
            })
                                   .Publish().RefCount();

            this.CompareListVisibility = propertyObserver
                                         .Select(x => VisibilityHelper.Set(x.Enable && x.Property.IsComperable()))
                                         .ToReactiveProperty().AddTo(this.unsubscribers);

            this.EqualityListVisibility = propertyObserver
                                          .Select(x => VisibilityHelper.Set(x.Enable && !x.Property.IsComperable()))
                                          .ToReactiveProperty().AddTo(this.unsubscribers);

            this.NumericTextVisibility = propertyObserver
                                         .Select(x => VisibilityHelper.Set(x.Enable && x.Property.IsInteger()))
                                         .ToReactiveProperty().AddTo(this.unsubscribers);

            this.FloatTextVisibility = propertyObserver
                                       .Select(x => VisibilityHelper.Set(x.Enable && x.Property.IsFloat()))
                                       .ToReactiveProperty().AddTo(this.unsubscribers);

            this.DirectoryListVisibility = propertyObserver
                                           .Select(x => VisibilityHelper.Set(x.Enable && x.Property == FileProperty.DirectoryPathStartsWith))
                                           .ToReactiveProperty().AddTo(this.unsubscribers);

            this.TagListVisibility = propertyObserver
                                     .Select(x => VisibilityHelper.Set(x.Enable && x.Property == FileProperty.ContainsTag))
                                     .ToReactiveProperty().AddTo(this.unsubscribers);

            this.TextBoxVisibility = propertyObserver
                                     .Select(x => VisibilityHelper.Set(x.Enable && x.Property.IsText()))
                                     .ToReactiveProperty().AddTo(this.unsubscribers);

            this.DateVisibility = propertyObserver
                                  .Select(x => VisibilityHelper.Set(x.Enable && x.Property.IsDate()))
                                  .ToReactiveProperty().AddTo(this.unsubscribers);

            this.IsVStringVisibility = propertyObserver
                                       .Select(x => VisibilityHelper.Set(x.Enable && !this.isSVO))
                                       .ToReactiveProperty().AddTo(this.unsubscribers);

            this.PropertyComboBoxDefaultVisibility = this.PropertyListSelectedIndex
                                                     .Select(x => VisibilityHelper.Set(x < 0))
                                                     .ToReactiveProperty()
                                                     .AddTo(this.unsubscribers);

            this.TagComboBoxDefaultVisibility
                = new[]
                {
                this.TagListSelectedIndex.Select(x => x < 0),
                propertyObserver.Select(x => x.Enable && x.Property == FileProperty.ContainsTag)
                }
            .CombineLatestValuesAreAllTrue()
            .Select(x => VisibilityHelper.Set(x))
            .ToReactiveProperty()
            .AddTo(this.unsubscribers);


            propertyObserver.Subscribe(x =>
            {
                if (x.Enable)
                {
                    var currentIndex = this.EqualitySelectedIndex.Value;
                    this.EqualitySelector[this.GetEqualitySelectorIndex(true)]
                        = x.Property.GetEqualityLabel(true);
                    this.EqualitySelector[this.GetEqualitySelectorIndex(false)]
                        = x.Property.GetEqualityLabel(false);
                    this.EqualitySelectedIndex.Value = currentIndex;
                }
            }).AddTo(this.unsubscribers);


            this.PropertyListSelectedIndex.Value =
                unit == null
                ? -1
                : this.PropertyList.FindIndex(x => x.Value.Property == unit.Property);
        }
Example #18
0
        public void UserIsAssociatedEmptyApplicationIdentifier()
        {
            var core = new ApplicationCore();

            core.UserIsAssociated(this.UserApplication(Guid.NewGuid()), this.App(Guid.Empty));
        }
Example #19
0
        public void UserIsAssociatedNullEditor()
        {
            var core = new ApplicationCore();

            core.UserIsAssociated(null, this.App(Guid.NewGuid()));
        }
Example #20
0
        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args.Contains("WAIT"))
            {
                Thread.Sleep(5000);
            }

            SplashScreen appSplash = null;

            Fap.Foundation.SafeObservableStatic.Dispatcher = System.Windows.Application.Current.Dispatcher;
            SafeObservingCollectionManager.Start();
            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

            base.OnStartup(e);
            if (Compose())
            {
                if (e.Args.Length == 1 && e.Args[0] == "WAIT")
                {
                    //Delay the application starting up, used when restarting.
                    Thread.Sleep(3000);
                }

                ApplicationCore core = container.Resolve <ApplicationCore>();

                if (!core.CheckSingleInstance())
                {
                    //An instance of fap is already running.

                    //If we got a download url then forward onto the runing instance of FAP
                    if (e.Args.Length == 2 && e.Args[0] == "-url")
                    {
                        Model model = new Model();
                        model.Load();

                        Client      client = new Client(model.LocalNode);
                        AddDownload verb   = new AddDownload();
                        verb.URL = e.Args[1];
                        if (client.Execute(verb, model.LocalNode))
                        {
                            //Download sent successfully
                            Shutdown(0);
                            return;
                        }
                        else
                        {
                            //Unsuccessful - Notify user
                            WPFMessageBox.Show("FAP", "Failed to add download via RPC!");
                            Shutdown(1);
                            return;
                        }
                    }
                    else
                    {
                        //Inform the user they cannot run multiple instances
                        WPFMessageBox.Show("FAP", "An instance of FAP is already running");
                        Shutdown(1);
                        return;
                    }
                }

                string img = GetImage();
                appSplash = new SplashScreen(img);
                appSplash.Show(true);

                if (core.Load(false))
                {
                    core.StartClient();
                    core.StartGUI(!(e.Args.Contains("STARTUP")));
                    //Was a url passed on startup?
                    if (e.Args.Length == 2 && e.Args[0] == "-url")
                    {
                        core.AddDownloadUrlWhenConnected(e.Args[1]);
                    }
                }
                else
                {
                    Shutdown(1);
                }
            }
            else
            {
                Shutdown(1);
            }
            if (null != appSplash)
            {
                appSplash.Close(TimeSpan.FromSeconds(0));
            }
        }
Example #21
0
        public void GetApplicationInformationNull()
        {
            var core = new ApplicationCore();

            core.Get((ApplicationInformation)null);
        }
Example #22
0
 public RouteHandler(ApplicationCore core)
 {
     _core = core;
 }
Example #23
0
        public void SaveUserApplicationNullUserApplication()
        {
            var core = new ApplicationCore();

            core.Save((UserApplication)null, this.UserApplication(Guid.NewGuid()));
        }
Example #24
0
 public SettingsController(IContainer c, Model m, ApplicationCore ac)
 {
     container = c;
     model     = m;
     core      = ac;
 }
Example #25
0
        public void GetUserApplicationNull()
        {
            var core = new ApplicationCore();

            core.Get((Application)null);
        }
Example #26
0
        /// <summary>
        /// The main entry point for the MP2 client application.
        /// </summary>
        private static void Main(params string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            // Parse command line options
            var mpOptions = new CommandLineOptions();
            var parser    = new CommandLine.Parser(with => with.HelpWriter = Console.Out);

            parser.ParseArgumentsStrict(args, mpOptions, () => Environment.Exit(1));

            // Check if another instance is already running
            if (SingleInstanceHelper.IsAlreadyRunning(MUTEX_ID, out _mutex))
            {
                _mutex = null;
                // Set focus on previously running app
                SingleInstanceHelper.SwitchToCurrentInstance(SingleInstanceHelper.SHOW_MP2_CLIENT_MESSAGE);
                // Stop current instance
                Console.Out.WriteLine("Application already running.");
                Environment.Exit(2);
            }

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Team MediaPortal\MP2-Client\Log");
#endif

            Application.ThreadException += LauncherExceptionHandling.Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += LauncherExceptionHandling.CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException      += LauncherExceptionHandling.TaskScheduler_UnobservedTaskException;

            SystemStateService systemStateService = new SystemStateService();
            ServiceRegistration.Set <ISystemStateService>(systemStateService);
            systemStateService.SwitchSystemState(SystemState.Initializing, false);

            try
            {
#if !DEBUG
                SplashScreen splashScreen = null;
#endif
                ILogger logger = null;
                try
                {
                    // Check if user wants to override the default Application Data location.
                    ApplicationCore.RegisterVitalCoreServices(true, mpOptions.DataDirectory);

#if !DEBUG
                    splashScreen = CreateSplashScreen();
                    splashScreen.ShowSplashScreen();
#endif

                    ApplicationCore.RegisterCoreServices();

                    logger = ServiceRegistration.Get <ILogger>();

#if !DEBUG
                    IPathManager pathManager = ServiceRegistration.Get <IPathManager>();
                    logPath = pathManager.GetPath("<LOG>");
#endif

                    UiExtension.RegisterUiServices();
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.Critical("Error starting application", e);
                    }
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;

                    UiExtension.DisposeUiServices();
                    ApplicationCore.DisposeCoreServices();

                    throw;
                }

                // Start the core
                logger.Debug("ApplicationLauncher: Starting application");

                try
                {
                    IPluginManager pluginManager = ServiceRegistration.Get <IPluginManager>();
                    pluginManager.Initialize();
                    pluginManager.Startup(false);
                    ApplicationCore.StartCoreServices();

                    ISkinEngine            skinEngine            = ServiceRegistration.Get <ISkinEngine>();
                    IWorkflowManager       workflowManager       = ServiceRegistration.Get <IWorkflowManager>();
                    IMediaAccessor         mediaAccessor         = ServiceRegistration.Get <IMediaAccessor>();
                    ILocalSharesManagement localSharesManagement = ServiceRegistration.Get <ILocalSharesManagement>();

                    // We have to handle some dependencies here in the start order:
                    // 1) After all plugins are loaded, the SkinEngine can initialize (=load all skin resources)
                    // 2) After the skin resources are loaded, the workflow manager can initialize (=load its states and actions)
                    // 3) Before the main window is shown, the splash screen should be hidden
                    // 4) After the workflow states and actions are loaded, the main window can be shown
                    // 5) After the skinengine triggers the first workflow state/startup screen, the default shortcuts can be registered
                    mediaAccessor.Initialize();         // Independent from other services
                    localSharesManagement.Initialize(); // After media accessor was initialized
                    skinEngine.Initialize();            // 1)
                    workflowManager.Initialize();       // 2)

#if !DEBUG
                    splashScreen.CloseSplashScreen(); // 3)
#endif

                    skinEngine.Startup();                                         // 4)
                    UiExtension.Startup();                                        // 5)

                    ApplicationCore.RegisterDefaultMediaItemAspectTypes().Wait(); // To be done after UI services are running

                    _ipcServer = new IpcServer("Client");
                    _ipcServer.CustomShutdownCallback = () =>
                    {
                        ServiceRegistration.Get <IScreenControl>().Shutdown();
                        return(true);
                    };
                    try
                    {
                        _ipcServer.Open();
                    }
                    catch (Exception ipcEx)
                    {
                        logger.Error(ipcEx);
                    }
                    systemStateService.SwitchSystemState(SystemState.Running, true);

                    if (mpOptions.AutoStart)
                    {
                        StartFocusKeeper();
                    }

                    Application.Run();
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true; // Block ServiceRegistration from trying to load new services in shutdown phase

                    // 1) Stop UI extensions (Releases all active players, must be done before shutting down SE)
                    // 2) Shutdown SkinEngine (Closes all screens, uninstalls background manager, stops render thread)
                    // 3) Shutdown WorkflowManager (Disposes all models)
                    // 4) Shutdown ImporterWorker
                    // 5) Shutdown PluginManager (Shuts down all plugins)
                    // 6) Remove all services
                    UiExtension.StopUiServices();
                    skinEngine.Shutdown();
                    workflowManager.Shutdown();
                    ServiceRegistration.Get <IImporterWorker>().Shutdown();
                    pluginManager.Shutdown();
                    mediaAccessor.Shutdown();
                    localSharesManagement.Shutdown();
                    ApplicationCore.StopCoreServices();
                }
                catch (Exception e)
                {
                    logger.Critical("Error executing application", e);
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;
                }
                finally
                {
                    if (_ipcServer != null)
                    {
                        _ipcServer.Close();
                    }
                    UiExtension.DisposeUiServices();
                    ApplicationCore.DisposeCoreServices();

                    systemStateService.SwitchSystemState(SystemState.Ending, false);
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ConsoleLogger log = new ConsoleLogger(LogLevel.All, false);
                log.Error(ex);
#else
                UiCrashLogger crash = new UiCrashLogger(logPath);
                crash.CreateLog(ex);
#endif
                systemStateService.SwitchSystemState(SystemState.Ending, false);

                // Release mutex for single instance
                if (_mutex != null)
                {
                    _mutex.ReleaseMutex();
                }

                Application.Exit();
            }
        }
Example #27
0
        public void GetUserApplicationEmptyIdentifier()
        {
            var core = new ApplicationCore();

            core.Get(new Application());
        }
Example #28
0
        public void Start()
        {
            Thread.CurrentThread.Name = "Main";

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Team MediaPortal\MP2-Server\Log");
#endif

            _systemStateService = new SystemStateService();
            ServiceRegistration.Set <ISystemStateService>(_systemStateService);
            _systemStateService.SwitchSystemState(SystemState.Initializing, false);

            try
            {
                ILogger logger = null;
                try
                {
                    // Check if user wants to override the default Application Data location.
                    ApplicationCore.RegisterVitalCoreServices(_dataDirectory);
                    ApplicationCore.RegisterCoreServices();
                    logger = ServiceRegistration.Get <ILogger>();

#if !DEBUG
                    IPathManager pathManager = ServiceRegistration.Get <IPathManager>();
                    logPath = pathManager.GetPath("<LOG>");
#endif

                    BackendExtension.RegisterBackendServices();
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.Critical("Error starting application", e);
                    }
                    _systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;

                    BackendExtension.DisposeBackendServices();
                    ApplicationCore.DisposeCoreServices();

                    throw;
                }

                // Start the core
                logger.Debug("ApplicationLauncher: Starting core");

                try
                {
                    var mediaAccessor = ServiceRegistration.Get <IMediaAccessor>();
                    var pluginManager = ServiceRegistration.Get <IPluginManager>();
                    pluginManager.Initialize();
                    pluginManager.Startup(false);
                    ApplicationCore.StartCoreServices();

                    BackendExtension.StartupBackendServices();
                    ApplicationCore.RegisterDefaultMediaItemAspectTypes(); // To be done after backend services are running

                    mediaAccessor.Initialize();

                    _systemStateService.SwitchSystemState(SystemState.Running, true);
                    BackendExtension.ActivateImporterWorker();
                    // To be done after default media item aspect types are present and when the system is running (other plugins might also install media item aspect types)
                }
                catch (Exception e)
                {
                    logger.Critical("Error starting application", e);
                    _systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;
                    BackendExtension.DisposeBackendServices();
                    ApplicationCore.DisposeCoreServices();
                    _systemStateService.SwitchSystemState(SystemState.Ending, false);
                    throw; // needed to cancel OnStart of the Service
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ConsoleLogger log = new ConsoleLogger(LogLevel.All, false);
                log.Error(ex);
#else
                ServerCrashLogger crash = new ServerCrashLogger(logPath);
                crash.CreateLog(ex);
#endif
                _systemStateService.SwitchSystemState(SystemState.Ending, false);
                throw; // needed to cancel OnStart of the Service
            }
        }
Example #29
0
        public void GetApplicationInformationNullUser()
        {
            var core = new ApplicationCore();

            core.Get(null, Guid.NewGuid());
        }
Example #30
0
 public void ProcessPollResults(List <ModuleObjectValue> objectValues)
 {
     DbService.WriteValuesToDb(objectValues);
     ApplicationCore.GetInstance().GetLogger().LogInfo($"Закончен опрос {GetSerial()}");
 }
Example #31
0
        public void GetApplicationInformationEmptyUserId()
        {
            var core = new ApplicationCore();

            core.Get(new User(), Guid.NewGuid());
        }
Example #32
0
        static void Main(params string[] args)
        {
            System.Threading.Thread.CurrentThread.Name = "Manager";
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Parse Command Line options
            CommandLineOptions mpArgs = new CommandLineOptions();

            try
            {
                CommandLine.Parse(args, mpArgs);
            }
            catch (ArgumentException)
            {
                mpArgs.DisplayOptions();
                return;
            }

            using (new ServiceScope(true)) //This is the first servicescope
            {
                ApplicationCore.RegisterCoreServices();

                IPathManager pathManager = ServiceScope.Get <IPathManager>();
                // Check if user wants to override the default Application Data location.
                if (mpArgs.IsOption(CommandLineOptions.Option.Data))
                {
                    pathManager.ReplacePath("DATA", (string)mpArgs.GetOption(CommandLineOptions.Option.Data));
                }

                //Check whether the user wants to log method names in the logger
                //This adds an extra 10 to 40 milliseconds to the log call, depending on the length of the stack trace
                bool     logMethods = mpArgs.IsOption(CommandLineOptions.Option.LogMethods);
                LogLevel level      = LogLevel.All;
                if (mpArgs.IsOption(CommandLineOptions.Option.LogLevel))
                {
                    level = (LogLevel)mpArgs.GetOption(CommandLineOptions.Option.LogLevel);
                }
                ILogger logger = ServiceScope.Get <ILogger>();
                logger.Level          = level;
                logger.LogMethodNames = logMethods;

                logger.Debug("Manager: Registering Strings Manager");
                ServiceScope.Add <ILocalisation>(new StringManager());

#if !DEBUG
                // Not in Debug mode (ie Release) then catch all Exceptions
                // In Debug mode these will be left unhandled.
                try
                {
#endif
                // Start the system
                logger.Debug("ApplicationLauncher: Starting MediaPortal manager");

                IPluginManager pluginManager = ServiceScope.Get <IPluginManager>();
                pluginManager.Initialize();
                pluginManager.Startup(true);
                Application.Run(new MainWindow());
                pluginManager.Shutdown();

#if !DEBUG
            }
            catch (Exception ex)
            {
                CrashLogger crash = new CrashLogger(pathManager.GetPath("<LOG>"));
                crash.CreateLog(ex);
                //Form frm =
                //  new YesNoDialogScreen("MediaPortal 2", "Unrecoverable Error",
                //                        "MediaPortal has encountered an unrecoverable error\r\nDetails have been logged\r\n\r\nRestart?",
                //                        BaseScreen.Image.bug);
                //restart = frm.ShowDialog() == DialogResult.Yes;
            }
#endif
            }
        }
Example #33
0
 public SettingsController(IContainer c, Model m, ApplicationCore ac)
 {
     container = c;
     model = m;
     core = ac;
 }