public bool Connect(string hostname)
 {
     try
     {
         string connStr;
         string provider;
         if (!GetDatabaseConnectionString(out connStr, out provider))
         {
             return(false);
         }
         RemoteControl.HostName = hostname;
         Gentle.Framework.ProviderFactory.SetDefaultProviderConnectionString(connStr);
         me          = new User();
         me.IsAdmin  = true;
         groups      = ChannelGroup.ListAll();
         radioGroups = RadioChannelGroup.ListAll();
         channels    = Channel.ListAll();
         mappings    = GroupMap.ListAll();
         cards       = Card.ListAll();
     }
     catch (Exception ex)
     {
         lastException = ex;
         RemoteControl.Clear();
         return(false);
     }
     return(true);
 }
예제 #2
0
        private void InitializeGentleAndTVE()
        {
            try
            {
                // read Gentle configuration from CommonAppData
                string gentleConfigFile = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                    "Team MediaPortal", "MediaPortal TV Server", "Gentle.config"
                    );

                if (!File.Exists(gentleConfigFile))
                {
                    throw new FileNotFoundException("The Gentle configuration file couldn't be found. This occurs when TV Server is not installed.", gentleConfigFile);
                }

                Gentle.Common.Configurator.AddFileHandler(gentleConfigFile);

                // connect to tv server via TVE API
                RemoteControl.Clear();
                RemoteControl.HostName = TvDatabase.Server.ListAll().First(server => server.IsMaster).HostName;

                _tvControl = RemoteControl.Instance;
            }
            catch (Exception ex)
            {
                Log.Error("Failed to connect to TVEngine", ex);
            }
        }
예제 #3
0
        private void InitializeGentleAndTVE()
        {
            _tveInstalled = true;

            try
            {
                // Use the same Gentle.config as the TVEngine
                string gentleConfigFile = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                    "Team MediaPortal", "MediaPortal TV Server", "Gentle.config"
                    );

                // but be quiet when it doesn't exists, as not everyone has the TV Engine installed
                if (!File.Exists(gentleConfigFile))
                {
                    Log.Info("Cannot find Gentle.config file, assuming TVEngine isn't installed...");
                    _tveInstalled = false;
                    return;
                }

                Gentle.Common.Configurator.AddFileHandler(gentleConfigFile);

                // connect to tv server via TVE API
                RemoteControl.Clear();
                RemoteControl.HostName = "127.0.0.1"; // Why do we have to even bother with this setting?

                _tvControl = RemoteControl.Instance;
            }
            catch (Exception ex)
            {
                Log.Error("Failed to connect to TVEngine", ex);
            }
        }
예제 #4
0
        public void OnStop()
        {
            if (!Started)
            {
                return;
            }
            Log.WriteFile("TV Service: stopping");

            if (_InitializedEvent != null)
            {
                _InitializedEvent.Reset();
            }
            StopRemoting();
            RemoteControl.Clear();
            if (_controller != null)
            {
                _controller.DeInit();
                _controller = null;
            }

            StopPlugins();
            if (_powerEventThreadId != 0)
            {
                Log.Debug("TV Service: OnStop asking PowerEventThread to exit");
                PostThreadMessage(_powerEventThreadId, WM_QUIT, IntPtr.Zero, IntPtr.Zero);
                _powerEventThread.Join();
            }
            _powerEventThreadId = 0;
            _powerEventThread   = null;
            _started            = false;
            Log.WriteFile("TV Service: stopped");
        }
예제 #5
0
        private bool CheckTvServerConnection(List <string> portErrors)
        {
            bool succeeded = true;

            if (!CheckTcpPort(31456)) // TvService.RemoteControl
            {
                portErrors.Add("31456 (TCP) RemoteControl");
                succeeded = false;
            }

            if (succeeded)
            {
                try
                {
                    int cards = RemoteControl.Instance.Cards;
                    // Need to setup the database connection string here
                    // before checking for database connectivity,
                    // otherwhise we will check for the wrong database provider
                    TVHome.Navigator.SetupDatabaseConnection();
                }
                catch (Exception)
                {
                    RemoteControl.Clear();
                    succeeded = false;
                }
            }
            return(succeeded);
        }
예제 #6
0
 protected override void OnPageDestroy(int new_windowId)
 {
     SaveSettings();
     RemoteControl.Clear();
     RemoteControl.HostName = _hostName;
     base.OnPageDestroy(new_windowId);
 }
예제 #7
0
    protected void idTest_Click(object sender, EventArgs e)
    {
        try
        {
            tableResult.Visible = true;
            RemoteControl.Clear();
            RemoteControl.HostName = idTvserver.Text;
            int cards = RemoteControl.Instance.Cards;
            textBoxResult.Text = "Connected to tvserver";

            try
            {
                string connectionString, provider;
                RemoteControl.Instance.GetDatabaseConnectionString(out connectionString, out provider);
                Gentle.Framework.ProviderFactory.ResetGentle(true);
                Gentle.Framework.ProviderFactory.SetDefaultProviderConnectionString(connectionString);
                textBoxDatabaseResult.Text = "Connected to SQL server";
                idSave.Visible             = true;
            }
            catch (Exception ex)
            {
                textBoxDatabaseResult.Text = "Unable to connect to SQL server" + ex.ToString();
            }
        }
        catch (Exception ex)
        {
            textBoxResult.Text = "Unable to connect to tv server " + ex.ToString();
        }
    }
예제 #8
0
        private void buttonRestart_Click(object sender, EventArgs e)
        {
            try
            {
                buttonRestart.Enabled = false;
                timer1.Enabled        = false;

                RemoteControl.Clear();
                if (ServiceHelper.IsStopped)
                {
                    if (ServiceHelper.Start())
                    {
                        ServiceHelper.WaitInitialized();
                    }
                }
                else if (ServiceHelper.IsRunning)
                {
                    if (ServiceHelper.Stop())
                    {
                    }
                }
                RemoteControl.Clear();
                timer1.Enabled = true;
            }
            finally
            {
                buttonRestart.Enabled = true;
            }
        }
예제 #9
0
 /// <summary>
 /// Starts the remoting interface
 /// </summary>
 private void StartRemoting()
 {
     try
     {
         // create the object reference and make the singleton instance available
         RemotingServices.Marshal(_controller, "TvControl", typeof(IController));
         RemoteControl.Clear();
     }
     catch (Exception ex)
     {
         Log.Write(ex);
     }
 }
예제 #10
0
        void UpdateTvServer()
        {
            IList servers = TvDatabase.Server.ListAll();

            foreach (TvDatabase.Server server in servers)
            {
                if (!server.IsMaster)
                {
                    continue;
                }
                RemoteControl.Clear();
                RemoteControl.HostName = server.HostName;
                return;
            }
        }
예제 #11
0
        /// <summary>
        /// Wait until TvService is fully initialized
        /// </summary>
        /// <param name="millisecondsTimeout">the maximum time to wait in milliseconds</param>
        /// <remarks>If <paramref name="millisecondsTimeout"/> is 0, the current status is immediately returned.
        /// Use <paramref name="millisecondsTimeout"/>=-1 to wait indefinitely</remarks>
        /// <returns>true if thTvService is initialized</returns>
        public static bool WaitInitialized(int millisecondsTimeout)
        {
            try
            {
                EventWaitHandle initialized = EventWaitHandle.OpenExisting(RemoteControl.InitializedEventName,
                                                                           EventWaitHandleRights.Synchronize);
                return(initialized.WaitOne(millisecondsTimeout));
            }
            catch (Exception ex) // either we have no right, or the event does not exist
            {
                Log.Error("Failed to wait for {0}", RemoteControl.InitializedEventName);
                Log.Write(ex);
            }
            // Fall back: try to call a method on the server (for earlier versions of TvService)
            DateTime expires = millisecondsTimeout == -1
                           ? DateTime.MaxValue
                           : DateTime.Now.AddMilliseconds(millisecondsTimeout);

            // Note if millisecondsTimeout = 0, we never enter the loop and always return false
            // There is no way to determine if TvService is initialized without waiting
            while (DateTime.Now < expires)
            {
                try
                {
                    RemoteControl.Clear();
                    int cards = RemoteControl.Instance.Cards;
                    return(true);
                }
                catch (System.Runtime.Remoting.RemotingException)
                {
                    Log.Info("ServiceHelper: Waiting for tvserver to initialize. (remoting not initialized)");
                }
                catch (System.Net.Sockets.SocketException)
                {
                    Log.Info("ServiceHelper: Waiting for tvserver to initialize. (socket not initialized)");
                }
                catch (Exception ex)
                {
                    Log.Error(
                        "ServiceHelper: Could not check whether the tvservice is running. Please check your network as well. \nError: {0}",
                        ex.ToString());
                    break;
                }
                Thread.Sleep(250);
            }
            return(false);
        }
예제 #12
0
        protected override void OnPageLoad()
        {
            if (!TVHome.Connected)
            {
                RemoteControl.Clear();
                GUIWindowManager.ActivateWindow((int)Window.WINDOW_SETTINGS_TVENGINE);
                return;
            }

            TVHome.WaitForGentleConnection();

            if (TVHome.Navigator == null)
            {
                TVHome.OnLoaded();
            }
            else if (TVHome.Navigator.Channel == null)
            {
                TVHome.m_navigator.ReLoad();
                TVHome.LoadSettings(false);
            }

            if (TVHome.m_navigator == null)
            {
                TVHome.m_navigator = new ChannelNavigator(); // Create the channel navigator (it will load groups and channels)
            }

            base.OnPageLoad();
            if (btnPriorities != null)
            {
                btnPriorities.Visible = false;
            }
            //@      ConflictManager.OnConflictsUpdated += new MediaPortal.TV.Recording.ConflictManager.OnConflictsUpdatedHandler(ConflictManager_OnConflictsUpdated);

            LoadSettings();
            needUpdate   = false;
            selectedItem = null;
            LoadDirectory();

            while (m_iSelectedItem >= GetItemCount() && m_iSelectedItem > 0)
            {
                m_iSelectedItem--;
            }
            GUIControl.SelectItemControl(GetID, listSchedules.GetID, m_iSelectedItem);

            btnSortBy.SortChanged += new SortEventHandler(SortChanged);
        }
예제 #13
0
 public override bool DeInit()
 {
     RemoteControl.Clear();
     lock (_recordingSync)
     {
         if (_checkForRecordingTimer != null)
         {
             _checkForRecordingTimer.Dispose();
         }
         _checkForRecordingTimer = null;
         if (_allCards != null)
         {
             _allCards.Clear();
         }
         _allCards = null;
         _currentlyRecording.Clear();
         _currentlyRecording = null;
     }
     return(true);
 }
예제 #14
0
        public void OnStop()
        {
            if (!_started)
            {
                return;
            }

            Log.WriteFile("TV Service: stopping");

            // Reset "Global\MPTVServiceInitializedEvent"
            if (_InitializedEvent != null)
            {
                _InitializedEvent.Reset();
            }

            // Stop the plugins
            StopPlugins();

            // Stop remoting and deinit the TvController
            StopRemoting();
            RemoteControl.Clear();
            if (_controller != null)
            {
                _controller.DeInit();
                _controller = null;
            }

            // Terminate the power event thread
            if (_powerEventThreadId != 0)
            {
                Log.Debug("TV Service: OnStop asking PowerEventThread to exit");
                PostThreadMessage(_powerEventThreadId, WM_QUIT, IntPtr.Zero, IntPtr.Zero);
                _powerEventThread.Join();
            }
            _powerEventThreadId = 0;
            _powerEventThread   = null;

            _started = false;
            Log.WriteFile("TV Service: stopped");
        }
 public void ResetConnection()
 {
     RemoteControl.Clear();
     _isTimeShifting = false;
 }
예제 #16
0
        private void Init()
        {
            CheckForIllegalCrossThreadCalls = false;
            //
            // Set caption
            //
            Text = "MediaPortal - TV Server Configuration";

            //
            // Build options tree
            //
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(String.Format(@"{0}\gentle.config", PathManager.GetDataPath));
                XmlNode nodeKey      = doc.SelectSingleNode("/Gentle.Framework/DefaultProvider");
                XmlNode node         = nodeKey.Attributes.GetNamedItem("connectionString");
                XmlNode nodeProvider = nodeKey.Attributes.GetNamedItem("name");

                Gentle.Framework.ProviderFactory.ResetGentle(true);
                Gentle.Framework.GentleSettings.DefaultProviderName = nodeProvider.InnerText;
                Gentle.Framework.ProviderFactory.GetDefaultProvider();
                Gentle.Framework.ProviderFactory.SetDefaultProviderConnectionString(node.InnerText);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to open:" + String.Format(@"{0}\gentle.config", PathManager.GetDataPath));
                Log.Write(ex);
            }

            try
            {
                Server.ListAll();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to open database");
                Log.Error("Unable to get list of servers");
                Log.Write(ex);
            }

            Project project = new Project();

            AddSection(project);

            layer   = new TvBusinessLayer();
            servers = new Servers();
            AddSection(servers);
            IList <Server> dbsServers = Server.ListAll();

            if (dbsServers != null)
            {
                foreach (Server server in dbsServers)
                {
                    if (server.IsMaster)
                    {
                        bool connected = false;
                        while (!connected)
                        {
                            RemoteControl.HostName = server.HostName;

                            if (server.ReferringCard().Count > 0)
                            {
                                try
                                {
                                    Card c = (Card)server.ReferringCard()[0];
                                    RemoteControl.Instance.Type(c.IdCard);
                                    connected = true;
                                }
                                catch (Exception ex)
                                {
                                    string localHostname = Dns.GetHostName();
                                    if (localHostname != server.HostName)
                                    {
                                        DialogResult dlg = MessageBox.Show(String.Format("Unable to connect to <{0}>.\n" +
                                                                                         "Do you want to try the current comupter name ({1}) instead?",
                                                                                         server.HostName, localHostname),
                                                                           "Wrong config detected",
                                                                           MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                                        if (dlg == DialogResult.Yes)
                                        {
                                            Log.Info("Controller: server {0} changed to {1}", server.HostName, localHostname);
                                            server.HostName = localHostname;
                                            server.Persist();
                                            RemoteControl.Clear();
                                            ServiceHelper.Restart();
                                            ServiceHelper.WaitInitialized();
                                        }
                                        else
                                        {
                                            MessageBox.Show("Setup will now close");
                                            Environment.Exit(-1);
                                        }
                                    }
                                    else
                                    {
                                        Log.Error("Cannot connect to server {0}", server.HostName);
                                        Log.Write(ex);
                                        DialogResult dlg = MessageBox.Show("Unable to connect to <" + server.HostName + ">.\n" +
                                                                           "Please check the TV Server logs for details.\n\n" +
                                                                           "Setup will now close.");
                                        Environment.Exit(-1);
                                    }
                                }
                            }
                        }
                        break;
                    }
                }

                AddServerTvCards(servers, dbsServers, false);

                TvChannels tvChannels = new TvChannels();
                AddSection(tvChannels);
                AddChildSection(tvChannels, new TvCombinations("TV Combinations"));
                AddChildSection(tvChannels, new TvChannelMapping());

                RadioChannels radioChannels = new RadioChannels();
                AddSection(radioChannels);
                AddChildSection(radioChannels, new RadioCombinations("Radio Combinations"));
                AddChildSection(radioChannels, new RadioChannelMapping());

                Epg EpgSection = new Epg();
                AddSection(EpgSection);
                AddChildSection(EpgSection, new TvEpgGrabber());
                AddChildSection(EpgSection, new RadioEpgGrabber());

                AddSection(new EpgGenreMap());
                AddSection(new ScanSettings());
                AddSection(new TvRecording());
                AddSection(new TvTimeshifting());
                AddSection(new TvSchedules());
                AddSection(new StreamingServer());
                AddSection(new UserPriorities());

                AddSection(new TestService("Manual Control"));
                AddSection(new TestChannels("Test Channels"));

                _pluginLoader.Load();
                pluginsRoot = new Plugins("Plugins", _pluginLoader);
                AddSection(pluginsRoot);

                pluginsRoot.ChangedActivePlugins += SectChanged;

                foreach (ITvServerPlugin plugin in _pluginLoader.Plugins)
                {
                    SectionSettings settings = plugin.Setup;
                    if (settings != null)
                    {
                        Setting isActive = layer.GetSetting(String.Format("plugin{0}", plugin.Name), "false");
                        settings.Text = plugin.Name;
                        if (isActive.Value == "true")
                        {
                            AddChildSection(pluginsRoot, settings);
                        }
                    }
                }
                if (showAdvancedSettings)
                {
                    AddSection(new DebugOptions());
                }
                AddSection(new ImportExport());
                AddSection(new ThirdPartyChecks());

                sectionTree.SelectedNode = sectionTree.Nodes[0];
                // make sure window is in front of mediaportal
            }
            BringToFront();
        }
예제 #17
0
        protected override void OnPageLoad()
        {
            Log.Info("RadioHome:OnPageLoad");

            if (!TVHome.Connected)
            {
                RemoteControl.Clear();
                GUIWindowManager.ActivateWindow((int)Window.WINDOW_SETTINGS_TVENGINE);
                return;
            }

            if (TVHome.Navigator == null)
            {
                TVHome.OnLoaded();
            }
            else if (TVHome.Navigator.Channel == null)
            {
                TVHome.m_navigator.ReLoad();
                TVHome.LoadSettings(false);
            }

            // Create the channel navigator (it will load groups and channels)
            if (TVHome.m_navigator == null)
            {
                TVHome.m_navigator = new ChannelNavigator();
            }

            // Reload ChannelGroups
            Radio radioLoad = (Radio)GUIWindowManager.GetWindow((int)Window.WINDOW_RADIO);

            radioLoad.OnAdded();

            base.OnPageLoad();
            GUIMessage msgStopRecorder = new GUIMessage(GUIMessage.MessageType.GUI_MSG_RECORDER_STOP, 0, 0, 0, 0, 0, null);

            GUIWindowManager.SendMessage(msgStopRecorder);
            switch (currentSortMethod)
            {
            case SortMethod.Name:
                btnSortBy.SelectedItem = 0;
                break;

            case SortMethod.Type:
                btnSortBy.SelectedItem = 1;
                break;

            case SortMethod.Genre:
                btnSortBy.SelectedItem = 2;
                break;

            case SortMethod.Bitrate:
                btnSortBy.SelectedItem = 3;
                break;

            case SortMethod.Number:
                btnSortBy.SelectedItem = 4;
                break;
            }

            SelectCurrentItem();
            LoadDirectory(currentFolder);

            SetLastChannel();

            if ((_autoTurnOnRadio) && !(g_Player.Playing && g_Player.IsRadio))
            {
                GUIListItem item = facadeLayout.SelectedListItem;
                if (item != null && item.Label != ".." && !item.IsFolder)
                {
                    Play(facadeLayout.SelectedListItem);
                }
            }

            btnSortBy.SortChanged += SortChanged;
        }
예제 #18
0
        protected override void OnClicked(int controlId, GUIControl control, Action.ActionType actionType)
        {
            if (control == btnChange)
            {
                if (GetKeyboard(ref _hostName))
                {
                    RemoteControl.Clear();
                    RemoteControl.HostName = _hostName;
                    if (lblHostName != null)
                    {
                        lblHostName.Label = _hostName;
                    }
                    GUIPropertyManager.SetProperty("#TV.setup.hostname", _hostName);

                    CheckTvServiceStatus();

                    List <string> portErrors  = new List <string>();
                    bool          tvServerOk  = CheckTvServerConnection(portErrors);
                    bool          databaseOk  = CheckDatabaseConnection(portErrors);
                    bool          streamingOk = CheckStreamingConnection(tvServerOk, databaseOk, portErrors);

                    //Show the check results dialog to the user
                    GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK);
                    if (tvServerOk && databaseOk && streamingOk)
                    {
                        //TVHome.OnPageLoadDone = false;
                        RemoteControl.UseIncreasedTimeoutForInitialConnection = true;

                        TVHome.Navigator.ReLoad();
                        Settings xmlreader = new MPSettings();
                        TVHome.Navigator.LoadSettings(xmlreader);
                        if (pDlgOK != null)
                        {
                            pDlgOK.SetHeading(GUILocalizeStrings.Get(605));
                            pDlgOK.SetLine(1, GUILocalizeStrings.Get(200064)); // Connected to TvServer
                            pDlgOK.SetLine(2, "");
                            pDlgOK.SetLine(3, "");
                            pDlgOK.DoModal(GUIWindowManager.ActiveWindow);
                        }
                        //goto TV home, even directly fullscreen if configured this way.
                        GUIWindowManager.ActivateWindow((int)Window.WINDOW_TV, true);

                        return;
                    }
                    RemoteControl.Clear();
                    pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK);
                    if (pDlgOK != null)
                    {
                        if (portErrors.Count > 0)
                        {
                            pDlgOK.SetHeading(GUILocalizeStrings.Get(200065)); // Some ports seem to be blocked
                            for (int i = 0; i < 4; i++)
                            {
                                if (i < portErrors.Count)
                                {
                                    pDlgOK.SetLine(i + 1, portErrors[i]);
                                }
                                else
                                {
                                    pDlgOK.SetLine(i + 1, "");
                                }
                            }
                            pDlgOK.DoModal(GUIWindowManager.ActiveWindow);
                        }
                        pDlgOK.SetHeading(GUILocalizeStrings.Get(605));
                        if (tvServerOk)
                        {
                            pDlgOK.SetLine(1, GUILocalizeStrings.Get(200064)); // Connected to TvServer
                        }
                        else
                        {
                            pDlgOK.SetLine(1, GUILocalizeStrings.Get(200066)); // Unable to connect to TvServer
                        }

                        if (databaseOk)
                        {
                            pDlgOK.SetLine(2, GUILocalizeStrings.Get(200067)); // Connected to database
                        }
                        else
                        {
                            pDlgOK.SetLine(2, GUILocalizeStrings.Get(200068)); // Unable to connect to database
                        }
                        if (portErrors.Count == 0)
                        {
                            pDlgOK.SetLine(3, GUILocalizeStrings.Get(200069)); // All ip ports seem to be fine
                        }
                        else
                        {
                            pDlgOK.SetLine(3, GUILocalizeStrings.Get(200070)); // Please check firewall
                        }
                        pDlgOK.DoModal(GUIWindowManager.ActiveWindow);

                        return;
                    }
                }
            }
            else if (control == btnBack)
            {
                SwitchToHomeView();
            }
            base.OnClicked(controlId, control, actionType);
        }
예제 #19
0
        public static void Main(string[] arguments)
        {
            // Init Common logger -> this will enable TVPlugin to write in the Mediaportal.log file
            var loggerName = Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]);
            var dataPath   = Log.GetPathName();
            var loggerPath = Path.Combine(dataPath, "log");

#if DEBUG
            if (loggerName != null)
            {
                loggerName = loggerName.Replace(".vshost", "");
            }
#endif
            CommonLogger.Instance = new CommonLog4NetLogger(loggerName, dataPath, loggerPath);


            Thread.CurrentThread.Name = "SetupTv";

            Process[] p = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
            if (p.Length > 1)
            {
                System.Environment.Exit(0);
            }

            string DeploySql = string.Empty;
            string DeployPwd = string.Empty;

            foreach (string param in arguments)
            {
                switch (param.ToLowerInvariant())
                {
                case "/delete-db":
                    startupMode = StartupMode.DbCleanup;
                    break;

                case "/configure-db":
                    startupMode = StartupMode.DbConfig;
                    break;

                case "/debugoptions":
                    debugOptions = true;
                    break;
                }

                if (param.StartsWith("--Deploy"))
                {
                    switch (param.Substring(0, 12))
                    {
                    case "--DeployMode":
                        Log.Debug("---- started in Deploy mode ----");
                        startupMode = StartupMode.DeployMode;
                        break;

                    case "--DeploySql:":
                        DeploySql = param.Split(':')[1].ToLower();
                        break;

                    case "--DeployPwd:":
                        DeployPwd = param.Split(':')[1];
                        break;
                    }
                }
            }

            Application.SetCompatibleTextRenderingDefault(false);

            // set working dir from application.exe
            string applicationPath = Application.ExecutablePath;
            applicationPath = System.IO.Path.GetFullPath(applicationPath);
            applicationPath = System.IO.Path.GetDirectoryName(applicationPath);
            System.IO.Directory.SetCurrentDirectory(applicationPath);

            FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(Application.ExecutablePath);

            try
            {
                Log.Info("---- SetupTv v" + versionInfo.FileVersion + " is starting up on " + OSInfo.OSInfo.GetOSDisplayVersion());
            } catch (Exception)
            {
                Log.Info("---- SetupTv v" + versionInfo.FileVersion + " is starting up on Windows 10 Pro for Workstations (???)");
            }
            Log.Info(OSInfo.OSInfo.GetLastInstalledWindowsUpdateTimestampAsString());
            Log.Info("Windows Media Player: [{0}]", OSInfo.OSInfo.GetWMPVersion());

            //Check for unsupported operating systems
            OSPrerequisites.OSPrerequisites.OsCheck(true);

            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            appSettings.Set("GentleConfigFile", String.Format(@"{0}\gentle.config", PathManager.GetDataPath));

            Application.ThreadException += Application_ThreadException;

            //test connection with database
            Log.Info("---- check connection with database ----");
            SetupDatabaseForm dlg = new SetupDatabaseForm(startupMode);

            if (startupMode == StartupMode.DeployMode)
            {
                if (DeploySql == "dbalreadyinstalled")
                {
                    Log.Info("---- ask user for connection details ----");
                    if (dlg.ShowDialog() != DialogResult.OK || startupMode != StartupMode.DeployMode)
                    {
                        return; // close the application without restart here.
                    }
                    dlg.CheckServiceName();
                    if (startupMode == StartupMode.DeployMode)
                    {
                        dlg.SaveGentleConfig();
                    }
                }
                else if (String.IsNullOrEmpty(DeploySql) || String.IsNullOrEmpty(DeployPwd))
                {
                    dlg.LoadConnectionDetailsFromConfig(true);
                }
                else
                {
                    if (DeploySql == "mysql")
                    {
                        dlg.provider                 = SetupDatabaseForm.ProviderType.MySql;
                        dlg.rbMySQL.Checked          = true;
                        dlg.tbUserID.Text            = "root";
                        dlg.tbServerHostName.Text    = Dns.GetHostName();
                        dlg.tbServiceDependency.Text = @"MySQL5";
                    }
                    else
                    {
                        dlg.provider                 = SetupDatabaseForm.ProviderType.SqlServer;
                        dlg.rbSQLServer.Checked      = true;
                        dlg.tbUserID.Text            = "sa";
                        dlg.tbServerHostName.Text    = Dns.GetHostName() + @"\SQLEXPRESS";
                        dlg.tbServiceDependency.Text = @"SQLBrowser";
                    }
                    dlg.tbPassword.Text     = DeployPwd;
                    dlg.tbDatabaseName.Text = dlg.schemaNameDefault;
                    dlg.schemaName          = dlg.schemaNameDefault;
                }
            }

            if (dlg.tbServerHostName.Text.Trim().ToLower() == "localhost" | dlg.tbServerHostName.Text.Trim() == "127.0.0.1")
            {
                Log.Info("*****************************************************************");
                Log.Info("* WARNING, connection host ({0}) not officially supported *", dlg.tbServerHostName.Text);
                Log.Info("*****************************************************************");
            }

            if ((startupMode != StartupMode.Normal && startupMode != StartupMode.DeployMode) ||
                (!dlg.TestConnection(startupMode)))
            {
                Log.Info("---- ask user for connection details ----");
                if (dlg.ShowDialog() != DialogResult.OK || startupMode != StartupMode.DeployMode)
                {
                    return; // close the application without restart here.
                }
            }
            dlg.CheckServiceName();
            if (startupMode == StartupMode.DeployMode)
            {
                dlg.SaveGentleConfig();
            }

            Log.Info("---- check if database needs to be updated/created ----");
            int currentSchemaVersion = dlg.GetCurrentShemaVersion(startupMode);
            if (currentSchemaVersion <= 36) // drop pre-1.0 DBs and handle -1
            {
                // Allow users to cancel DB recreation to backup their old DB
                if (currentSchemaVersion > 0)
                {
                    if (
                        MessageBox.Show(
                            "Your existing database cannot be upgraded and will be replaced by an empty database. Continue now?",
                            "DB recreation needed", MessageBoxButtons.OKCancel, MessageBoxIcon.Question,
                            MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
                    {
                        return;
                    }
                }

                Log.Info("---- create database ----");
                if (!dlg.ExecuteSQLScript("create"))
                {
                    MessageBox.Show("Failed to create the database.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Log.Info("- Database created.");
                currentSchemaVersion = dlg.GetCurrentShemaVersion(startupMode);
            }

            Log.Info("---- upgrade database schema ----");
            if (!dlg.UpgradeDBSchema(currentSchemaVersion))
            {
                MessageBox.Show("Failed to upgrade the database.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Log.Info("---- check if tvservice is running ----");
            if (!ServiceHelper.IsRunning)
            {
                Log.Info("---- tvservice is not running ----");
                if (startupMode != StartupMode.DeployMode)
                {
                    DialogResult result = MessageBox.Show("The Tv service is not running.\rStart it now?",
                                                          "Mediaportal TV service", MessageBoxButtons.YesNo);
                    if (result != DialogResult.Yes)
                    {
                        return;
                    }
                }
                Log.Info("---- start tvservice----");
                ServiceHelper.Start();
            }

            ServiceHelper.WaitInitialized();
            int cards = 0;
            try
            {
                cards = RemoteControl.Instance.Cards;
            }
            catch (Exception)
            {
                Log.Info("---- restart tvservice----");
                ServiceHelper.Restart();
                ServiceHelper.WaitInitialized();
                try
                {
                    RemoteControl.Clear();
                    RemoteControl.HostName = Dns.GetHostName();
                    cards = RemoteControl.Instance.Cards;
                }
                catch (Exception ex)
                {
                    Log.Info("---- Unable to restart tv service----");
                    Log.Write(ex);
                    MessageBox.Show("Failed to startup tvservice" + ex);
                    return;
                }
            }

            var layer = new TvBusinessLayer();
            layer.SetLogLevel();

            // Mantis #0001991: disable mpg recording  (part I: force TS recording format)
            IList <Card> TvCards = Card.ListAll();
            foreach (Card card in TvCards)
            {
                if (card.RecordingFormat != 0)
                {
                    card.RecordingFormat = 0;
                    Log.Info("Card {0} switched from .MPG to .TS format", card.Name);
                    card.Persist();
                }
            }

            // Mantis #0002138: impossible to configure TVGroups
            layer.CreateGroup(TvConstants.TvGroupNames.AllChannels);

            // Avoid the visual part of SetupTv if in DeployMode
            if (startupMode == StartupMode.DeployMode)
            {
                return;
            }

            try
            {
                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
                Application.EnableVisualStyles();
                Application.DoEvents();

                new Startup().Start();
            }
            catch (Exception ex)
            {
                Log.Write(ex);
            }
        }