<commit_before>﻿// ReSharper disable HeuristicUnreachableCode
// ReSharper disable CSharpWarnings::CS0162

using System.Net;

namespace SIM.Tool
{
  using System;
  using System.ComponentModel;
  using System.Diagnostics;
  using System.IO;
  using System.Linq;
  using System.Reflection;
  using System.Security.Principal;
  using System.ServiceProcess;
  using System.Windows;
  using System.Xml;
  using SIM.Adapters.SqlServer;
  using SIM.Core;
  using SIM.Core.Common;
  using SIM.Instances;
  using SIM.Pipelines;
  using SIM.Pipelines.Processors;
  using SIM.Tool.Base;
  using SIM.Tool.Base.Profiles;
  using SIM.Tool.Windows;
  using Sitecore.Diagnostics.Base;
  using JetBrains.Annotations;
  using log4net.Core;
  using log4net.Layout;
  using log4net.Util;
  using Sitecore.Diagnostics.Logging;
  using SIM.Core.Logging;
  using SIM.Extensions;
  using SIM.Tool.Base.Wizards;
  using File = System.IO.File;
  using SIM.IO.Real;
  using SIM.Tool.Windows.Pipelines.Setup;

  public partial class App
  {
    #region Fields

    private static string AppLogsMessage { get; } = $"The application will be suspended, look at the {ApplicationManager.LogsFolder} log file to find out what has happened";

    private static IO.IFileSystem FileSystem { get; } = new RealFileSystem();

    #endregion

    #region Properties

    #endregion

    #region Methods

    #region Public methods

    public static string GetLicensePath()
    {
      return Path.Combine(ApplicationManager.DataFolder, "license.xml");
    }

    public static string GetRepositoryPath()
    {
      var path = Path.Combine(ApplicationManager.DataFolder, "Repository");
      SIM.FileSystem.FileSystem.Local.Directory.Ensure(path);
      return path;
    }

    #endregion

    #region Protected methods

    protected override void OnStartup([CanBeNull] StartupEventArgs e)
    {
      InitializeLogging();

      base.OnStartup(e);

      if (!EnsureSingleProcess(e.Args))
      {
        Log.Info("Shutting down as there is another process running");

        Environment.Exit(0);

        return;
      }

      // invoke auto-updater if not developing or debugging
      if (!ApplicationManager.IsDev && !ApplicationManager.IsDebugging)
      {
        try
        {
          Log.Info("Running update procedure");

          var prefix = ApplicationManager.IsQa ? "qa/" : "";
          var suffix = ApplicationManager.IsQa ? ".QA" : "";
          CoreApp.RunApp("rundll32.exe", $"dfshim.dll,ShOpenVerbApplication http://dl.sitecore.net/updater/{prefix}sim/SIM.Tool{suffix}.application");
        }
        catch (Exception ex)
        {
          Log.Error(ex, "Error connecting to SIM auto-updater.");
        }
      }

      if (CoreApp.HasBeenUpdated)
      {
        var ver = ApplicationManager.AppVersion;
        if (!string.IsNullOrEmpty(ver))
        {
          var exists = false;
          var wc = new WebClient();
          var url = $"https://github.com/Sitecore/Sitecore-Instance-Manager/releases/tag/{ver}";
          try
          {
            wc.DownloadString(url);
            exists = true;
          }
          catch
          {
            Log.Warn($"Tag was not found: {url}");
          }

          if (exists)
          {
            Log.Info("Showing release notes");

            CoreApp.OpenInBrowser(url, true);
          }
        }
      }
      
      if (CoreApp.IsVeryFirstRun || CoreApp.HasBeenUpdated)
      {
        Log.Info("Cleaning up caches after update");

        CacheManager.ClearAll();
        foreach (var dir in Directory.GetDirectories(ApplicationManager.TempFolder))
        {
          try
          {
            Directory.Delete(dir, true);
          }
          catch (Exception ex)
          {
            WindowHelper.HandleError($"Failed to delete directory1: {dir}", isError: true, ex: ex);
          }
        }

        Log.Info("Unpacking resources");

        var ext = ".deploy.txt";
        foreach (var filePath in Directory.GetFiles(".", $"*{ext}", SearchOption.AllDirectories))
        {
          if (filePath == null)
          {
            continue;
          }

          var newFilePath = filePath.Substring(0, filePath.Length - ext.Length);
          if (File.Exists(newFilePath))
          {
            try
            {
              File.Delete(newFilePath);
            }
            catch (Exception ex)
            {
              throw new InvalidOperationException($"Failed to delete file: {newFilePath}", ex);
            }            
          }

          File.Move(filePath, newFilePath);
        }
      }

      // write it here as all preceding logic is finished
      CoreApp.WriteLastRunVersion();

      if (!CheckPermissions())
      {
        Log.Info("Shutting down due to missing permissions (it is normally okay as it will be re-run with elevated permissions)");

        Environment.Exit(0);

        return;
      }

      CoreApp.LogMainInfo();

      if (!CheckIis())
      {
        WindowHelper.ShowMessage("Cannot connect to IIS. Make sure it is installed and running.", MessageBoxButton.OK, MessageBoxImage.Exclamation);

        Environment.Exit(0);

        return;
      }

      // Initializing pipelines from Pipelines.config and WizardPipelines.config files
      if (!InitializePipelines())
      {
        Environment.Exit(0);

        return;
      }

      // Application is closing when it doesn't have any window instance therefore it's 
      // required to create MainWindow before creating the initial configuration dialog
      var main = CreateMainWindow();
      if (main == null)
      {
        Environment.Exit(0);

        return;
      }
<commit_msg>Improve app start procedure<commit_after>﻿// ReSharper disable HeuristicUnreachableCode
// ReSharper disable CSharpWarnings::CS0162

using System.Net;

namespace SIM.Tool
{
  using System;
  using System.ComponentModel;
  using System.Diagnostics;
  using System.IO;
  using System.Linq;
  using System.Reflection;
  using System.Security.Principal;
  using System.ServiceProcess;
  using System.Threading;
  using System.Windows;
  using System.Xml;
  using SIM.Adapters.SqlServer;
  using SIM.Core;
  using SIM.Core.Common;
  using SIM.Instances;
  using SIM.Pipelines;
  using SIM.Pipelines.Processors;
  using SIM.Tool.Base;
  using SIM.Tool.Base.Profiles;
  using SIM.Tool.Windows;
  using Sitecore.Diagnostics.Base;
  using JetBrains.Annotations;
  using log4net.Core;
  using log4net.Layout;
  using log4net.Util;
  using Sitecore.Diagnostics.Logging;
  using SIM.Core.Logging;
  using SIM.Extensions;
  using SIM.Tool.Base.Wizards;
  using File = System.IO.File;
  using SIM.IO.Real;
  using SIM.Tool.Windows.Pipelines.Setup;

  public partial class App
  {
    #region Fields

    private static string AppLogsMessage { get; } = $"The application will be suspended, look at the {ApplicationManager.LogsFolder} log file to find out what has happened";

    private static IO.IFileSystem FileSystem { get; } = new RealFileSystem();

    #endregion

    #region Properties

    #endregion

    #region Methods

    #region Public methods

    public static string GetLicensePath()
    {
      return Path.Combine(ApplicationManager.DataFolder, "license.xml");
    }

    public static string GetRepositoryPath()
    {
      var path = Path.Combine(ApplicationManager.DataFolder, "Repository");
      SIM.FileSystem.FileSystem.Local.Directory.Ensure(path);
      return path;
    }

    #endregion

    #region Protected methods

    protected override void OnStartup([CanBeNull] StartupEventArgs e)
    {
      InitializeLogging();

      base.OnStartup(e);

      if (!CheckPermissions())
      {
        Log.Info("Shutting down due to missing permissions (it is normally okay as it will be re-run with elevated permissions)");

        Environment.Exit(0);

        return;
      }

      if (!EnsureSingleProcess(e.Args))
      {
        Log.Info("Shutting down as there is another process running");

        Environment.Exit(0);

        return;
      }

      // invoke auto-updater if not developing or debugging
      if (!ApplicationManager.IsDev && !ApplicationManager.IsDebugging)
      {
        try
        {
          Log.Info("Running update procedure");

          var prefix = ApplicationManager.IsQa ? "qa/" : "";
          var suffix = ApplicationManager.IsQa ? ".QA" : "";
          CoreApp.RunApp("rundll32.exe", $"dfshim.dll,ShOpenVerbApplication http://dl.sitecore.net/updater/{prefix}sim/SIM.Tool{suffix}.application");
        }
        catch (Exception ex)
        {
          Log.Error(ex, "Error connecting to SIM auto-updater.");
        }
      }

      if (CoreApp.HasBeenUpdated)
      {
        var ver = ApplicationManager.AppVersion;
        if (!string.IsNullOrEmpty(ver))
        {
          var exists = false;
          var wc = new WebClient();
          var url = $"https://github.com/Sitecore/Sitecore-Instance-Manager/releases/tag/{ver}";
          try
          {
            wc.DownloadString(url);
            exists = true;
          }
          catch
          {
            Log.Warn($"Tag was not found: {url}");
          }

          if (exists)
          {
            Log.Info("Showing release notes");

            CoreApp.OpenInBrowser(url, true);
          }
        }
      }
      
      if (CoreApp.IsVeryFirstRun || CoreApp.HasBeenUpdated)
      {
        Log.Info("Cleaning up caches after update");

        CacheManager.ClearAll();
        foreach (var dir in Directory.GetDirectories(ApplicationManager.TempFolder))
        {
          try
          {
            Directory.Delete(dir, true);
          }
          catch (Exception ex)
          {
            WindowHelper.HandleError($"Failed to delete directory1: {dir}", isError: true, ex: ex);
          }
        }

        Log.Info("Unpacking resources");

        var ext = ".deploy.txt";
        foreach (var filePath in Directory.GetFiles(".", $"*{ext}", SearchOption.AllDirectories))
        {
          if (filePath == null)
          {
            continue;
          }

          var newFilePath = filePath.Substring(0, filePath.Length - ext.Length);
          if (File.Exists(newFilePath))
          {
            try
            {
              File.Delete(newFilePath);
            }
            catch (Exception ex)
            {
              throw new InvalidOperationException($"Failed to delete file: {newFilePath}", ex);
            }            
          }

          File.Move(filePath, newFilePath);
        }
      }

      // write it here as all preceding logic is finished
      CoreApp.WriteLastRunVersion();

      CoreApp.LogMainInfo();

      if (!CheckIis())
      {
        WindowHelper.ShowMessage("Cannot connect to IIS. Make sure it is installed and running.", MessageBoxButton.OK, MessageBoxImage.Exclamation);

        Environment.Exit(0);

        return;
      }

      // Initializing pipelines from Pipelines.config and WizardPipelines.config files
      if (!InitializePipelines())
      {
        Environment.Exit(0);

        return;
      }

      // Application is closing when it doesn't have any window instance therefore it's 
      // required to create MainWindow before creating the initial configuration dialog
      var main = CreateMainWindow();
      if (main == null)
      {
        Environment.Exit(0);

        return;
      }

{'fraction_non_alphanumeric': 0.09980671235283782, 'fraction_numerical': 0.0028114566859954314, 'mean_word_length': 2.110959278491391, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6056350', 'n_tokens_mistral': 3263, 'n_tokens_neox': 3124, 'n_words': 777}