Пример #1
0
        /// <summary>Generate a filepath for the given pair name</summary>
        public static string DBFilePath(string exchange_name, string pair_name)
        {
            var dbpath = Misc.ResolveUserPath("PriceData", $"{Path_.SanitiseFileName(pair_name)} - {Path_.SanitiseFileName(exchange_name)}.db");

            Path_.CreateDirs(Path_.Directory(dbpath));
            return(dbpath);
        }
Пример #2
0
        /// <summary>Handle the Load button</summary>
        private void HandleLoad(object sender, RoutedEventArgs e)
        {
            // Prompt for a settings file
            var fd = new OpenFileDialog
            {
                Title            = "Choose a Settings file to load",
                Filter           = Constants.SettingsFileFilter,
                CheckFileExists  = true,
                Multiselect      = false,
                InitialDirectory = Path_.Directory(m_settings.Filepath)
            };

            if (fd.ShowDialog(this) != true)
            {
                return;
            }
            var filepath = fd.FileName;

            try
            {
                m_settings.Filepath = filepath;
                m_settings.Load(filepath);
            }
            catch (Exception ex)
            {
                m_report.ErrorPopup($"Failed to open settings file {filepath} due to an error.", ex);
            }
        }
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        /// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param>
        /// <param name="progress">A provider for progress updates.</param>
        /// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns>
        protected override void Initialize()
        {
            var root = Path_.Directory(Assembly.GetExecutingAssembly().Location);

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            Assembly?CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
            {
                var path = Path_.CombinePath(root, new AssemblyName(args.Name).Name + ".dll");

                if (!Path_.FileExists(path))
                {
                    return(null);
                }
                return(Assembly.LoadFrom(path));
            }

            // When initialized asynchronously, the current thread may be a background thread at this point.
            // Do any initialization that requires the UI thread after switching to the UI thread.
            //await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
            base.Initialize();

            // Add our command handlers for menu
            if (GetService <IMenuCommandService>() is OleMenuCommandService mcs)
            {
                mcs.AddCommand(new AlignMenuCommand(this));
                mcs.AddCommand(new UnalignMenuCommand(this));
            }
        }
Пример #4
0
        /// <summary>Handle the Reset to Defaults button</summary>
        private void HandleSaveAs(object sender, RoutedEventArgs e)
        {
            // Prompt for where to save the settings
            var fd = new SaveFileDialog
            {
                Title            = "Save current Settings",
                Filter           = Constants.SettingsFileFilter,
                InitialDirectory = Path_.Directory(m_settings.Filepath)
            };

            if (fd.ShowDialog(this) != true)
            {
                return;
            }
            var filepath = fd.FileName;

            try
            {
                m_settings.Filepath = filepath;
                m_settings.Save();
            }
            catch (Exception ex)
            {
                m_report.ErrorPopup($"Failed to save settings file {filepath} due to an error.", ex);
            }
        }
Пример #5
0
        /// <summary>Does the work of finding and identifying duplicates</summary>
        private void FindDuplicates(ProgressForm dlg, object ctx, ProgressForm.Progress progress)         // worker thread context
        {
            // Build a map of file data
            var dir = string.Empty;

            foreach (var path in Settings.SearchPaths)
            {
                if (dlg.CancelPending)
                {
                    break;
                }
                foreach (var fi in Path_.EnumFileSystem(path, search_flags:SearchOption.AllDirectories, exclude:FileAttributes.Directory).Cast <System.IO.FileInfo>())
                {
                    if (dlg.CancelPending)
                    {
                        break;
                    }

                    // Report progress whenever the directory changes
                    var d = Path_.Directory(fi.FullName) ?? string.Empty;
                    if (d != dir)
                    {
                        dir = d;
                        progress(new ProgressForm.UserState {
                            Description = $"Scanning files...\r\n{dir}"
                        });
                    }

                    try
                    {
                        // Create file info for the file and look for a duplicate
                        var      finfo    = new FileInfo(fi);
                        FileInfo existing = FInfoMap.TryGetValue(finfo.Key, out existing) ? existing : null;
                        if (existing != null)
                        {
                            Dispatcher.Invoke(() =>
                            {
                                existing.Duplicates.Add(finfo);
                                var idx = Duplicates.BinarySearch(existing, FileInfo.Compare);
                                if (idx < 0)
                                {
                                    Duplicates.Insert(~idx, existing);
                                }
                            });
                        }
                        else
                        {
                            FInfoMap.Add(finfo.Key, finfo);
                        }
                    }
                    catch (Exception ex)
                    {
                        Errors.Add($"Failed to add {fi.FullName} to the map. {ex.Message}");
                    }
                }
            }
        }
Пример #6
0
        public History(string root_directory)
        {
            var filepath = Path.Combine(root_directory, "fronius.db");

            Path_.CreateDirs(Path_.Directory(filepath));

            var connection_string = $"Data Source={filepath};Version=3;journal mode=Memory;synchronous=Off";

            DB = new SQLiteConnection(connection_string);

            InitDBTables();
        }
Пример #7
0
        /// <summary>Write this string to a file</summary>
        public static void ToFile(this string str, string filepath, bool append = false, bool create_dir_if_necessary = true)
        {
            // Ensure the directory exists
            var dir = Path_.Directory(filepath);

            if (create_dir_if_necessary && !Path_.DirExists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            using (var f = new StreamWriter(new FileStream(filepath, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.ReadWrite)))
                f.Write(str);
        }
Пример #8
0
        /// <summary>Save settings to AppData</summary>
        public override void SaveSettingsToStorage()
        {
            try
            {
                // Notify of saving
                Saving?.Invoke(this, EventArgs.Empty);

                // Ensure the directory in AppData exists
                Directory.CreateDirectory(Path_.Directory(SettingsFilepath));

                // Write the settings to XML
                var root = new XElement("root");
                root.Add2(nameof(Groups), nameof(AlignGroup), Groups, false);
                root.Add2(nameof(AlignStyle), AlignStyle, false);
                root.Save(SettingsFilepath);
            }
            catch { }             // Don't allow anything to throw from here, otherwise VS locks up... :-/
        }
Пример #9
0
        /// <summary>Write an ldr string to a file</summary>
        public static void Write(string ldr_str, string filepath, bool append = false)
        {
            try
            {
                // Ensure the directory exists
                var dir = Path_.Directory(filepath);
                if (!Path_.DirExists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                // Lock, then write the file
                using (Path_.LockFile(filepath))
                    using (var f = new StreamWriter(new FileStream(filepath, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read)))
                        f.Write(ldr_str);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Failed to write Ldr script to '{filepath}'. {ex.Message}");
            }
        }
Пример #10
0
 public History()
 {
     Path_.CreateDirs(Path_.Directory(Filepath));
     DB = new SQLiteConnection(DBConnectionString);
     InitDBTables();
 }
Пример #11
0
        /// <summary>
        /// Smart copy from 'src' to 'dst'. Loosely like XCopy.
        /// 'src' can be a single file, a comma separated list of files, or a directory<para/>
        /// 'dst' can be a
        /// if 'src' is a directory, </summary>
        public static void Copy(string src, string dst, bool overwrite = false, bool only_if_modified = false, bool ignore_non_existing = false, Action <string>?feedback = null, bool show_unchanged = false)
        {
            var src_is_dir = Path_.IsDirectory(src);
            var dst_is_dir = Path_.IsDirectory(dst) || dst.EndsWith("/") || dst.EndsWith("\\") || src_is_dir;

            // Find the names of the source files to copy
            var files = new List <string>();

            if (src_is_dir)
            {
                files = Path_.EnumFileSystem(src, SearchOption.AllDirectories).Select(x => x.FullName).ToList();
            }
            else if (Path_.FileExists(src))
            {
                files = new List <string>()
                {
                    src
                }
            }
            ;
            else if (src.Contains('*') || src.Contains('?'))
            {
                files = Path_.EnumFileSystem(src, SearchOption.AllDirectories, new Pattern(EPattern.Wildcard, src).RegexString).Select(x => x.FullName).ToList();
            }
            else if (!ignore_non_existing)
            {
                throw new FileNotFoundException($"'{src}' does not exist");
            }

            // If the 'src' represents multiple files, 'dst' must be a directory
            if (src_is_dir || files.Count > 1)
            {
                // if 'dst' doesn't exist, assume it's a directory
                if (!Path_.DirExists(dst))
                {
                    dst_is_dir = true;
                }

                // or if it does exist, check that it is actually a directory
                else if (!dst_is_dir)
                {
                    throw new FileNotFoundException($"'{dst}' is not a valid directory");
                }
            }

            // Ensure that 'dstdir' exists. (Canonicalise fixes the case where 'dst' is a drive, e.g. 'C:\')
            var dstdir = Path_.Canonicalise((dst_is_dir ? dst : Path_.Directory(dst)).TrimEnd('/', '\\'));

            if (!Path_.DirExists(dstdir))
            {
                Directory.CreateDirectory(dstdir);
            }

            // Copy the file(s) to 'dst'
            foreach (var srcfile in files)
            {
                // If 'dst' is a directory, use the same filename from 'srcfile'
                var dstfile = string.Empty;
                if (dst_is_dir)
                {
                    var spath = src_is_dir ? Path_.RelativePath(src, srcfile) : Path_.FileName(srcfile);
                    dstfile = Path_.CombinePath(dstdir, spath);
                }
                else
                {
                    dstfile = dst;
                }

                // If 'srcfile' is a directory, ensure the directory exists at the destination
                if (Path_.IsDirectory(srcfile))
                {
                    if (!dst_is_dir)
                    {
                        throw new Exception($"ERROR: {dst} is not a directory");
                    }

                    // Create the directory at the destination
                    if (!Path_.DirExists(dstfile))
                    {
                        System.IO.Directory.CreateDirectory(dstfile);
                    }
                    if (feedback != null)
                    {
                        feedback(srcfile + " --> " + dstfile);
                    }
                }
                else
                {
                    // Copy if modified or always based on the flag
                    if (only_if_modified && !Path_.DiffContent(srcfile, dstfile))
                    {
                        if (feedback != null && show_unchanged)
                        {
                            feedback(srcfile + " --> unchanged");
                        }
                        continue;
                    }

                    // Ensure the directory path exists
                    var d = Path_.Directory(dstfile);
                    var f = Path_.FileName(dstfile);
                    if (!Path_.DirExists(d))
                    {
                        System.IO.Directory.CreateDirectory(d);
                    }
                    if (feedback != null)
                    {
                        feedback(srcfile + " --> " + dstfile);
                    }
                    File.Copy(srcfile, dstfile, overwrite);
                }
            }
        }