public void RenameFile()
        {
            var fullNameWithRenamedFolder =
                Path.Combine(ProjectFullNameNew.GetDirectoryName(), ProjectFullName.GetFileName());

            FileManager.Move(fullNameWithRenamedFolder, this.ProjectFullNameNew);
        }
        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, " ")));
            }
        }
Пример #3
0
        /// <summary>
        /// Stores the results of a given URL in the cache.
        /// Description is adjusted to be filesystem-safe and then appended to the file hash when saving.
        /// If not present, the filename will be used.
        /// If `move` is true, then the file will be moved; otherwise, it will be copied.
        ///
        /// Returns a path to the newly cached file.
        ///
        /// This method is filesystem transaction aware.
        /// </summary>
        public string Store(Uri url, string path, string description = null, bool move = false)
        {
            log.DebugFormat("Storing {0}", url);

            // Make sure we clear our cache entry first.
            Remove(url);

            string hash = CreateURLHash(url);

            description = description ?? Path.GetFileName(path);

            Debug.Assert(
                Regex.IsMatch(description, "^[A-Za-z0-9_.-]*$"),
                "description isn't as filesystem safe as we thought... (#1266)"
                );

            string fullName   = String.Format("{0}-{1}", hash, Path.GetFileName(description));
            string targetPath = Path.Combine(cachePath, fullName);

            log.DebugFormat("Storing {0} in {1}", path, targetPath);

            if (move)
            {
                tx_file.Move(path, targetPath);
            }
            else
            {
                tx_file.Copy(path, targetPath, true);
            }

            // We've changed our cache, so signal that immediately.
            OnCacheChanged();

            return(targetPath);
        }
Пример #4
0
        /// <summary>
        /// Stores the results of a given URL in the cache.
        /// Description is appended to the file hash when saving. If not present, the filename will be used.
        /// If `move` is true, then the file will be moved; otherwise, it will be copied.
        ///
        /// Returns a path to the newly cached file.
        ///
        /// This method is filesystem transaction aware.
        /// </summary>
        public string Store(Uri url, string path, string description = null, bool move = false)
        {
            log.DebugFormat("Storing {0}", url);

            // Make sure we clear our cache entry first.
            this.Remove(url);

            string hash = CreateURLHash(url);

            description = description ?? Path.GetFileName(path);

            string fullName   = String.Format("{0}-{1}", hash, Path.GetFileName(description));
            string targetPath = Path.Combine(cachePath, fullName);

            log.DebugFormat("Storing {0} in {1}", path, targetPath);

            if (move)
            {
                tx_file.Move(path, targetPath);
            }
            else
            {
                tx_file.Copy(path, targetPath, overwrite: true);
            }

            return(targetPath);
        }
Пример #5
0
        public bool MoveFile(string fileInWCard, string fileOutPath)
        {
            if (isFileMoved == true)
            {
                return(true);
            }
            archiveFileName = "";
            try
            {
                string filePath = GetFile(fileInWCard);
                if (!string.IsNullOrEmpty(filePath))
                {
                    TxFileManager fileMgr = new TxFileManager();
                    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions()
                    {
                        IsolationLevel = IsolationLevel.ReadCommitted
                    }))
                    {
                        String   fileName   = System.IO.Path.GetFileName(filePath);
                        DateTime myDateTime = DateTime.Now;
                        archiveFileName = System.IO.Path.Combine(new string[] { fileOutPath, myDateTime.Year.ToString("0000"), myDateTime.Month.ToString("00"), myDateTime.Day.ToString("00"), fileName });
                        try
                        {
                            //Create the dir
                            fileMgr.CreateDirectory(System.IO.Path.GetDirectoryName(archiveFileName));
                            //Move file to archive
                            fileMgr.Move(filePath, archiveFileName);
                        }
                        catch (System.IO.FileNotFoundException ex)
                        {
                            numOfRetried++;
                            SolutionTraceClass.WriteLineInfo(String.Format("'Credit' File ({1}) could not be moved.  Exception.  Message was->{0}", ex.Message, fileName));
                            LoggingHelper.LogErrorActivity(String.Format("'Credit' File ({0}) could not be moved.", fileName), ex);
                            archiveFileName = "";
                        }
                        catch (Exception ex)
                        {
                            numOfRetried++;
                            SolutionTraceClass.WriteLineWarning(String.Format("'Credit' File ({1}) could not be moved.  Exception.  Message was->{0}", ex.Message, fileName));
                            LoggingHelper.LogErrorActivity(String.Format("'Credit' File ({0}) could not be moved.", fileName), ex);
                            archiveFileName = "";
                        }

                        scope.Complete();
                        isFileMoved = true;
                    }
                }
            }
            catch (Exception ex)
            {
                SolutionTraceClass.WriteLineError(String.Format("'Credit' Exception.  Message was->{0}", ex.Message));
                LoggingHelper.LogErrorActivity(ex);
                SolutionTraceClass.WriteLineVerbose("End");
                return(false);
            }

            SolutionTraceClass.WriteLineVerbose("End");
            return(!string.IsNullOrEmpty(archiveFileName));
        }
Пример #6
0
        /// <summary>
        /// Stores the results of a given URL in the cache.
        /// Description is adjusted to be filesystem-safe and then appended to the file hash when saving.
        /// If not present, the filename will be used.
        /// If `move` is true, then the file will be moved; otherwise, it will be copied.
        ///
        /// Returns a path to the newly cached file.
        ///
        /// This method is filesystem transaction aware.
        /// </summary>
        public string Store(Uri url, string path, string description = null, bool move = false)
        {
            log.DebugFormat("Storing {0}", url);

            TxFileManager tx_file = new TxFileManager();

            // Make sure we clear our cache entry first.
            Remove(url);

            string hash = CreateURLHash(url);

            description = description ?? Path.GetFileName(path);

            Debug.Assert(
                Regex.IsMatch(description, "^[A-Za-z0-9_.-]*$"),
                "description isn't as filesystem safe as we thought... (#1266)"
                );

            string fullName   = String.Format("{0}-{1}", hash, Path.GetFileName(description));
            string targetPath = Path.Combine(cachePath, fullName);

            // Purge hashes associated with the new file
            PurgeHashes(tx_file, targetPath);

            log.InfoFormat("Storing {0} in {1}", path, targetPath);

            if (move)
            {
                tx_file.Move(path, targetPath);
            }
            else
            {
                tx_file.Copy(path, targetPath, true);
            }

            // We've changed our cache, so signal that immediately.
            if (!cachedFiles?.ContainsKey(hash) ?? false)
            {
                cachedFiles?.Add(hash, targetPath);
            }

            return(targetPath);
        }
Пример #7
0
        /// <summary>
        /// Stores the results of a given URL in the cache.
        /// Description is adjusted to be filesystem-safe and then appended to the file hash when saving.
        /// If not present, the filename will be used.
        /// If `move` is true, then the file will be moved; otherwise, it will be copied.
        ///
        /// Returns a path to the newly cached file.
        ///
        /// This method is filesystem transaction aware.
        /// </summary>
        public string Store(Uri url, string path, string description = null, bool move = false)
        {
            log.DebugFormat("Storing {0}", url);

            // Make sure we clear our cache entry first.
            Remove(url);

            string hash = CreateURLHash(url);

            if (description != null)
            {
                // Versions can contain ALL SORTS OF WACKY THINGS! Colons, friggin newlines,
                // slashes, and heaven knows what use mod authors try to smoosh into them.
                // We'll reduce this down to "friendly" characters, replacing everything else with
                // dashes. This doesn't change look-ups, as we use the hash prefix for that.

                description = Regex.Replace(description, "[^A-Za-z0-9_.-]", "-");
            }

            description = description ?? Path.GetFileName(path);

            string fullName   = String.Format("{0}-{1}", hash, Path.GetFileName(description));
            string targetPath = Path.Combine(cachePath, fullName);

            log.DebugFormat("Storing {0} in {1}", path, targetPath);

            if (move)
            {
                tx_file.Move(path, targetPath);
            }
            else
            {
                tx_file.Copy(path, targetPath, true);
            }

            return(targetPath);
        }
Пример #8
0
        static void RunStressTest()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            {
                // Pre-test checks
                string       tempDir;
                IFileManager fm = new TxFileManager();
                using (TransactionScope s1 = new TransactionScope())
                {
                    tempDir = (new DirectoryInfo(fm.CreateTempDirectory())).Parent.FullName;
                    Console.WriteLine("Temp path: " + tempDir);
                }

                string[] directories = Directory.GetDirectories(tempDir);
                string[] files       = Directory.GetFiles(tempDir);
                if (directories.Length > 0 || files.Length > 0)
                {
                    Console.WriteLine(string.Format("ERROR  Please ensure temp path {0} has no children before running this test.", tempDir));
                    return;
                }
            }

            // Start each test in its own thread and repeat for a few interations
            const int    numThreads = 10;
            const int    iterations = 250;
            const string text       = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

            long count = 0;

            IList <Thread> threads = new List <Thread>();

            for (int i = 0; i < numThreads; i++)
            {
                Thread t = new Thread(() =>
                {
                    IFileManager fm = new TxFileManager();
                    for (int j = 0; j < iterations; j++)
                    {
                        using (TransactionScope s1 = new TransactionScope())
                        {
                            TransactionOptions to = new TransactionOptions();
                            to.Timeout            = TimeSpan.FromMinutes(30);

                            long myCount = Interlocked.Increment(ref count);
                            if (myCount % 250 == 0)
                            {
                                Console.WriteLine(myCount + " (" + myCount * 100 / (numThreads * iterations) + " %)");
                            }

                            string f1 = fm.CreateTempFileName();
                            string f2 = fm.CreateTempFileName();
                            string d1 = fm.CreateTempDirectory();

                            if (i % 100 == 0)
                            {
                                Console.WriteLine(i);
                            }

                            fm.AppendAllText(f1, text);
                            fm.Copy(f1, f2, false);

                            fm.CreateDirectory(d1);
                            fm.Delete(f2);
                            fm.DeleteDirectory(d1);
                            bool b1   = fm.DirectoryExists(d1);
                            bool b2   = fm.FileExists(f1);
                            string f3 = fm.CreateTempFileName();
                            fm.Move(f1, f3);
                            string f4 = fm.CreateTempFileName();
                            fm.Snapshot(f4);
                            fm.WriteAllBytes(f4, new byte[] { 64, 65 });
                            string f5 = fm.CreateTempFileName();
                            fm.WriteAllText(f5, text);

                            fm.Delete(f1);
                            fm.Delete(f2);
                            fm.Delete(f3);
                            fm.Delete(f4);
                            fm.Delete(f5);
                            fm.DeleteDirectory(d1);
                            s1.Complete();
                        }
                    }
                });

                threads.Add(t);
            }

            foreach (Thread t in threads)
            {
                t.Start();
            }

            Console.WriteLine("All threads started.");

            foreach (Thread t in threads)
            {
                t.Join();
            }

            sw.Stop();

            Console.WriteLine("All threads joined. Elapsed: {0}.", sw.ElapsedMilliseconds);
        }
Пример #9
0
        // Moves files from AppData to current folder and vice versa
        // This is based off of the array below
        // Index 0 = Current Path
        // Index 1 = Default Path

        // Mode 0 = Current path -> Default Path (Turning off)
        // Mode 1 = Default path -> Current Path (Turning on)
        private void portibleModeToggle(int mode)
        {
            String[,] folderArray = new string[, ] {
                { Path.Combine(Paths.exeFolder, "config"), Paths.defaultConfigPath }, { Path.Combine(Paths.exeFolder, "Shortcuts"), Paths.defaultShortcutsPath }
            };
            String[,] fileArray = new string[, ] {
                { Path.Combine(Paths.exeFolder, "Taskbar Groups Background.exe"), Paths.defaultBackgroundPath }, { Path.Combine(Paths.exeFolder, "Settings.xml"), Settings.defaultSettingsPath }
            };

            int int1;
            int int2;

            if (mode == 0)
            {
                int1 = 0;
                int2 = 1;
            }
            else
            {
                int1 = 1;
                int2 = 0;
            }

            try
            {
                // Kill off the background process
                Process[] pname = Process.GetProcessesByName(Path.GetFileNameWithoutExtension("Taskbar Groups Background"));
                if (pname.Length != 0)
                {
                    pname[0].Kill();
                }

                IFileManager fm = new TxFileManager();
                using (TransactionScope scope1 = new TransactionScope())
                {
                    Settings.settingInfo.portableMode = true;
                    Settings.writeXML();

                    for (int i = 0; i < folderArray.Length / 2; i++)
                    {
                        if (fm.DirectoryExists(folderArray[i, int1]))
                        {
                            // Need to use another method to move from one partition to another
                            Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(folderArray[i, int1], folderArray[i, int2]);

                            // Folders may still reside after being moved
                            if (fm.DirectoryExists(folderArray[i, int1]) && !Directory.EnumerateFileSystemEntries(folderArray[i, int1]).Any())
                            {
                                fm.DeleteDirectory(folderArray[i, int1]);
                            }
                        }
                        else
                        {
                            fm.CreateDirectory(folderArray[i, int2]);
                        }
                    }

                    for (int i = 0; i < fileArray.Length / 2; i++)
                    {
                        if (fm.FileExists(fileArray[i, int1]))
                        {
                            fm.Move(fileArray[i, int1], fileArray[i, int2]);
                        }
                    }

                    if (mode == 0)
                    {
                        Paths.ConfigPath            = Paths.defaultConfigPath;
                        Paths.ShortcutsPath         = Paths.defaultShortcutsPath;
                        Paths.BackgroundApplication = Paths.defaultBackgroundPath;
                        Settings.settingsPath       = Settings.defaultSettingsPath;

                        portabilityButton.Tag   = "n";
                        portabilityButton.Image = Properties.Resources.toggleOff;
                    }
                    else
                    {
                        Paths.ConfigPath    = folderArray[0, 0];
                        Paths.ShortcutsPath = folderArray[1, 0];

                        Paths.BackgroundApplication = fileArray[0, 0];
                        Settings.settingsPath       = fileArray[1, 0];

                        portabilityButton.Tag   = "y";
                        portabilityButton.Image = Properties.Resources.toggleOn;
                    }

                    changeAllShortcuts();


                    scope1.Complete();

                    MessageBox.Show("File moving done!");
                }
            }
            catch (IOException e) {
                MessageBox.Show("The application does not have access to this directory!\r\n\r\nError: " + e.Message);
            }
        }