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 ScanSettings());
                AddSection(new TvRecording());
                AddSection(new TvTimeshifting());
                AddSection(new TvSchedules());
                AddSection(new StreamingServer());

                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();
        }
        public void CheckServiceName()
        {
            // only query service names of local machine
            if (!IsDatabaseOnLocalMachine(ParseServerHostName(tbServerHostName.Text)))
            {
                tbServiceDependency.Enabled = false;
                return;
            }
            tbServiceDependency.Enabled = true;

            // first try the quick method and assume the user is right or using defaults
            string ConfiguredServiceName = tbServiceDependency.Text;
            string DBSearchPattern       = @"MySQL";
            Color  clAllOkay             = Color.GreenYellow;

            if (ServiceHelper.IsInstalled(ConfiguredServiceName))
            {
                tbServiceDependency.BackColor = clAllOkay;
                DBSearchPattern = ConfiguredServiceName;
            }
            else
            {
                // MSSQL
                if (rbSQLServer.Checked)
                {
                    DBSearchPattern = @"SQLBrowser";
                }

                if (ServiceHelper.GetDBServiceName(ref DBSearchPattern))
                {
                    tbServiceDependency.Text      = DBSearchPattern;
                    tbServiceDependency.BackColor = clAllOkay;
                }
                else
                {
                    Log.Info("SetupDatabaseForm: DB service name not recognized - using defaults");
                    tbServiceDependency.BackColor = Color.Red;
                }
            }

            // if a matching service name is available - add it now
            if (tbServiceDependency.BackColor == clAllOkay && tbServiceDependency.Enabled)
            {
                if (ServiceHelper.AddDependencyByName(DBSearchPattern))
                {
                    Log.Info("SetupDatabaseForm: Added dependency for TvService - {0}", DBSearchPattern);
                    if (!ServiceHelper.IsServiceEnabled(DBSearchPattern, false))
                    {
                        if (MessageBox.Show(this,
                                            string.Format(
                                                "The tv service depends on {0} but this service does not autostart - enable now?",
                                                DBSearchPattern),
                                            "Dependency avoids autostart",
                                            MessageBoxButtons.YesNo,
                                            MessageBoxIcon.Warning,
                                            MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                        {
                            // enable the dependency now
                            if (!ServiceHelper.IsServiceEnabled(DBSearchPattern, true))
                            {
                                MessageBox.Show("Failed to change the startup behaviour", "Dependency error", MessageBoxButtons.OK,
                                                MessageBoxIcon.Error);
                            }
                        }
                        // start the service right now
                        if (!ServiceHelper.Start(DBSearchPattern))
                        {
                            MessageBox.Show(string.Format("Failed to start the dependency service: {0}", DBSearchPattern),
                                            "Dependency start error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    Log.Info("SetupDatabaseForm: Could not add dependency for TvService - {0}", DBSearchPattern);
                }
            }
        }
Beispiel #3
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);

            Log.Info("---- SetupTv v" + versionInfo.FileVersion + " is starting up on " + OSInfo.OSInfo.GetOSDisplayVersion());

            //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;
                }
            }

            // 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
            TvBusinessLayer layer = new TvBusinessLayer();
            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);
            }
        }