File Resource Manager. Allows inclusion of file system operations in transactions. http://www.chinhdo.com/20080825/transactional-file-manager/
Inheritance: IFileManager
Beispiel #1
0
		/// <summary>
		/// Copies the source to the destination.
		/// </summary>
		/// <remarks>
		/// If the source is a directory, it is copied recursively.
		/// </remarks>
		/// <param name="p_tfmFileManager">The transactional file manager to use to copy the files.</param>
		/// <param name="p_strSource">The path from which to copy.</param>
		/// <param name="p_strDestination">The path to which to copy.</param>
		/// <param name="p_fncCopyCallback">A callback method that notifies the caller when a file has been copied,
		/// and provides the opportunity to cancel the copy operation.</param>
		/// <returns><c>true</c> if the copy operation wasn't cancelled; <c>false</c> otherwise.</returns>
		public static bool Copy(TxFileManager p_tfmFileManager, string p_strSource, string p_strDestination, Func<string, bool> p_fncCopyCallback)
		{
			if (File.Exists(p_strSource))
			{
				if (!Directory.Exists(Path.GetDirectoryName(p_strDestination)))
					p_tfmFileManager.CreateDirectory(Path.GetDirectoryName(p_strDestination));
				p_tfmFileManager.Copy(p_strSource, p_strDestination, true);
				if ((p_fncCopyCallback != null) && p_fncCopyCallback(p_strSource))
					return false;
			}
			else if (Directory.Exists(p_strSource))
			{
				if (!Directory.Exists(p_strDestination))
					p_tfmFileManager.CreateDirectory(p_strDestination);
				string[] strFiles = Directory.GetFiles(p_strSource);
				foreach (string strFile in strFiles)
				{
					p_tfmFileManager.Copy(strFile, Path.Combine(p_strDestination, Path.GetFileName(strFile)), true);
					if ((p_fncCopyCallback != null) && p_fncCopyCallback(strFile))
						return false;
				}
				string[] strDirectories = Directory.GetDirectories(p_strSource);
				foreach (string strDirectory in strDirectories)
					if (!Copy(strDirectory, Path.Combine(p_strDestination, Path.GetFileName(strDirectory)), p_fncCopyCallback))
						return false;
			}
			return true;
		}
		/// <summary>
		/// A simple constructor that initializes the object with its dependencies.
		/// </summary>
		/// <param name="p_gmiGameModeInfo">The environment info of the current game mode.</param>
		/// <param name="p_modMod">The mod being installed.</param>
		/// <param name="p_ilgInstallLog">The install log to use to log file installations.</param>
		/// <param name="p_pmgPluginManager">The plugin manager.</param>
		/// <param name="p_dfuDataFileUtility">The utility class to use to work with data files.</param>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
        /// <param name="p_UsesPlugins">Game using plugin or mods (True for plugins).</param>
		public ModFileUpgradeInstaller(IGameModeEnvironmentInfo p_gmiGameModeInfo, IMod p_modMod, IInstallLog p_ilgInstallLog, IPluginManager p_pmgPluginManager, IDataFileUtil p_dfuDataFileUtility, TxFileManager p_tfmFileManager, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate, bool p_UsesPlugins)
            : base(p_gmiGameModeInfo, p_modMod, p_ilgInstallLog, p_pmgPluginManager, p_dfuDataFileUtility, p_tfmFileManager, p_dlgOverwriteConfirmationDelegate, p_UsesPlugins, null)
		{
			OriginallyInstalledFiles = new Set<string>(StringComparer.OrdinalIgnoreCase);
			foreach (string strFile in InstallLog.GetInstalledModFiles(Mod))
				OriginallyInstalledFiles.Add(strFile.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar));
		}
		/// <summary>
		/// A simple constructor that initializes the object with its dependencies.
		/// </summary>
		/// <param name="p_modMod">The mod being installed.</param>
		/// <param name="p_ilgInstallLog">The install log to use to log file installations.</param>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
		public IniInstaller(IMod p_modMod, IInstallLog p_ilgInstallLog, TxFileManager p_tfmFileManager, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate)
		{
			TouchedFiles = new Set<string>(StringComparer.OrdinalIgnoreCase);
			Mod = p_modMod;
			InstallLog = p_ilgInstallLog;
			TransactionalFileManager = p_tfmFileManager;
			m_dlgOverwriteConfirmationDelegate = p_dlgOverwriteConfirmationDelegate ?? ((s, b, m) => OverwriteResult.No);
		}
 /// <summary>
 /// A simple constructor that initializes the object with its dependencies.
 /// </summary>
 /// <param name="p_gmiGameModeInfo">The environment info of the current game mode.</param>
 /// <param name="p_modMod">The mod being installed.</param>
 /// <param name="p_ilgInstallLog">The install log to use to log file installations.</param>
 /// <param name="p_pmgPluginManager">The plugin manager.</param>
 /// <param name="p_dfuDataFileUtility">The utility class to use to work with data files.</param>
 /// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
 /// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
 /// <param name="p_UsesPlugins">Whether the file is a mod or a plugin.</param>
 public ModFileInstaller(IGameModeEnvironmentInfo p_gmiGameModeInfo, IMod p_modMod, IInstallLog p_ilgInstallLog, IPluginManager p_pmgPluginManager, IDataFileUtil p_dfuDataFileUtility, TxFileManager p_tfmFileManager, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate, bool p_UsesPlugins)
 {
     GameModeInfo = p_gmiGameModeInfo;
     Mod = p_modMod;
     InstallLog = p_ilgInstallLog;
     PluginManager = p_pmgPluginManager;
     DataFileUtility = p_dfuDataFileUtility;
     TransactionalFileManager = p_tfmFileManager;
     m_dlgOverwriteConfirmationDelegate = p_dlgOverwriteConfirmationDelegate ?? ((s, b, m) => OverwriteResult.No);
     IsPlugin = p_UsesPlugins;
 }
		/// <summary>
		/// Called to perform the upgrade.
		/// </summary>
		/// <remarks>
		/// Sets up the resources required to upgrade the install log.
		/// </remarks>
		/// <param name="p_mdrManagedModRegistry">The <see cref="ModRegistry"/> that contains the list
		/// of managed mods.</param>
		/// <param name="p_strModInstallDirectory">The path of the directory where all of the mods are installed.</param>
		/// <param name="p_strLogPath">The path from which to load the install log information.</param>
		public void Upgrade(string p_strLogPath, string p_strModInstallDirectory, ModRegistry p_mdrManagedModRegistry)
		{
			Trace.WriteLine("Beginning Install Log Upgrade.");

			m_tfmFileManager = new TxFileManager();
			using (TransactionScope tsTransaction = new TransactionScope())
			{
				m_tfmFileManager.Snapshot(p_strLogPath);
				Start(p_strLogPath, p_strModInstallDirectory, p_mdrManagedModRegistry);
				tsTransaction.Complete();
				m_tfmFileManager = null;
			}
		}
        public void RenameImageAndUsages(PlantPhoto plantPhoto)
        {
            var dateString = _now.ToString("yyyy-MM-dd HH:mm:ss.fff");
              var fileManager = new TxFileManager();

              try {
            using (var conn = new SqlConnection(_settings.ConnectionString))
            using (var scope = new TransactionScope()) {
              conn.Open();

              conn.Execute(_photoUpdateQuery,
            new { OldPhotoId = plantPhoto.PhotoId, NewPhotoId = plantPhoto.PhotoId.AddTif(), NewUpdatedAt = _now });

              conn.Execute(_usageUpdateQuery,
            new { plantPhoto.PhotoId, NewPhotoId = plantPhoto.PhotoId.AddTif() });

              foreach (var imageRoot in _settings.ImageRoots)
              {
            var imagePath = plantPhoto.GetActualImagePath(imageRoot);
            var newPath = plantPhoto.GetReplacementPath(imageRoot, _settings.TargetExtension);

            if (File.Exists(imagePath)) {
              fileManager.Move(imagePath, newPath);
            }
              }

              foreach (var thumbnailRoot in _settings.ThumbnailRoots)
              {
            var thumbPath = plantPhoto.GetThumbnailPath(thumbnailRoot);
            var newPath = plantPhoto.GetReplacementPath(thumbnailRoot, _settings.TargetExtension, true);

            if (File.Exists(thumbPath)) {
              fileManager.Move(thumbPath, newPath);
            }
              }

              scope.Complete();
              var message = string.Format("{0}\t{0}{1}\t{2}", plantPhoto.PhotoId, _settings.TargetExtension, dateString);
              Logger.Info(message);
            }
              }
              catch (TransactionAbortedException trex)
              {
            Logger.Error(string.Format("{0}\t{1}", plantPhoto.PhotoId, trex.Message.Replace(Environment.NewLine, " ")));
              }
              catch (Exception exc)
              {
            Logger.Error(string.Format("{0}\t{1}", plantPhoto.PhotoId, exc.Message.Replace(Environment.NewLine, " ")));
              }
        }
Beispiel #7
0
        private static void WriteSafeFile()
        {
            try
            {
                Thread.Sleep(100);

                IFileManager fileManager = new TxFileManager();

                using (TransactionScope scope1 = new TransactionScope())
                {

                    File.Delete(TEMP);

                    FileInfo fi = new FileInfo(ORIGINAL);
                    fi.CopyTo(TEMP);

                    Console.WriteLine("Created temp");

                    File.Replace(TEMP, ORIGINAL, "monkey");

                    //fileManager.Copy(ORIGINAL,TEMP,true);

                    //Console.WriteLine("Created temp");

                    //fileManager.Delete(ORIGINAL);

                    //Console.WriteLine("Deleted original");

                    //fileManager.Move(TEMP,ORIGINAL);

                    //Console.WriteLine("Rename temop to original");

                    scope1.Complete();
                }

            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
        }
Beispiel #8
0
    /// <summary>
    ///   Called to perform the upgrade.
    /// </summary>
    /// <remarks>
    ///   Sets up the resources required to upgrade the install log, and then
    ///   call <see cref="DoUpgrade()" /> so implementers can do the upgrade.
    /// </remarks>
    /// <returns>
    ///   <lang langref="true" /> if the upgrade completed; <lang langref="false" />
    ///   if the user cancelled.
    /// </returns>
    internal bool PerformUpgrade()
    {
      FileManager = new TxFileManager();
      var booComplete = false;
      using (var tsTransaction = new TransactionScope())
      {
        FileManager.Snapshot(InstallLog.Current.InstallLogPath);

        using (ProgressWorker = new BackgroundWorkerProgressDialog(DoUpgrade))
        {
          ProgressWorker.OverallMessage = "Upgrading FOMM Files";
          if (ProgressWorker.ShowDialog() == DialogResult.OK)
          {
            booComplete = true;
            tsTransaction.Complete();
          }
        }
        FileManager = null;
      }
      return booComplete;
    }
Beispiel #9
0
		/// <summary>
		/// Registers the given mods with the registry.
		/// </summary>
		/// <param name="p_lstAddedMods">The mods that have been added and need to be registered with the manager.</param>
		protected void RegisterModFiles(IList<string> p_lstAddedMods)
		{
			OverallMessage = "Adding mod to manager...";
			ItemMessage = "Registering Mods...";
			if (p_lstAddedMods != null)
			{
				ItemProgress = 0;
				ItemProgressMaximum = p_lstAddedMods.Count;

				foreach (string strMod in p_lstAddedMods)
				{
					OverallMessage = String.Format("Adding mod: {0}", strMod);

					try
					{
						if (m_mrgModRegistry.RegisteredMods.SingleOrDefault(x => x.Filename == strMod) == null)
						{
							if (m_eifEnvironmentInfo.Settings.AddMissingInfoToMods)
								m_mrgModRegistry.RegisterMod(strMod, ModInfo);
							else
								m_mrgModRegistry.RegisterMod(strMod);
						}

						if (m_rmmReadMeManager != null)
						{
							TxFileManager tfmFileManager = new TxFileManager();
							string strModFolderPath = m_gmdGameMode.GameModeEnvironmentInfo.ModDirectory;
							if (m_rmmReadMeManager.VerifyReadMeFile(tfmFileManager, strMod))
								m_rmmReadMeManager.SaveReadMeConfig();
						}
					}
					catch (Exception ex)
					{
						OverallMessage = String.Format("Error registering this mod: {1}" + Environment.NewLine + "Error: {0} ", ex.Message, GetModDisplayName());
						ItemMessage = "Error registering mod.";
						Status = TaskStatus.Error;
						OnTaskEnded(null, null);
						return;
					}
					StepItemProgress();
				}
			}
			StepOverallProgress();
			OverallMessage = String.Format("{0} has been added", GetModDisplayName());
			ItemMessage = "Finished adding mod.";
			Status = TaskStatus.Complete;
			OnTaskEnded(null, null);
		}
		/// <summary>
		/// A simple constructor that initializes the object with its dependencies.
		/// </summary>
		/// <param name="p_gmiGameModeInfo">The environment info of the current game mode.</param>
		/// <param name="p_modMod">The mod being installed.</param>
		/// <param name="p_ilgInstallLog">The install log to use to log file installations.</param>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <param name="p_futFileUtility">The file utility class.</param>
		/// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
		public GamebryoGameSpecificValueUpgradeInstaller(IMod p_modMod, IGameModeEnvironmentInfo p_gmiGameModeInfo, IInstallLog p_ilgInstallLog, TxFileManager p_tfmFileManager, FileUtil p_futFileUtility, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate)
			:base(p_modMod, p_gmiGameModeInfo, p_ilgInstallLog, p_tfmFileManager, p_futFileUtility, p_dlgOverwriteConfirmationDelegate)
		{
			OriginallyInstalledEdits = new Set<string>();
			OriginallyInstalledEdits.AddRange(InstallLog.GetInstalledGameSpecificValueEdits(Mod));
		}
Beispiel #11
0
    /// <summary>
    ///   Runs the install script.
    /// </summary>
    /// <remarks>
    ///   This contains the boilerplate code that needs to be done for all install-type
    ///   scripts. Implementers must override the <see cref="DoScript()" /> method to
    ///   implement their script-specific functionality.
    /// </remarks>
    /// <param name="p_booSuppressSuccessMessage">
    ///   Indicates whether to
    ///   supress the success message. This is useful for batch installs.
    /// </param>
    /// <seealso cref="DoScript()" />
    protected bool Run(bool p_booSuppressSuccessMessage, bool p_booSetFOModReadOnly)
    {
      var booSuccess = false;
      if (CheckAlreadyDone())
      {
        booSuccess = true;
      }

      if (!booSuccess)
      {
        try
        {
          //the install process modifies INI and config files.
          // if multiple sources (i.e., installs) try to modify
          // these files simultaneously the outcome is not well known
          // (e.g., one install changes SETTING1 in a config file to valueA
          // while simultaneously another install changes SETTING1 in the
          // file to value2 - after each install commits its changes it is
          // not clear what the value of SETTING1 will be).
          // as a result, we only allow one mod to be installed at a time,
          // hence the lock.
          lock (objInstallLock)
          {
            using (var tsTransaction = new TransactionScope())
            {
              m_tfmFileManager = new TxFileManager();
              using (Script = CreateInstallScript())
              {
                var booCancelled = false;
                if (p_booSetFOModReadOnly && (Fomod != null))
                {
                  if (Fomod.ReadOnlyInitStepCount > 1)
                  {
                    using (m_bwdProgress = new BackgroundWorkerProgressDialog(BeginFOModReadOnlyTransaction))
                    {
                      m_bwdProgress.OverallMessage = "Preparing FOMod...";
                      m_bwdProgress.ShowItemProgress = false;
                      m_bwdProgress.OverallProgressMaximum = Fomod.ReadOnlyInitStepCount;
                      m_bwdProgress.OverallProgressStep = 1;
                      try
                      {
                        Fomod.ReadOnlyInitStepStarted += Fomod_ReadOnlyInitStepStarted;
                        Fomod.ReadOnlyInitStepFinished += Fomod_ReadOnlyInitStepFinished;
                        if (m_bwdProgress.ShowDialog() == DialogResult.Cancel)
                        {
                          booCancelled = true;
                        }
                      }
                      finally
                      {
                        Fomod.ReadOnlyInitStepStarted -= Fomod_ReadOnlyInitStepStarted;
                        Fomod.ReadOnlyInitStepFinished -= Fomod_ReadOnlyInitStepFinished;
                      }
                    }
                  }
                  else
                  {
                    Fomod.BeginReadOnlyTransaction();
                  }
                }
                if (!booCancelled)
                {
                  booSuccess = DoScript();
                  if (booSuccess)
                  {
                    tsTransaction.Complete();
                  }
                }
              }
            }
          }
        }
        catch (Exception e)
        {
          var stbError = new StringBuilder(e.Message);
          if (e is FileNotFoundException)
          {
            stbError.Append(" (" + ((FileNotFoundException) e).FileName + ")");
          }
          if (e is IllegalFilePathException)
          {
            stbError.Append(" (" + ((IllegalFilePathException) e).Path + ")");
          }
          if (e.InnerException != null)
          {
            stbError.AppendLine().AppendLine(e.InnerException.Message);
          }
          if (e is RollbackException)
          {
            foreach (var erm in ((RollbackException) e).ExceptedResourceManagers)
            {
              stbError.AppendLine(erm.ResourceManager.ToString());
              stbError.AppendLine(erm.Exception.Message);
              if (erm.Exception.InnerException != null)
              {
                stbError.AppendLine(erm.Exception.InnerException.Message);
              }
            }
          }
          var strMessage = String.Format(ExceptionMessage, stbError);
          MessageBox.Show(strMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
          return false;
        }
        finally
        {
          m_tfmFileManager = null;
          m_ilmModInstallLog = null;
          if (Fomod != null)
          {
            Fomod.EndReadOnlyTransaction();
          }
        }
      }
      if (booSuccess && !p_booSuppressSuccessMessage && !String.IsNullOrEmpty(SuccessMessage))
      {
        MessageBox.Show(SuccessMessage, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
      }
      else if (!booSuccess && !String.IsNullOrEmpty(FailMessage))
      {
        MessageBox.Show(FailMessage, "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
      return booSuccess;
    }
Beispiel #12
0
        public void Export(int scanFileID, string userName, string computer, string comment = null)
        {
            //kontrola vstupnich parametru
            if (scanFileID == 0)
                throw new ArgumentException("Neplatný parametr identifikátor souboru.");

            if (String.IsNullOrEmpty(userName))
                throw new ArgumentException("Neplatný parametr jméno uživatele.");

            if (String.IsNullOrEmpty(computer))
                throw new ArgumentException("Neplatný parametr název počítače.");

            ScanFileRepository repository = new ScanFileRepository();

            //kontrola existence naskenovaneho souboru
            ScanFile result = repository.Select(scanFileID);
            if (result == null)
                throw new ApplicationException(String.Format("Soubor (ID={0}) neexistuje.", scanFileID));

            //kontrola ulozenych parametrov
            if (result.Status != StatusCode.Complete)
                throw new ApplicationException(String.Format("Soubor (ID={0}) nemá status dokončeno.", result.ScanFileID));

            //export ALEPH
            TxFileManager fileMgr = new TxFileManager();
            string filePath = null;
            string ftpPath = null;

            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
            {
                try
                {
                    filePath = result.GetScanFilePath();

                    switch (result.PartOfBook)
                    {
                        case PartOfBook.FrontCover:
                            ftpPath = Path.Combine(result.Book.Catalogue.GetDirectoryFTP(true), result.FileName);
                            fileMgr.Copy(filePath, ftpPath, true);
                            break;

                        case PartOfBook.TableOfContents:
                            if (result.UseOCR)
                            {
                                string txtFilePath = Path.Combine(result.Book.Catalogue.GetDirectoryFTP(true), result.TxtFileName);
                                fileMgr.WriteAllText(txtFilePath, result.OcrText);
                            }

                            string pdfFilePath = result.GetOcrFilePath();
                            ftpPath = Path.Combine(result.Book.Catalogue.GetDirectoryFTP(true), result.OcrFileName);
                            fileMgr.Copy(pdfFilePath, ftpPath, true);
                            break;

                        default:
                            break;
                    }
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(String.Format("Nepodařilo se exportovat soubor '{0}' na FTP: {1}.", filePath, ex.Message));
                }

                //ulozenie operace do databazy
                try
                {
                    result.Modified = DateTime.Now;
                    result.Comment = (comment != null ? comment.Left(1000) : null);
                    result.Status = StatusCode.Exported;
                    repository.Update(result);

                    LogOperation(result.ScanFileID, userName, computer, result.Modified, result.Comment, result.Status);

                    ts.Complete();
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(String.Format("Nepodařilo se uložit data souboru (ID={0}) do databáze.", scanFileID), ex);
                }
            }
        }
		/// <summary>
		/// A simple constructor that initializes the object with its dependencies.
		/// </summary>
		/// <param name="p_gmiGameModeInfo">The environment info of the current game mode.</param>
		/// <param name="p_modMod">The mod being installed.</param>
		/// <param name="p_ilgInstallLog">The install log to use to log file installations.</param>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <param name="p_futFileUtility">The file utility class.</param>
		/// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
		public GamebryoGameSpecificValueInstaller(IMod p_modMod, IGameModeEnvironmentInfo p_gmiGameModeInfo, IInstallLog p_ilgInstallLog, TxFileManager p_tfmFileManager, FileUtil p_futFileUtility, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate)
		{
			TouchedFiles = new Set<string>(StringComparer.OrdinalIgnoreCase);
			Mod = p_modMod;
			GameModeInfo = p_gmiGameModeInfo;
			InstallLog = p_ilgInstallLog;
			TransactionalFileManager = p_tfmFileManager;
			FileUtility = p_futFileUtility;
			m_dlgOverwriteConfirmationDelegate = p_dlgOverwriteConfirmationDelegate;
		}
		/// <summary>
		/// Gets the installer to use to upgrade game specific values.
		/// </summary>
		/// <param name="p_modMod">The mod being upgraded.</param>
		/// <param name="p_ilgInstallLog">The install log to use to log the installation of the game specific values.</param>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <returns>The installer to use to manage game specific values, or <c>null</c> if the game mode does not
		/// install any game specific values.</returns>
		/// <param name="p_futFileUtility">The file utility class.</param>
		/// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
		public override IGameSpecificValueInstaller GetGameSpecificValueUpgradeInstaller(IMod p_modMod, IInstallLog p_ilgInstallLog, TxFileManager p_tfmFileManager, FileUtil p_futFileUtility, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate)
		{
			return new GamebryoGameSpecificValueInstaller(p_modMod, GameModeEnvironmentInfo, p_ilgInstallLog, p_tfmFileManager, p_futFileUtility, p_dlgOverwriteConfirmationDelegate);
		}
Beispiel #15
0
    /// <summary>
    ///   This performs the mirgration.
    /// </summary>
    /// <param name="p_objArgs">The path to the old FOMM installation.</param>
    protected void DoMigration(object p_objArgs)
    {
      var strOldFOMMLocation = (string) p_objArgs;
      var tfmFileManager = new TxFileManager();

      //copy the mods
      //do we need to copy?
      if (
        !Path.Combine(strOldFOMMLocation, "mods")
             .Equals(Program.GameMode.ModDirectory, StringComparison.InvariantCultureIgnoreCase))
      {
        var lstModFiles = new List<string>();
        lstModFiles.AddRange(Directory.GetFiles(Path.Combine(strOldFOMMLocation, "mods"), "*.fomod"));
        lstModFiles.AddRange(Directory.GetFiles(Path.Combine(strOldFOMMLocation, "mods"), "*.xml"));
        m_bwdProgress.ItemMessage = "Copying mods...";
        m_bwdProgress.ItemProgressMaximum = lstModFiles.Count;
        m_bwdProgress.ItemProgress = 0;
        foreach (var strMod in lstModFiles)
        {
          var strModFileName = Path.GetFileName(strMod);
          m_bwdProgress.ItemMessage = "Copying mods (" + strModFileName + ")...";
          tfmFileManager.Copy(strMod, Path.Combine(Program.GameMode.ModDirectory, strModFileName), true);
          //File.Copy(strMod, Path.Combine(Program.GameMode.ModDirectory, Path.GetFileName(strMod)));
          m_bwdProgress.StepItemProgress();
          if (m_bwdProgress.Cancelled())
          {
            return;
          }
        }
      }

      m_bwdProgress.StepOverallProgress();

      //copy overwrites folder
      //do we need to?
      if (
        !Path.Combine(strOldFOMMLocation, "overwrites")
             .Equals(Program.GameMode.OverwriteDirectory,
                     StringComparison.InvariantCultureIgnoreCase))
      {
        var strOverwriteFiles = Directory.GetFiles(Path.Combine(strOldFOMMLocation, "overwrites"), "*.*",
                                                   SearchOption.AllDirectories);
        m_bwdProgress.ItemMessage = "Copying overwrites...";
        m_bwdProgress.ItemProgressMaximum = strOverwriteFiles.Length;
        m_bwdProgress.ItemProgress = 0;
        FileUtil.Copy(tfmFileManager, Path.Combine(strOldFOMMLocation, "overwrites"),
                      Program.GameMode.OverwriteDirectory, OverwriteFileCopied);
      }

      m_bwdProgress.StepOverallProgress();

      //copy install logs
      //do we need to?
      if (
        !Path.Combine(strOldFOMMLocation, "fomm")
             .Equals(Program.GameMode.InstallInfoDirectory, StringComparison.InvariantCultureIgnoreCase))
      {
        var strMiscFiles = Directory.GetFiles(Path.Combine(strOldFOMMLocation, "fomm"), "InstallLog.xml*");
        m_bwdProgress.ItemMessage = "Copying info files...";
        m_bwdProgress.ItemProgressMaximum = strMiscFiles.Length;
        m_bwdProgress.ItemProgress = 0;
        foreach (var strFile in strMiscFiles)
        {
          tfmFileManager.Copy(strFile, Path.Combine(Program.GameMode.InstallInfoDirectory, Path.GetFileName(strFile)),
                              true);
          m_bwdProgress.StepItemProgress();
          if (m_bwdProgress.Cancelled())
          {
            return;
          }
        }
      }

      m_bwdProgress.StepOverallProgress();
    }
Beispiel #16
0
        //[Obsolete]
        //public void Export2(int scanFileID, string ftpPath)
        //{
        //    //kontrola vstupnich parametru
        //    if (scanFileID == 0)
        //        throw new ArgumentException("Neplatný parametr identifikátor souboru.");
        //    ScanFileRepository repository = new ScanFileRepository();
        //    //kontrola existence naskenovaneho souboru
        //    ScanFile result = repository.Select(scanFileID);
        //    if (result == null)
        //        throw new ApplicationException(String.Format("Soubor (ID={0}) neexistuje.", scanFileID));
        //    //kontrola ulozenych parametrov
        //    if (result.Status != StatusCode.Exported)
        //        throw new ApplicationException(String.Format("Soubor (ID={0}) nemá status exportováno.", result.ScanFileID));
        //    //export ALEPH
        //    TxFileManager fileMgr = new TxFileManager();
        //    string filePath = null;
        //    try
        //    {
        //        filePath = result.GetScanFilePath();
        //        string ftpFilePath = null;
        //        switch (result.PartOfBook)
        //        {
        //            case PartOfBook.FrontCover:
        //                ftpFilePath = Path.Combine(ftpPath, result.FileName);
        //                fileMgr.Copy(filePath, ftpFilePath, true);
        //                break;
        //            case PartOfBook.TableOfContents:
        //                if (result.UseOCR)
        //                {
        //                    string txtFilePath = Path.Combine(ftpPath, result.TxtFileName);
        //                    fileMgr.WriteAllText(txtFilePath, result.OcrText);
        //                }
        //                string pdfFilePath = result.GetOcrFilePath();
        //                ftpFilePath = Path.Combine(ftpPath, result.OcrFileName);
        //                fileMgr.Copy(pdfFilePath, ftpFilePath, true);
        //                break;
        //            default:
        //                break;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new ApplicationException(String.Format("Nepodařilo se exportovat soubor '{0}' na FTP: {1}.", filePath, ex.Message));
        //    }
        //}
        public void Delete(int scanFileID, string userName)
        {
            //kontrola vstupnich parametru
            if (scanFileID == 0)
                throw new ArgumentException("Neplatný parametr identifikátor souboru.");

            if (String.IsNullOrEmpty(userName))
                throw new ArgumentException("Neplatný parametr jméno uživatele.");

            ScanFileRepository repository = new ScanFileRepository();

            //kontrola existence naskenovaneho souboru
            ScanFile result = repository.Select(scanFileID);
            if (result == null)
                throw new ApplicationException(String.Format("Soubor (ID={0}) neexistuje.", scanFileID));

            //kontrola ulozenych parametrov
            if (result.Status == StatusCode.Exported)
                throw new ApplicationException(String.Format("Soubor (ID={0}) má status exportován.", result.ScanFileID));

            //vymazanie suboru naskenovaneho obrazku
            TxFileManager fileMgr = new TxFileManager();
            string filePath = null;

            //ulozenie operace do databazy
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
            {
                try
                {
                    filePath = result.GetScanFilePath();
                    if (fileMgr.FileExists(filePath)) fileMgr.Delete(filePath);

                    filePath = result.GetOcrFilePath();
                    if (fileMgr.FileExists(filePath)) fileMgr.Delete(filePath);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(String.Format("Nepodařilo se vymazat soubor '{0}' z disku: {1}.", filePath, ex.Message));
                }

                try
                {
                    repository.Delete(result);

                    Book book = BookComponent.Instance.GetByID(result.BookID);
                    if (book != null && (book.ScanFiles == null || book.ScanFiles.Count == 0))
                    {
                        BookComponent.Instance.Delete(result.BookID, userName);
                    }

                    ts.Complete();
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(String.Format("Nepodařilo se vymazat data souboru (ID={0}) z databáze.", scanFileID), ex);
                }
            }
        }
		/// <summary>
		/// Creates the file installer to use to install the mod's ini edits.
		/// </summary>
		/// <remarks>
		/// This returns the regular <see cref="IniInstaller"/>.
		/// </remarks>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
		/// <returns>The file installer to use to install the mod's files.</returns>
		protected virtual IIniInstaller CreateIniInstaller(TxFileManager p_tfmFileManager, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate)
		{
			return new IniInstaller(Mod, ModInstallLog, p_tfmFileManager, p_dlgOverwriteConfirmationDelegate);
		}
		/// <summary>
		/// Runs the install tasks.
		/// </summary>
		protected void RunTasks()
		{
			//the install process modifies INI and config files.
			// if multiple sources (i.e., installs) try to modify
			// these files simultaneously the outcome is not well known
			// (e.g., one install changes SETTING1 in a config file to valueA
			// while simultaneously another install changes SETTING1 in the
			// file to value2 - after each install commits its changes it is
			// not clear what the value of SETTING1 will be).
			// as a result, we only allow one mod to be installed at a time,
			// hence the lock.
			bool booSuccess = false;
			string strMessage = "The mod was not activated.";

			try
			{
				lock (objUninstallLock)
				{
					using (TransactionScope tsTransaction = new TransactionScope())
					{
						if (!File.Exists(Mod.Filename))
							throw new Exception("The selected file was not found: " + Mod.Filename);
						
						TxFileManager tfmFileManager = new TxFileManager();

						if (!BeginModReadOnlyTransaction())
							return;
						RegisterMod();
						booSuccess = RunScript(tfmFileManager);
						if (booSuccess)
						{
							Mod.InstallDate = DateTime.Now.ToString();
							tsTransaction.Complete();
							strMessage = "The mod was successfully activated.";
							GC.GetTotalMemory(true);
						}
					}
				}
			}
			catch (TransactionException)
			{
				throw;
			}
			catch (SecurityException)
			{
				throw;
			}
			catch (ObjectDisposedException)
			{
				throw;
			}
			//this blobck used to be conditionally excluded from debug builds,
			// presumably so that the debugger would break on the source of the
			// exception, however that prevents the full mod install flow from
			// happening, which lead to missed bugs
			catch (Exception e)
			{
				StringBuilder stbError = new StringBuilder(e.Message);
				if (e is FileNotFoundException)
					stbError.Append(" (" + ((FileNotFoundException)e).FileName + ")");
				if (e is IllegalFilePathException)
					stbError.Append(" (" + ((IllegalFilePathException)e).Path + ")");
				if (e.InnerException != null)
					stbError.AppendLine().AppendLine(e.InnerException.Message);
				if (e is RollbackException)
					foreach (RollbackException.ExceptedResourceManager erm in ((RollbackException)e).ExceptedResourceManagers)
					{
						stbError.AppendLine(erm.ResourceManager.ToString());
						stbError.AppendLine(erm.Exception.Message);
						if (erm.Exception.InnerException != null)
							stbError.AppendLine(erm.Exception.InnerException.Message);
					}
				string strExceptionMessageFormat = "A problem occurred during install: " + Environment.NewLine + "{0}" + Environment.NewLine + "The mod was not installed."; ;
				strMessage = String.Format(strExceptionMessageFormat, stbError.ToString());
				PopupErrorMessage = strMessage;
				PopupErrorMessageType = "Error";
			}
			finally
			{
				Mod.EndReadOnlyTransaction();
			}
			OnTaskSetCompleted(booSuccess, strMessage, Mod);
		}
		/// <summary>
		/// This executes the install script.
		/// </summary>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <returns><c>true</c> if the script completed successfully;
		/// <c>false</c> otherwise.</returns>
		protected bool RunScript(TxFileManager p_tfmFileManager)
		{
			IModFileInstaller mfiFileInstaller = CreateFileInstaller(p_tfmFileManager, m_dlgOverwriteConfirmationDelegate);
			bool booResult = false;
			IIniInstaller iniIniInstaller = null;
			IGameSpecificValueInstaller gviGameSpecificValueInstaller = null;
			if (Mod.HasInstallScript)
			{
				try
				{
					IDataFileUtil dfuDataFileUtility = new DataFileUtil(GameMode.GameModeEnvironmentInfo.InstallationPath);

					iniIniInstaller = CreateIniInstaller(p_tfmFileManager, m_dlgOverwriteConfirmationDelegate);
					gviGameSpecificValueInstaller = CreateGameSpecificValueInstaller(p_tfmFileManager, m_dlgOverwriteConfirmationDelegate);

					InstallerGroup ipgInstallers = new InstallerGroup(dfuDataFileUtility, mfiFileInstaller, iniIniInstaller, gviGameSpecificValueInstaller, PluginManager);
					IScriptExecutor sexScript = Mod.InstallScript.Type.CreateExecutor(Mod, GameMode, EnvironmentInfo, ipgInstallers, UIContext);
					sexScript.TaskStarted += new EventHandler<EventArgs<IBackgroundTask>>(ScriptExecutor_TaskStarted);
					sexScript.TaskSetCompleted += new EventHandler<TaskSetCompletedEventArgs>(ScriptExecutor_TaskSetCompleted);
					booResult = sexScript.Execute(Mod.InstallScript);
				}
				catch (Exception ex)
				{
					PopupErrorMessage = ex.Message;
					PopupErrorMessageType = "Error";
				}

				iniIniInstaller.FinalizeInstall();

				if (gviGameSpecificValueInstaller != null)
					gviGameSpecificValueInstaller.FinalizeInstall();
			}
			else
				booResult = RunBasicInstallScript(mfiFileInstaller, ActiveMods);
			mfiFileInstaller.FinalizeInstall();
			return booResult;
		}
Beispiel #20
0
        /// <summary>
        /// Called to perform the upgrade.
        /// </summary>
        /// <remarks>
        /// Sets up the resources required to upgrade the install log, and then
        /// call <see cref="DoUpgrade()"/> so implementers can do the upgrade.
        /// </remarks>
        /// <returns><lang cref="true"/> if the upgrade completed; <lang cref="false"/>
        /// if the user cancelled.</returns>
        internal bool PerformUpgrade()
        {
            #if TRACE
            Trace.WriteLine("Beginning Install Log Upgrade.");
            #endif
            m_tfmFileManager = new TxFileManager();
            bool booComplete = false;
            using (TransactionScope tsTransaction = new TransactionScope())
            {
                m_tfmFileManager.Snapshot(InstallLog.Current.InstallLogPath);

                using (m_pgdProgress = new BackgroundWorkerProgressDialog(DoUpgrade))
                {
                    m_pgdProgress.OverallMessage = "Upgrading FOMM Files";
                    if (m_pgdProgress.ShowDialog() == DialogResult.OK)
                    {
                        booComplete = true;
                        tsTransaction.Complete();
                    }
                }
                m_tfmFileManager = null;
            }
            return booComplete;
        }
		/// <summary>
		/// Runs the basic uninstall script.
		/// </summary>
		/// <remarks>
		/// A basic uninstall uninstalls all of the changes made when the mod was installed.
		/// </remarks>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <returns><c>true</c> if the uninstallation was successful;
		/// <c>false</c> otherwise.</returns>
		protected bool RunBasicUninstallScript(TxFileManager p_tfmFileManager, out string p_strErrorMessage)
		{
			p_strErrorMessage = null;
			IDataFileUtil dfuDataFileUtility = new DataFileUtil(GameMode.GameModeEnvironmentInfo.InstallationPath);

            IModFileInstaller mfiFileInstaller = new ModFileInstaller(GameMode.GameModeEnvironmentInfo, Mod, ModInstallLog, PluginManager, dfuDataFileUtility, p_tfmFileManager, null, GameMode.UsesPlugins, m_mmModManager);
			IIniInstaller iniIniInstaller = new IniInstaller(Mod, ModInstallLog, p_tfmFileManager, null);
			IGameSpecificValueInstaller gviGameSpecificValueInstaller = GameMode.GetGameSpecificValueInstaller(Mod, ModInstallLog, p_tfmFileManager, new NexusFileUtil(EnvironmentInfo), null);

			InstallerGroup ipgInstallers = new InstallerGroup(dfuDataFileUtility, mfiFileInstaller, iniIniInstaller, gviGameSpecificValueInstaller, PluginManager);
			BasicUninstallTask butTask = new BasicUninstallTask(Mod, ipgInstallers, ModInstallLog, GameMode, ActiveMods);
			OnTaskStarted(butTask);

			bool booResult = butTask.Execute();

			if (mfiFileInstaller.InstallErrors.Count > 0)
			{
				p_strErrorMessage = Environment.NewLine + "There were issues while installing/uninstalling this mod:" + Environment.NewLine;
				foreach (string strPath in mfiFileInstaller.InstallErrors)
					DetailsErrorMessage += strPath + Environment.NewLine;

				PopupErrorMessage = p_strErrorMessage;
				PopupErrorMessageType = butTask.strPopupErrorMessageType;
			}

			mfiFileInstaller.FinalizeInstall();
			iniIniInstaller.FinalizeInstall();
			if (gviGameSpecificValueInstaller != null)
				gviGameSpecificValueInstaller.FinalizeInstall();

			return booResult;
		}
		/// <summary>
		/// Runs the uninstall tasks.
		/// </summary>
		protected void RunTasks()
		{
			//the install process modifies INI and config files.
			// if multiple sources (i.e., installs) try to modify
			// these files simultaneously the outcome is not well known
			// (e.g., one install changes SETTING1 in a config file to valueA
			// while simultaneously another install changes SETTING1 in the
			// file to value2 - after each install commits its changes it is
			// not clear what the value of SETTING1 will be).
			// as a result, we only allow one mod to be installed at a time,
			// hence the lock.
			bool booSuccess = false;
			string strErrorMessage = String.Empty;

			lock (objUninstallLock)
			{
				using (TransactionScope tsTransaction = new TransactionScope())
				{
					TxFileManager tfmFileManager = new TxFileManager();

					booSuccess = RunBasicUninstallScript(tfmFileManager, out strErrorMessage);
					if (booSuccess)
					{
						Mod.InstallDate = null;
						ModInstallLog.RemoveMod(Mod);
						tsTransaction.Complete();
						GC.GetTotalMemory(true);
					}
				}
			}

			if (booSuccess)
				OnTaskSetCompleted(booSuccess, "The mod was successfully deactivated." + Environment.NewLine + strErrorMessage, Mod);
			else
				OnTaskSetCompleted(false, "The mod was not deactivated." + Environment.NewLine + strErrorMessage, Mod);
		}
		/// <summary>
		/// Gets the installer to use to install game specific values.
		/// </summary>
		/// <param name="p_modMod">The mod being installed.</param>
		/// <param name="p_ilgInstallLog">The install log to use to log the installation of the game specific values.</param>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <returns>The installer to use to manage game specific values, or <c>null</c> if the game mode does not
		/// install any game specific values.</returns>
		/// <param name="p_futFileUtility">The file utility class.</param>
		/// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
		public override IGameSpecificValueInstaller GetGameSpecificValueInstaller(IMod p_modMod, IInstallLog p_ilgInstallLog, TxFileManager p_tfmFileManager, FileUtil p_futFileUtility, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate)
		{
			return null;
		}
		/// <summary>
		/// Creates the file installer to use to install the mod's game specific value edits.
		/// </summary>
		/// <remarks>
		/// This returns a regular <see cref="IGameSpecificValueInstaller"/>.
		/// </remarks>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
		/// <returns>The file installer to use to install the mod's files.</returns>
		protected virtual IGameSpecificValueInstaller CreateGameSpecificValueInstaller(TxFileManager p_tfmFileManager, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate)
		{
			return GameMode.GetGameSpecificValueInstaller(Mod, ModInstallLog, p_tfmFileManager, new NexusFileUtil(EnvironmentInfo), p_dlgOverwriteConfirmationDelegate);
		}
		/// <summary>
		/// Gets the installer to use to upgrade game specific values.
		/// </summary>
		/// <param name="p_modMod">The mod being upgraded.</param>
		/// <param name="p_ilgInstallLog">The install log to use to log the installation of the game specific values.</param>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <returns>The installer to use to manage game specific values, or <c>null</c> if the game mode does not
		/// install any game specific values.</returns>
		/// <param name="p_futFileUtility">The file utility class.</param>
		/// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
		public abstract IGameSpecificValueInstaller GetGameSpecificValueUpgradeInstaller(IMod p_modMod, IInstallLog p_ilgInstallLog, TxFileManager p_tfmFileManager, FileUtil p_futFileUtility, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate);
		/// <summary>
		/// A simple constructor that initializes the object with its dependencies.
		/// </summary>
		/// <param name="p_modMod">The mod being installed.</param>
		/// <param name="p_ilgInstallLog">The install log to use to log file installations.</param>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
		public IniUpgradeInstaller(IMod p_modMod, IInstallLog p_ilgInstallLog, TxFileManager p_tfmFileManager, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate)
			: base(p_modMod, p_ilgInstallLog, p_tfmFileManager, p_dlgOverwriteConfirmationDelegate)
		{
			OriginallyInstalledEdits = new Set<IniEdit>();
			OriginallyInstalledEdits.AddRange(InstallLog.GetInstalledIniEdits(Mod));
		}
        public void ExtensionMethods_WriteToFile_RollbackIfError()
        {
            //------------Setup for test--------------------------
            var tmpFile = Path.GetTempFileName();
            File.WriteAllText(tmpFile, "this is going to be some very long test just to ensure we can over write it");
            const string val = "<x><y>1</y></x>";
            StringBuilder value = new StringBuilder(val);

            //------------Execute Test---------------------------
            IFileManager fm = new TxFileManager();
            value.WriteToFile(tmpFile, Encoding.UTF8, fm);

            //------------Assert Results-------------------------
            var result = File.ReadAllText(tmpFile);

            // clean up ;)
            File.Delete(tmpFile);

            Assert.AreEqual(val, result, "WriteToFile did not truncate");
        }
Beispiel #28
0
        /// <summary>
        /// This performs the mirgration.
        /// </summary>
        /// <param name="p_objArgs">The path to the old FOMM installation.</param>
        protected void DoMigration(object p_objArgs)
        {
            string strOldFOMMLocation = (string)p_objArgs;
            TxFileManager tfmFileManager = new TxFileManager();

            //copy the mods
            //do we need to copy?
            #if TRACE
            Trace.Write("Copying Mods (");
            #endif
            if (!Path.Combine(strOldFOMMLocation, "mods").Equals(Program.GameMode.ModDirectory, StringComparison.InvariantCultureIgnoreCase))
            {
                List<string> lstModFiles = new List<string>();
                lstModFiles.AddRange(Directory.GetFiles(Path.Combine(strOldFOMMLocation, "mods"), "*.fomod"));
                lstModFiles.AddRange(Directory.GetFiles(Path.Combine(strOldFOMMLocation, "mods"), "*.xml"));
                m_bwdProgress.ItemMessage = "Copying mods...";
            #if TRACE
                Trace.WriteLine(lstModFiles.Count + "):");
                Trace.Indent();
            #endif
                m_bwdProgress.ItemProgressMaximum = lstModFiles.Count;
                m_bwdProgress.ItemProgress = 0;
                string strModFileName = null;
                foreach (string strMod in lstModFiles)
                {
                    strModFileName = Path.GetFileName(strMod);
                    m_bwdProgress.ItemMessage = "Copying mods (" + strModFileName + ")...";
            #if TRACE
                    Trace.WriteLine(strMod + " => " + Path.Combine(Program.GameMode.ModDirectory, strModFileName));
            #endif
                    tfmFileManager.Copy(strMod, Path.Combine(Program.GameMode.ModDirectory, strModFileName), true);
                    //File.Copy(strMod, Path.Combine(Program.GameMode.ModDirectory, Path.GetFileName(strMod)));
                    m_bwdProgress.StepItemProgress();
                    if (m_bwdProgress.Cancelled())
                    {
            #if TRACE
                        Trace.Unindent();
                        Trace.WriteLine("Cancelled copying Mods.");
            #endif
                        return;
                    }
                }
            }
            #if TRACE
            else
            {
                Trace.WriteLine("No Need).");
            }
            Trace.Unindent();
            Trace.WriteLine("Done copying Mods.");
            #endif

            m_bwdProgress.StepOverallProgress();

            //copy overwrites folder
            //do we need to?
            #if TRACE
            Trace.WriteLine("Copying overwrite files (");
            #endif
            if (!Path.Combine(strOldFOMMLocation, "overwrites").Equals(((Fallout3GameMode)Program.GameMode).OverwriteDirectory, StringComparison.InvariantCultureIgnoreCase))
            {
                string[] strOverwriteFiles = Directory.GetFiles(Path.Combine(strOldFOMMLocation, "overwrites"), "*.*", SearchOption.AllDirectories);
                m_bwdProgress.ItemMessage = "Copying overwrites...";
                m_bwdProgress.ItemProgressMaximum = strOverwriteFiles.Length;
                m_bwdProgress.ItemProgress = 0;
            #if TRACE
                Trace.WriteLine(strOverwriteFiles.Length + "):");
                Trace.Indent();
            #endif
                FileUtil.Copy(tfmFileManager, Path.Combine(strOldFOMMLocation, "overwrites"), ((Fallout3GameMode)Program.GameMode).OverwriteDirectory, OverwriteFileCopied);
            }
            #if TRACE
            else
            {
                Trace.WriteLine("No Need).");
            }
            Trace.Unindent();
            Trace.WriteLine("Done copying overwrite files.");
            #endif

            m_bwdProgress.StepOverallProgress();

            //copy install logs
            //do we need to?
            #if TRACE
            Trace.WriteLine("Copying install logs (");
            #endif
            if (!Path.Combine(strOldFOMMLocation, "fomm").Equals(Program.GameMode.InstallInfoDirectory, StringComparison.InvariantCultureIgnoreCase))
            {
                string[] strMiscFiles = Directory.GetFiles(Path.Combine(strOldFOMMLocation, "fomm"), "InstallLog.xml*");
                m_bwdProgress.ItemMessage = "Copying info files...";
                m_bwdProgress.ItemProgressMaximum = strMiscFiles.Length;
                m_bwdProgress.ItemProgress = 0;
            #if TRACE
                Trace.WriteLine(strMiscFiles.Length + "):");
                Trace.Indent();
            #endif
                foreach (string strFile in strMiscFiles)
                {
            #if TRACE
                    Trace.WriteLine(strFile + " => " + Path.Combine(Program.GameMode.InstallInfoDirectory, Path.GetFileName(strFile)));
            #endif
                    tfmFileManager.Copy(strFile, Path.Combine(Program.GameMode.InstallInfoDirectory, Path.GetFileName(strFile)), true);
                    m_bwdProgress.StepItemProgress();
                    if (m_bwdProgress.Cancelled())
                    {
            #if TRACE
                        Trace.Unindent();
                        Trace.WriteLine("Cancelled copying install logs.");
            #endif
                        return;
                    }
                }
            }
            #if TRACE
            else
            {
                Trace.WriteLine("No Need).");
            }
            Trace.Unindent();
            Trace.WriteLine("Done copying install logs.");
            #endif

            m_bwdProgress.StepOverallProgress();
        }
		/// <summary>
		/// Creates the file installer to use to install the mod's files.
		/// </summary>
		/// <remarks>
		/// This returns the regular <see cref="ModFileInstaller"/>.
		/// </remarks>
		/// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
		/// <param name="p_dlgOverwriteConfirmationDelegate">The method to call in order to confirm an overwrite.</param>
		/// <returns>The file installer to use to install the mod's files.</returns>
		protected virtual IModFileInstaller CreateFileInstaller(TxFileManager p_tfmFileManager, ConfirmItemOverwriteDelegate p_dlgOverwriteConfirmationDelegate)
		{
            return new ModFileInstaller(GameMode.GameModeEnvironmentInfo, Mod, ModInstallLog, PluginManager, new DataFileUtil(GameMode.GameModeEnvironmentInfo.InstallationPath), p_tfmFileManager, p_dlgOverwriteConfirmationDelegate, GameMode.UsesPlugins, m_mmModManager);
		}
        public void BuildCatalogFromWorkspace(string workspacePath, params string[] folders)
        {
            if (string.IsNullOrEmpty(workspacePath))
            {
                throw new ArgumentNullException("workspacePath");
            }
            if (folders == null)
            {
                throw new ArgumentNullException("folders");
            }

            if (folders.Length == 0 || !Directory.Exists(workspacePath))
            {
                return;
            }

            var streams = new List<ResourceBuilderTO>();

            try
            {

                foreach (var path in folders.Where(f => !string.IsNullOrEmpty(f) && !f.EndsWith("VersionControl")).Select(f => Path.Combine(workspacePath, f)))
                {
                    if (!Directory.Exists(path))
                    {
                        continue;
                    }

                    var files = Directory.GetFiles(path, "*.xml");
                    foreach (var file in files)
                    {

                        FileAttributes fa = File.GetAttributes(file);

                        if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                        {
                            Dev2Logger.Log.Info("Removed READONLY Flag from [ " + file + " ]");
                            File.SetAttributes(file, FileAttributes.Normal);
                        }

                        // Use the FileStream class, which has an option that causes asynchronous I/O to occur at the operating system level.  
                        // In many cases, this will avoid blocking a ThreadPool thread.  
                        var sourceStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, true);
                        streams.Add(new ResourceBuilderTO { FilePath = file, FileStream = sourceStream });

                    }
                }

                // Use the parallel task library to process file system ;)
                streams.ForEach(currentItem =>
                {

                    XElement xml = null;

                    try
                    {
                        xml = XElement.Load(currentItem.FileStream);
                    }
                    catch (Exception e)
                    {
                        Dev2Logger.Log.Error("Resource [ " + currentItem.FilePath + " ] caused " + e.Message);
                    }

                    StringBuilder result = xml.ToStringBuilder();

                    var isValid = xml != null && HostSecurityProvider.Instance.VerifyXml(result);
                    if (isValid)
                    {
                        var resource = new Resource(xml)
                        {
                            FilePath = currentItem.FilePath
                        };

                        //2013.08.26: Prevent duplicate unassigned folder in save dialog and studio explorer tree by interpreting 'unassigned' as blank
                        if (resource.ResourcePath.ToUpper() == "UNASSIGNED")
                        {
                            resource.ResourcePath = string.Empty;
                            // DON'T FORCE A SAVE HERE - EVER!!!!
                        }
                        xml = _resourceUpgrader.UpgradeResource(xml, Assembly.GetExecutingAssembly().GetName().Version, a =>
                        {

                            var fileManager = new TxFileManager();
                            using (TransactionScope tx = new TransactionScope())
                            {
                                try
                                {

                                    StringBuilder updateXml = a.ToStringBuilder();
                                    var signedXml = HostSecurityProvider.Instance.SignXml(updateXml);

                                    signedXml.WriteToFile(currentItem.FilePath, Encoding.UTF8, fileManager);
                                    tx.Complete();
                                }
                                catch 
                                {
                                    try
                                    {
                                        Transaction.Current.Rollback();
                                    }
                                    catch (Exception err)
                                    {
                                        Dev2Logger.Log.Error(err);
                                    }
                                    throw;
                                }
                            }

                        });
                        if (resource.IsUpgraded)
                        {
                            // Must close the source stream first and then add a new target stream 
                            // otherwise the file will be remain locked
                            currentItem.FileStream.Close();

                            xml = resource.UpgradeXml(xml, resource);

                            StringBuilder updateXml = xml.ToStringBuilder();
                            var signedXml = HostSecurityProvider.Instance.SignXml(updateXml);
                             var fileManager = new TxFileManager();
                             using (TransactionScope tx = new TransactionScope())
                             {
                                 try
                                 {
                                     signedXml.WriteToFile(currentItem.FilePath, Encoding.UTF8,fileManager);
                                     tx.Complete();
                                 }
                                 catch
                                 {
                                     Transaction.Current.Rollback();
                                     throw;
                                 }
                             }
                        }
                        if (resource.VersionInfo == null)
                        {

                        }

                        lock (_addLock)
                        {
                            AddResource(resource, currentItem.FilePath);
                        }
                    }
                    else
                    {
                        Dev2Logger.Log.Debug(string.Format("'{0}' wasn't loaded because it isn't signed or has modified since it was signed.", currentItem.FilePath));
                    }
                });
            }
            finally
            {
                // Close all FileStream instances in a finally block after the tasks are complete. 
                // If each FileStream was instead created in a using statement, the FileStream 
                // might be disposed of before the task was complete
                foreach (var stream in streams)
                {
                    stream.FileStream.Close();
                }
            }
        }