Example #1
0
        public PGView()
        {
            InitializeComponent();

            if (DesignerProperties.IsInDesignTool)
            {
                return;
            }

            StartupMode mode = PhoneApplicationService.Current.StartupMode;

            Debug.WriteLine("StartupMode mode =" + mode.ToString());

            if (mode == StartupMode.Activate)
            {
                PhoneApplicationService service = PhoneApplicationService.Current;
                service.Activated   += new EventHandler <Microsoft.Phone.Shell.ActivatedEventArgs>(AppActivated);
                service.Launching   += new EventHandler <LaunchingEventArgs>(AppLaunching);
                service.Deactivated += new EventHandler <DeactivatedEventArgs>(AppDeactivated);
                service.Closing     += new EventHandler <ClosingEventArgs>(AppClosing);
            }
            else
            {
            }

            // initializes native execution logic
            this.nativeExecution = new NativeExecution(ref this.GapBrowser);
        }
        /// <summary>
        /// 判断app是否以管理员权限运行,不是的话提升权限重启app
        /// </summary>
        /// <param name="startupMode"></param>
        public static void ElvateApp(StartupMode startupMode)
        {
            if (!IsElvated())
            {
                // It is not possible to launch a ClickOnce app as administrator directly,
                // so instead we launch the app as administrator in a new process.
                var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase);

                // The following properties run the new process as administrator
                processInfo.UseShellExecute = true;
                processInfo.Verb            = "runas";
                processInfo.Arguments       = startupMode.ToString();
                // Start the new process
                try
                {
                    Process.Start(processInfo);
                }
                catch (Exception ex)
                {
                }

                // Shut down the current process
                Environment.Exit(0);
            }
        }
Example #3
0
        public CordovaView()
        {
            InitializeComponent();

            if (DesignerProperties.IsInDesignTool)
            {
                return;
            }


            StartupMode mode = PhoneApplicationService.Current.StartupMode;

            if (mode == StartupMode.Launch)
            {
                PhoneApplicationService service = PhoneApplicationService.Current;
                service.Activated   += new EventHandler <Microsoft.Phone.Shell.ActivatedEventArgs>(AppActivated);
                service.Launching   += new EventHandler <LaunchingEventArgs>(AppLaunching);
                service.Deactivated += new EventHandler <DeactivatedEventArgs>(AppDeactivated);
                service.Closing     += new EventHandler <ClosingEventArgs>(AppClosing);
            }
            else
            {
            }

            // initializes native execution logic
            this.nativeExecution = new NativeExecution(ref this.CordovaBrowser);
            this.bmHelper        = new BrowserMouseHelper(ref this.CordovaBrowser);
        }
 public override void Login(StartupMode mode = StartupMode.Login)
 {
     base.Login(mode);
     ClientInfo.Current.ModUser    = CurrentBaseApp.LoggedUser.HistoryName;
     ClientInfo.Current.ModComp    = Environment.MachineName;
     ClientInfo.Current.LanguageId = 0;
 }
        public static BrowserLaunchUri GetBrowserLaunchUri(StartupMode mode, ushort?port)
        {
            var scheme    = mode == StartupMode.Hosted ? "http" : "https";
            var portToUse = port.HasValue ? port : GetFreePort();
            var host      = mode == StartupMode.Hosted ? "*" : "localhost";

            return(new BrowserLaunchUri(scheme, host, portToUse.Value));
        }
Example #6
0
 public RunData()
 {
     Data          = new Dictionary <string, string>();
     Flags         = new List <string>();
     Exception     = null;
     ErrorMessage  = "Znenie chyby";
     Attachments   = new List <string>();
     ServisObjects = new Dictionary <string, ServisObject>();
     StartupMode   = StartupMode.COMPLEX;
 }
Example #7
0
        public async void SetStartUpMode(string lightid, StartupMode startup)
        {
            var light = await m_HueClient.GetLightAsync(lightid);

            light.Config.Startup.Mode = startup; //TODO: ungetestet!


            //var caller = new ApiCaller();
            //caller.HttpPut("lights/" + lightid, "{\"config\":{\"startup\":{\"mode\":\"" + startup.ToString().ToLower() + "\"}}}");
        }
Example #8
0
        public MainWindow(StartupMode startupMode, string[] args)
        {
            m_startupMode  = startupMode;
            m_firmwareFile = args != null && args.Length > 0 ? args[0] : null;
            m_hideToTray   = m_startupMode.HasFlag(StartupMode.Minimized) || GetAutorunState();

            InitializeComponent();
            Initialize();
            InitializeControls();
            InitializeTray();
            InitializeLanguages();
        }
Example #9
0
        private async Task LaunchWithStartupMode(IActivatedEventArgs LaunchArgs)
        {
            StartupMode Mode = StartupModeController.GetStartupMode();

            switch (Mode)
            {
            case StartupMode.CreateNewTab:
            {
                ExtendedSplash extendedSplash = new ExtendedSplash(LaunchArgs.SplashScreen);
                Window.Current.Content = extendedSplash;
                break;
            }

            case StartupMode.LastOpenedTab:
            {
                List <string[]> LastOpenedPathArray = await StartupModeController.GetAllPathAsync(Mode).ToListAsync();

                StartupModeController.Clear(StartupMode.LastOpenedTab);

                if (LastOpenedPathArray.Count == 0)
                {
                    ExtendedSplash extendedSplash = new ExtendedSplash(LaunchArgs.SplashScreen);
                    Window.Current.Content = extendedSplash;
                }
                else
                {
                    ExtendedSplash extendedSplash = new ExtendedSplash(LaunchArgs.SplashScreen, LastOpenedPathArray);
                    Window.Current.Content = extendedSplash;
                }

                break;
            }

            case StartupMode.SpecificTab:
            {
                string[] SpecificPathArray = await StartupModeController.GetAllPathAsync(Mode).Select((Item) => Item.FirstOrDefault()).OfType <string>().ToArrayAsync();

                if (SpecificPathArray.Length == 0)
                {
                    ExtendedSplash extendedSplash = new ExtendedSplash(LaunchArgs.SplashScreen);
                    Window.Current.Content = extendedSplash;
                }
                else
                {
                    ExtendedSplash extendedSplash = new ExtendedSplash(LaunchArgs.SplashScreen, SpecificPathArray);
                    Window.Current.Content = extendedSplash;
                }

                break;
            }
            }
        }
    public SetupDatabaseForm(StartupMode aStartMode)
    {
      InitializeComponent();
      _dialogMode = aStartMode;

      if (aStartMode == StartupMode.DbCleanup)
      {
        btnSave.Visible = false;
        btnDrop.Visible = true;
      }
      // A user might want to save a "wrong" database name so TV-Server creates a new DB.
      if (aStartMode == StartupMode.DbConfig)
        btnSave.Enabled = true;
    }
Example #11
0
        private async Task UpdateTransactionsLoop(StartupMode startupMode, CancellationToken token)
        {
            switch (startupMode)
            {
            case StartupMode.database:
                Logger.LogInformation("Getting stored height from databse...");
                LastHeight = GetStoredLastHeight();

                if (LastHeight == 0)
                {
                    Logger.LogInformation("No stored height, warming up from network.");
                    LastHeight = await GetNetworkCurrentLastHeight();
                }

                break;

            case StartupMode.network:
                Logger.LogInformation("Warming up, getting current top height.");
                LastHeight = await GetNetworkCurrentLastHeight();

                break;

            case StartupMode.initial:
                break;
            }

            Logger.LogInformation("Begin polling from {0}", LastHeight);

            while (!token.IsCancellationRequested)
            {
                Logger.LogDebug("Updating from height: {0}", LastHeight);

                var transactions = await GetTransactions(LastHeight);

                if (transactions != null && transactions.Count > 0)
                {
                    Logger.LogInformation("Got {0} new transactions, processing", transactions.Count);
                    ProcessNewTransactions(transactions);
                    LastHeight = GetLastHeight(transactions);
                    Logger.LogInformation("New lastHeight: {0}", LastHeight);
                    StoreLastHeight();
                }
                else
                {
                    Logger.LogDebug("Got 0, delay.");
                }

                await Task.Delay(Delay);
            }
        }
Example #12
0
        public void StartPolling(StartupMode startupMode)
        {
            if (IsWorking)
            {
                return;
            }

            IsWorking = true;

            Logger.LogInformation("Start polling");

            _tokenSource = new CancellationTokenSource();
            PollingTask  = UpdateTransactionsLoop(startupMode, _tokenSource.Token);
        }
        public bool TestConnection(StartupMode ModeType)
        {
            try
            {
                if (ModeType != StartupMode.DeployMode)
                {
                    LoadConnectionDetailsFromConfig(true);
                }

                if (string.IsNullOrEmpty(tbServerHostName.Text) || string.IsNullOrEmpty(tbPassword.Text))
                {
                    return(false);
                }

                string connectionString = ComposeConnectionString(tbServerHostName.Text, tbUserID.Text, tbPassword.Text, "",
                                                                  false, 15);

                switch (provider)
                {
                case ProviderType.SqlServer:
                    using (SqlConnection connect = new SqlConnection(connectionString))
                    {
                        connect.Open();
                        connect.Close();
                    }
                    break;

                case ProviderType.MySql:
                    using (MySqlConnection connect = new MySqlConnection(connectionString))
                    {
                        connect.Open();
                        connect.Close();
                    }
                    break;

                default:
                    throw (new Exception("Unsupported provider!"));
                }
            }
            catch (Exception)
            {
                return(false);
            }

            SqlConnection.ClearAllPools();

            //database server is found
            return(true);
        }
Example #14
0
        public CordovaView()
        {
            InitializeComponent();

            if (DesignerProperties.IsInDesignTool)
            {
                return;
            }


            StartupMode mode = PhoneApplicationService.Current.StartupMode;

            if (mode == StartupMode.Launch)
            {
                PhoneApplicationService service = PhoneApplicationService.Current;
                service.Activated   += new EventHandler <Microsoft.Phone.Shell.ActivatedEventArgs>(AppActivated);
                service.Launching   += new EventHandler <LaunchingEventArgs>(AppLaunching);
                service.Deactivated += new EventHandler <DeactivatedEventArgs>(AppDeactivated);
                service.Closing     += new EventHandler <ClosingEventArgs>(AppClosing);
            }
            else
            {
            }

            configHandler = new ConfigHandler();
            configHandler.LoadAppPackageConfig();

            if (configHandler.ContentSrc != null)
            {
                if (Uri.IsWellFormedUriString(configHandler.ContentSrc, UriKind.Absolute))
                {
                    this.StartPageUri = new Uri(configHandler.ContentSrc, UriKind.Absolute);
                }
                else
                {
                    this.StartPageUri = new Uri(AppRoot + "www/" + configHandler.ContentSrc, UriKind.Relative);
                }
            }

            ApplyConfigurationPreferences();

            browserDecorators = new Dictionary <string, IBrowserDecorator>();

            // initializes native execution logic
            nativeExecution = new NativeExecution(ref this.CordovaBrowser);
            bmHelper        = new BrowserMouseHelper(ref this.CordovaBrowser);

            CreateDecorators();
        }
        public SetupDatabaseForm(StartupMode aStartMode)
        {
            InitializeComponent();
            _dialogMode = aStartMode;

            if (aStartMode == StartupMode.DbCleanup)
            {
                btnSave.Visible = false;
                btnDrop.Visible = true;
            }
            // A user might want to save a "wrong" database name so TV-Server creates a new DB.
            if (aStartMode == StartupMode.DbConfig)
            {
                btnSave.Enabled = true;
            }
        }
Example #16
0
        public static string StartupModeToString(StartupMode value)
        {
            switch (value)
            {
            case StartupMode.Auto:
                return("Automatic");

            case StartupMode.Manual:
                return("Manual");

            case StartupMode.Disabled:
                return("Disabled");

            default:
                return("Disabled");
            }
        }
        private static ServiceStartMode GetStartMode(StartupMode mode)
        {
            switch (mode)
            {
            case StartupMode.Automatic:
                return(ServiceStartMode.Automatic);

            case StartupMode.Manual:
                return(ServiceStartMode.Manual);

            case StartupMode.Disabled:
                return(ServiceStartMode.Disabled);

            default:
                throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
            }
        }
Example #18
0
        /// <summary>
        ///   according to the startup mode style return the style
        /// </summary>
        /// <returns> </returns>
        internal static int GetWindowStateByStartupModeStyle(StartupMode startupMode)
        {
            int style = 0;

            if (startupMode == StartupMode.Default)
            {
            }
            else if (startupMode == StartupMode.Maximize)
            {
                style = Styles.WINDOW_STATE_MAXIMIZE;
            }
            else if (startupMode == StartupMode.Minimize)
            {
                style = Styles.WINDOW_STATE_MINIMIZE;
            }

            return(style);
        }
 public ExportPluginAttribute(
     string name,
     StartupMode mode   = StartupMode.Auto,
     string author      = "Ensage",
     string version     = "1.0.0.0",
     string description = "",
     int priority       = 500,
     params HeroId[] units)
     : base(typeof(IPluginLoader))
 {
     this.Name        = name;
     this.Mode        = mode;
     this.Author      = author;
     this.Version     = version;
     this.Description = description;
     this.Priority    = priority;
     this.Units       = units?.Length > 0 ? units : null;
 }
            /// <summary>
            /// 以高权限执行某些任务
            /// </summary>
            /// <param name="startupMode"></param>
            public static void RunElvatedTask(StartupMode startupMode)
            {
                // It is not possible to launch a ClickOnce app as administrator directly,
                // so instead we launch the app as administrator in a new process.
                var processInfo = new ProcessStartInfo(Process.GetCurrentProcess().MainModule.FileName);

                // The following properties run the new process as administrator
                processInfo.UseShellExecute = true;
                processInfo.Verb            = "runas";
                processInfo.Arguments       = startupMode.ToString();
                // Start the new process
                try
                {
                    Process.Start(processInfo);
                }
                catch
                {
                }
            }
 public static void SetLaunchMode(StartupMode Mode)
 {
     lock (Locker)
     {
         if (ApplicationData.Current.LocalSettings.Values["StartupMode"] is string ExistMode)
         {
             if (Enum.Parse <StartupMode>(ExistMode) != Mode)
             {
                 ApplicationData.Current.LocalSettings.Values["StartupMode"] = Enum.GetName(typeof(StartupMode), Mode);
                 ApplicationData.Current.SignalDataChanged();
             }
         }
         else
         {
             ApplicationData.Current.LocalSettings.Values["StartupMode"] = Enum.GetName(typeof(StartupMode), Mode);
             ApplicationData.Current.SignalDataChanged();
         }
     }
 }
Example #22
0
        public YBWebView()
        {
            InitializeComponent();

            StartupMode mode = PhoneApplicationService.Current.StartupMode;

            if (mode == StartupMode.Launch)
            {
                PhoneApplicationService service = PhoneApplicationService.Current;
                service.Activated   += new EventHandler <Microsoft.Phone.Shell.ActivatedEventArgs>(AppActivated);
                service.Launching   += new EventHandler <LaunchingEventArgs>(AppLaunching);
                service.Deactivated += new EventHandler <DeactivatedEventArgs>(AppDeactivated);
                service.Closing     += new EventHandler <ClosingEventArgs>(AppClosing);
            }
            else
            {
            }

            // initializes native execution logic
            this.nativeExecution = new NativeExecution(ref this.YebobBrowser);
        }
        /// <summary>
        /// Sets the Update Rate (1, 5 or 10Hz) of the GPS
        /// </summary>
        public void SetStartType(StartupMode mode)
        {
            byte[] b;

            switch (mode)
            {
                case StartupMode.Hot:
                    b = UTF8Encoding.UTF8.GetBytes(START_HOT);
                    break;
                case StartupMode.Warm:
                    b = UTF8Encoding.UTF8.GetBytes(START_WARM);
                    break;
                case StartupMode.FactoryReset:
                    b = UTF8Encoding.UTF8.GetBytes(START_FACTORY_RESET);
                    break;
                default:    // 1HZ
                    b = UTF8Encoding.UTF8.GetBytes(START_COLD);
                    break;
            }

            outputDataWriter.WriteBytes(b);
        }
Example #24
0
 public static bool SetServiceStartupMode(string serviceName, StartupMode startupMode, out string errorRepresent)
 {
     errorRepresent = "";
     if (!SeparatedProcess && (ForceElevate || !UacHelper.IsProcessElevated))
     {
         var result = Program.RunElevated(serviceName, out errorRepresent, startupMode);
         FlushCash();
         return(result);
     }
     if (!ServiceExist(serviceName))
     {
         return(false);
     }
     try
     {
         var parameters = new object[1];
         parameters[0] = StartupModeToString(startupMode);
         var result = (uint)GetCashedServiceManagmentObject(serviceName).InvokeMethod("ChangeStartMode", parameters);
         FlushCash();
         return(result == 0);
     }
     catch (Exception e) { errorRepresent = e.Message; FlushCash(); return(false); }
 }
Example #25
0
        /// <summary>
        /// Executes troubleshooter and passess serialised run data to this.
        /// Functional troubleshooter must be located in tsLocation directory otherwise exception is thrown
        /// </summary>
        /// <param name="tsLocation">the relative location of troubleshooter</param>
        public int RunTroubleShooter(string tsLocation, StartupMode mode)
        {
            RunData.StartupMode = mode;
            // if executable was not found, throw an exception.
            if (!File.Exists(Path.Combine(tsLocation, EXE_FILE)))
            {
                throw new FileNotFoundException($"Troubleshooter was not found at location specified: {tsLocation}.");
            }
            string serialisedData = JsonConvert.SerializeObject(RunData);

            File.WriteAllText(Path.Combine(tsLocation, INPUT_FILE_NAME), serialisedData);
            RunData.ClearFlags();
            //tu si hod breakpoint ak si chces debugovat troubleshooter so vstupnymi datami
            ProcessStartInfo _processStartInfo = new ProcessStartInfo();

            //set working directory so it can find important files like runData, patches, patchAssembly etc.
            _processStartInfo.WorkingDirectory = Path.Combine(Environment.CurrentDirectory, tsLocation);
            _processStartInfo.FileName         = EXE_FILE;
            _processStartInfo.Arguments        = INPUT_FILE_NAME;
            Process myProcess = Process.Start(_processStartInfo);

            myProcess.WaitForExit();
            return(myProcess.ExitCode);
        }
        public void If_port_is_not_specified_a_free_port_is_returned(StartupMode mode)
        {
            var uri = WebHostBuilderExtensions.GetBrowserLaunchUri(mode, null);

            CheckIfPortIsAvailable(uri.Port).Should().BeTrue();
        }
        public void If_a_port_it_specified_it_is_used(StartupMode mode)
        {
            var uri = WebHostBuilderExtensions.GetBrowserLaunchUri(mode, 6000);

            uri.Port.Should().Be(6000);
        }
Example #28
0
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
            Microsoft.Toolkit.Uwp.Helpers.SystemInformation.Instance.TrackAppUse(e);

            ApplicationViewTitleBar TitleBar = ApplicationView.GetForCurrentView().TitleBar;

            TitleBar.ButtonBackgroundColor         = Colors.Transparent;
            TitleBar.ButtonInactiveBackgroundColor = Colors.Transparent;

            CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;

            if (Window.Current.Content is Frame frame)
            {
                if (frame.Content is MainPage Main && Main.Nav.Content is TabViewContainer TabContainer)
                {
                    if (!string.IsNullOrWhiteSpace(e.Arguments) && await FileSystemStorageItemBase.CheckExistAsync(e.Arguments))
                    {
                        await TabContainer.CreateNewTabAsync(e.Arguments);
                    }
                    else
                    {
                        await TabContainer.CreateNewTabAsync();
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(e.Arguments) && await FileSystemStorageItemBase.CheckExistAsync(e.Arguments))
                {
                    ExtendedSplash extendedSplash = new ExtendedSplash(e.SplashScreen, new List <string[]> {
                        new string[] { e.Arguments }
                    });
                    Window.Current.Content = extendedSplash;
                }
                else
                {
                    StartupMode Mode = StartupModeController.GetStartupMode();

                    switch (Mode)
                    {
                    case StartupMode.CreateNewTab:
                    {
                        ExtendedSplash extendedSplash = new ExtendedSplash(e.SplashScreen);
                        Window.Current.Content = extendedSplash;
                        break;
                    }

                    case StartupMode.LastOpenedTab:
                    {
                        List <string[]> LastOpenedPathArray = await StartupModeController.GetAllPathAsync(Mode).ToListAsync();

                        StartupModeController.Clear(StartupMode.LastOpenedTab);

                        if (LastOpenedPathArray.Count == 0)
                        {
                            ExtendedSplash extendedSplash = new ExtendedSplash(e.SplashScreen);
                            Window.Current.Content = extendedSplash;
                        }
                        else
                        {
                            ExtendedSplash extendedSplash = new ExtendedSplash(e.SplashScreen, LastOpenedPathArray);
                            Window.Current.Content = extendedSplash;
                        }

                        break;
                    }

                    case StartupMode.SpecificTab:
                    {
                        string[] SpecificPathArray = await StartupModeController.GetAllPathAsync(Mode).Select((Item) => Item.FirstOrDefault()).OfType <string>().ToArrayAsync();

                        if (SpecificPathArray.Length == 0)
                        {
                            ExtendedSplash extendedSplash = new ExtendedSplash(e.SplashScreen);
                            Window.Current.Content = extendedSplash;
                        }
                        else
                        {
                            ExtendedSplash extendedSplash = new ExtendedSplash(e.SplashScreen, SpecificPathArray);
                            Window.Current.Content = extendedSplash;
                        }

                        break;
                    }
                    }
                }
            }

            Window.Current.Activate();
        }
 private static ServiceStartMode GetStartMode(StartupMode mode)
 {
     switch (mode)
     {
         case StartupMode.Automatic:
             return ServiceStartMode.Automatic;
         case StartupMode.Manual:
             return ServiceStartMode.Manual;
         case StartupMode.Disabled:
             return ServiceStartMode.Disabled;
         default:
             throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
     }
 }
Example #30
0
 /// <summary>
 /// Set the startup coordinates (top left) for most dialoges.  This should be set before the dialog is called.
 /// </summary>
 /// <param name="x">The X coordinate.</param>
 /// <param name="y">The X coordinate.</param>
 /// <param name="mode">The mode which is one of the following
 /// 0 : Off (default)
 /// 1 : The coordinates are relative to the graphics window, equivalent to GraphicsWindow.MouseX/Y.
 /// 2 : The coordinates are relative to the display window, equivalent to Desktop.MouseX/Y</param>
 public static void SetStartupPosition(Primitive x, Primitive y, Primitive mode)
 {
     eStartupMode = (StartupMode)(int)mode;
     xPosInput = x;
     yPosInput = y;
 }
        private string GetActionDescription()
        {
#if (DEBUG)
            return(ConfigurationState + "\r\n" + GetXMLAction());
#endif
            switch (ServiceAction)
            {
            case Actions.ChangeStartingMode:
                return("Change the Starting mode of : " + txtBxServiceName.Text);

            case Actions.Start:
                return("Start service : " + txtBxServiceName.Text);

            case Actions.Stop:
                return("Stop service : " + txtBxServiceName.Text);

            case Actions.Register:
                return("Register service : " + txtBxServiceName.Text + " from EXE : " + txtBxPathToEXE.Text + " with Starting Mode : " + StartupMode.ToString());

            case Actions.Unregister:
                return("Unregister service : " + txtBxServiceName.Text);

            default:
                return(Description);
            }
        }
Example #32
0
 /// <summary>
 /// 
 /// </summary>
 public Startup()
 {
   startupMode = StartupMode.Normal;
 }
Example #33
0
 /// <summary>
 ///
 /// </summary>
 public Startup()
 {
     startupMode = StartupMode.Normal;
 }
    public bool TestConnection(StartupMode ModeType)
    {
      try
      {
        if (ModeType != StartupMode.DeployMode)
        {
          LoadConnectionDetailsFromConfig(true);
        }

        if (string.IsNullOrEmpty(tbServerHostName.Text) || string.IsNullOrEmpty(tbPassword.Text))
          return false;

        string connectionString = ComposeConnectionString(tbServerHostName.Text, tbUserID.Text, tbPassword.Text, "",
                                                          false, 15);

        switch (provider)
        {
          case ProviderType.SqlServer:
            using (SqlConnection connect = new SqlConnection(connectionString))
            {
              connect.Open();
              connect.Close();
            }
            break;
          case ProviderType.MySql:
            using (MySqlConnection connect = new MySqlConnection(connectionString))
            {
              connect.Open();
              connect.Close();
            }
            break;
          default:
            throw (new Exception("Unsupported provider!"));
        }
      }
      catch (Exception)
      {
        return false;
      }

      SqlConnection.ClearAllPools();

      //database server is found
      return true;
    }
 /// <summary>
 /// Gets the current MySQL server version
 /// </summary>
 /// <returns>the current MySQL server version</returns>
 public string GetCurrentServerVersion(StartupMode ModeType)
 {
   string currentServerVersion = "";
   if (ModeType != StartupMode.DeployMode)
   {
     LoadConnectionDetailsFromConfig(false);
   }
   try
   {
     string connectionString = ComposeConnectionString(tbServerHostName.Text, tbUserID.Text, tbPassword.Text,
                                                       tbDatabaseName.Text, false, 15);
     switch (provider)
     {
       case ProviderType.MySql:
         {
           using (MySqlConnection connect = new MySqlConnection(connectionString))
           {
             connect.Open();
             currentServerVersion = connect.ServerVersion;
             connect.Close();
           }
         }
         break;
     }
     return currentServerVersion;
   }
   catch (Exception)
   {
     return "";
   }
   finally
   {
     SqlConnection.ClearAllPools();
   }
 }
    /// <summary>
    /// Gets the current schema version (-1= No database installed)
    /// </summary>
    /// <returns>the current schema version</returns>
    public int GetCurrentShemaVersion(StartupMode ModeType)
    {
      int currentSchemaVersion = -1;
      if (ModeType != StartupMode.DeployMode)
      {
        LoadConnectionDetailsFromConfig(false);
      }
      try
      {
        string connectionString = ComposeConnectionString(tbServerHostName.Text, tbUserID.Text, tbPassword.Text,
                                                          tbDatabaseName.Text, false, 15);
        switch (provider)
        {
          case ProviderType.SqlServer:
            {
              using (SqlConnection connect = new SqlConnection(connectionString))
              {
                connect.Open();
                using (SqlCommand cmd = connect.CreateCommand())
                {
                  cmd.CommandType = CommandType.Text;
                  cmd.CommandText = "select * from Version";
                  using (IDataReader reader = cmd.ExecuteReader())
                  {
                    if (reader != null)
                      if (reader.Read())
                      {
                        currentSchemaVersion = (int)reader["versionNumber"];
                        reader.Close();
                        connect.Close();
                      }
                  }
                }
              }
            }
            break;

          case ProviderType.MySql:
            {
              using (MySqlConnection connect = new MySqlConnection(connectionString))
              {
                connect.Open();
                using (MySqlCommand cmd = connect.CreateCommand())
                {
                  cmd.CommandType = CommandType.Text;
                  cmd.CommandText = "select * from Version";
                  using (IDataReader reader = cmd.ExecuteReader())
                  {
                    if (reader.Read())
                    {
                      currentSchemaVersion = (int)reader["versionNumber"];
                      reader.Close();
                      connect.Close();
                    }
                  }
                }
              }
            }
            break;
        }
        return currentSchemaVersion;
      }
      catch (Exception)
      {
        return -1;
      }
      finally
      {
        SqlConnection.ClearAllPools();
      }
    }
 /// <inheritdoc/>
 /// <param name="startupMode">Configure when the ASP.NET Core framework will be initialized</param>
 protected APIGatewayHttpApiV2ProxyFunction(StartupMode startupMode)
     : base(startupMode)
 {
 }
Example #38
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 ----");
      // Get MySQL server version
      string currentServerVersion = dlg.GetCurrentServerVersion(startupMode);
      if (!dlg.UpgradeDBSchema(currentSchemaVersion, currentServerVersion))
      {
        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);
      }
    }