/// <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);
            }
        }
Beispiel #2
0
        public ScriptUI(Model model, string name, string filepath, Guid context_id)
        {
            InitializeComponent();
            DockControl = new DockControl(this, $"Script-{context_id}")
            {
                ShowTitle      = false,
                TabText        = name,
                TabToolTip     = filepath,
                TabCMenu       = TabCMenu(),
                DestroyOnClose = true,
            };
            LastUpdateTime  = TimeSpan.Zero;
            Context         = new Context(model, name, context_id);
            LdrAutoComplete = new View3d.AutoComplete();
            Filepath        = filepath;
            Editor          = m_editor;

            Render              = Command.Create(this, RenderInternal);
            SaveScript          = Command.Create(this, SaveScriptInternal);
            RemoveObjects       = Command.Create(this, RemoveObjectsInternal);
            CloseScript         = Command.Create(this, CloseScriptInternal);
            IndentSelection     = Command.Create(this, IndentSelectionInternal);
            CommentOutSelection = Command.Create(this, CommentOutSelectionInternal);
            UncommentSelection  = Command.Create(this, UncommentSelectionInternal);

            // If the temporary script exists, load it
            if (Path_.FileExists(Filepath))
            {
                LoadFile();
            }

            DataContext = this;
        }
Beispiel #3
0
 /// <summary>Validate the current options</summary>
 public override Exception Validate()
 {
     return
         (m_ass.Length == 0 ? new Exception($"Assembly parameter not given") :
          !Path_.FileExists(m_ass) ? new FileNotFoundException($"Assembly file '{m_ass}' not found") :
          null);
 }
        /// <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));
            }
        }
Beispiel #5
0
        [Test] public void TestExpandHtml()
        {
            var filepath = Path.GetTempFileName();
            var data     = Encoding.UTF8.GetBytes("include file\r\ntext data");

            // Shared read access doesn't work for DeleteOnClose files so might as well just use a normal file and delete on clean up
            using (var file = new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read))
                file.Write(data, 0, data.Length);

            using (Scope.Create(null, () => Path_.DelFile(filepath)))
            {
                var template =
                    $"<root>\r\n" +
                    $"\t\t <!--#include file=\"{filepath}\"-->\r\n" +
                    $"<!--#var name=\"MyVar\" file=\"{filepath}\" value=\"text\\s+(?<value>\\w+)\"-->\r\n" +
                    $"  <!--#value name=\"MyVar\"-->\r\n" +
                    $"    <!--#value name=\"MyVar\"-->\r\n" +
                    $"</root>\r\n";
                const string result =
                    "<root>\r\n" +
                    "\t\t include file\r\n" +
                    "\t\t text data\r\n" +
                    "\r\n" +
                    "  data\r\n" +
                    "    data\r\n" +
                    "</root>\r\n";
                var r = Expand.Html(new StringSrc(template), Environment.CurrentDirectory);
                Assert.Equal(result, r);
            }
        }
Beispiel #6
0
        public void RelativePaths()
        {
            // Note: since this test runs for netcoreapp3.1 and netstandard2.0 it effectively
            // ensures consistent behaviour between my implementation and the the .net core one.
            string rel;

            rel = Path_.RelativePath(@"A:\aaa\eee\fff\", @"A:\aaa\BBB\ccc\ddd");
            Assert.Equal(rel, @"..\..\BBB\ccc\ddd");

            rel = Path_.RelativePath(@"A:\aaa\eee\fff\", @"A:\aaa\bbb\..\..\ddd");
            Assert.Equal(rel, @"..\..\..\ddd");

            rel = Path_.RelativePath(@"A:\aaa\eee\fff\", @"B:\AAA\BBB\CCC\DDD");
            Assert.Equal(rel, @"B:\AAA\BBB\CCC\DDD");

            rel = Path_.RelativePath(@"A:\aaa\eee\fff", @"A:\aaa\");
            Assert.Equal(rel, @"..\..");

            rel = Path_.RelativePath(@"A:\aAa\eee\fff", @"A:\AaA\BbB\");
            Assert.Equal(rel, @"..\..\BbB\");

            rel = Path_.RelativePath(@"A:\aAa", @"A:\AaA\BbB\CcC");
            Assert.Equal(rel, @"BbB\CcC");

            rel = Path_.RelativePath(@"A:\aAa\Part", @"A:\AaA\Partial\CcC");
            Assert.Equal(rel, @"..\Partial\CcC");
        }
Beispiel #7
0
        public RylobotModel(Robot robot)
        {
            m_sym_cache = new Cache <string, Symbol> {
                ThreadSafe = true, Mode = CacheMode.StandardCache
            };
            Robot = robot;

            var settings_filepath = Util.ResolveAppDataPath("Rylogic", "Rylobot", "Settings.xml");

            Settings = new Settings(settings_filepath)
            {
                AutoSaveOnChanges = true
            };

            // Ensure the instrument settings directory exists
            if (!Path_.DirExists(Settings.General.InstrumentSettingsDir))
            {
                Directory.CreateDirectory(Settings.General.InstrumentSettingsDir);
            }

            // Create the account
            Acct = new Account(this, Robot.Account);

            // Create the instrument
            Instrument = new Instrument(this);

            // Create a strategy
            Strategy = new StrategyPotLuck(this);

            // ToDo:
            // Restore SnR levels + other indicators
        }
Beispiel #8
0
        /// <summary>Load the keys data for the given username and password</summary>
        private EResult GetKeys(out XElement keys)
        {
            keys = null;

            // Get the key file name. This is an encrypted XML file
            if (!Path_.FileExists(KeysFilepath))
            {
                return(EResult.NotFound);
            }

            // Read the file contents into memory and decrypt it
            try
            {
                // This code throw a CryptographicException when the 'User' has an incorrect password.
                // This is not an error, it's just that CrytographicException are not disabled by default
                // in the debugger exception settings.
                var keys_xml = string.Empty;
                using (var fs = new FileStream(KeysFilepath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    using (var cs = new CryptoStream(fs, Decryptor, CryptoStreamMode.Read))
                        using (var sr = new StreamReader(cs))
                            keys_xml = sr.ReadToEnd();

                keys = XElement.Parse(keys_xml, LoadOptions.None);
                return(EResult.Success);
            }
            catch
            {
                // If the xml is not valid, assume bad password
                return(EResult.BadPassword);
            }
        }
Beispiel #9
0
 public static void SaveToFile(Path_ p)
 {
     using (StreamWriter writer = new StreamWriter("output.txt"))
     {
         foreach (Point3D point in p.Path) writer.WriteLine("{0} {1} {2}", point.X, point.Y, point.Z);
     }
 }
Beispiel #10
0
        /// <summary>Update the enabled state of UI elements</summary>
        private void UpdateUI(object sender = null, EventArgs args = null)
        {
            m_btn_range_to_start.Enabled = m_radio_range.Checked;
            m_btn_range_to_end.Enabled   = m_radio_range.Checked;
            m_tb_range_min.Enabled       = m_radio_range.Checked;
            m_tb_range_max.Enabled       = m_radio_range.Checked;

            var status = string.Empty;

            for (;;)
            {
                if (!Path_.IsValidFilepath(OutputFilepath, false))
                {
                    status = "Invalid export file path";
                    break;
                }
                if (ByteRange.Count <= 0)
                {
                    status = "Invalid export data range";
                    break;
                }
                break;
            }
            m_lbl_status.Text      = status;
            m_lbl_status.ForeColor = Color.DarkRed;
            m_btn_ok.Enabled       = !status.HasValue();
        }
Beispiel #11
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);
        }
Beispiel #12
0
        /// <summary>Called when a new user account has been assigned</summary>
        private void HandleAcctChanged(object sender = null, EventArgs e = null)
        {
            // Ensure closed
            Util.Dispose(ref m_db);

            // If there is no account id, don't open a database
            if (Model == null || !Model.Acct.AccountId.HasValue())
            {
                return;
            }

            // Open a database of the trade history and other user account related info
            var filepath = Path_.CombinePath(Settings.General.AcctDataCacheDir, "Acct_{0}.db".Fmt(Model.Acct.AccountId));

            m_db = new Sqlite.Database(filepath);

            // Tweak some DB settings for performance
            m_db.Execute(Sqlite.Sql("PRAGMA synchronous = OFF"));
            m_db.Execute(Sqlite.Sql("PRAGMA journal_mode = MEMORY"));

            // Ensure the table of trades exists
            var sql = Sqlite.Sql("create table if not exists ", Table.TradeHistory, " (\n",
                                 "[", nameof(Trade.Id), "] text primary key,\n",
                                 "[", nameof(Trade.SymbolCode), "] text)");

            m_db.Execute(sql);

            // Ensure the table of orders exists
            sql = Sqlite.Sql("create table if not exists ", Table.Orders, " (\n",
                             "[", nameof(Order.Id), "] integer primary key,\n",
                             "[", ("TradeId"), "] text,\n",
                             "[", nameof(Order.SymbolCode), "] text,\n",
                             "[", nameof(Order.TradeType), "] integer)");
            m_db.Execute(sql);
        }
Beispiel #13
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>Return the child nodes for 'node'</summary>
        private static IEnumerable <TreeNode> GetChildNodes(TreeNode node)
        {
            var path = new Path(node.FullPath);

            return(Path_.EnumFileSystem(path.Name, SearchOption.TopDirectoryOnly)
                   .Where(fi => fi.IsDirectory())
                   .Select(fi => new TreeNode(fi.Name, node.TriState)));
        }
Beispiel #15
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}");
                    }
                }
            }
        }
Beispiel #16
0
        // Notes:
        // This is a base class for an entry signal trigger.
        // Derived types use various methods to guess where price is going.
        // Derived types add 'Feature' objects to the 'Features' collection, these are basically
        // values in the range [-1.0,+1.0] where -1.0 = strong sell, +1.0 = strong buy.

        public Predictor(Rylobot bot, string name)
        {
            Bot          = bot;
            Name         = name;
            CurrentIndex = 0;
            Instrument   = new Instrument(bot);
            Features     = new List <Feature>();
            LogFilepath  = Path_.CombinePath(@"P:\projects\Tradee\Rylobot\Rylobot\net\Data", "{0}.predictions.csv".Fmt(name));
        }
Beispiel #17
0
        /// <summary>Upload a local file to the host. The remote file will be named 'remote_filename' on the host</summary>
        public void Upload(string local_filepath, string remote_filename, ResumeBehaviour resume = ResumeBehaviour.DontResume)
        {
            Trace(string.Format("Uploading: {0} to {1}/{2}/{3}", local_filepath, Settings.RemoteHost, Settings.RemotePath, remote_filename));
            Reply reply;

            // Check the local filepath exists first
            if (!Path_.FileExists(local_filepath))
            {
                throw new FileNotFoundException("Upload failed", local_filepath);
            }

            // Upload the file
            using (var input = new FileStream(local_filepath, FileMode.Open, FileAccess.Read))
            {
                if (resume != ResumeBehaviour.DontResume)
                {
                    // Some servers may not support resumed uploading.
                    long offset = RemoteFileSize(remote_filename);
                    if (SendCommand("REST " + offset).Code == Status.PendingFurtherInfo)
                    {
                        Trace("Resuming file upload from offset " + offset);
                        input.Seek(offset, SeekOrigin.Begin);
                    }
                    else if (resume == ResumeBehaviour.Resume)
                    {
                        // The caller specifically wanted resuming but it's
                        // not supported, throw so they can choose what to do.
                        Trace("Resuming not supported. Aborting.");
                        throw new NotSupportedException("Resumed upload not supported by server");
                    }
                    else
                    {
                        Trace("Resuming not supported. Restarting.");
                        input.Seek(0, SeekOrigin.Begin);
                    }
                }

                // Store the file
                reply = SendCommand("STOR " + remote_filename);
                if (reply.Code != Status.DataConnectionAlreadyOpen && reply.Code != Status.DataConnectionOpenning)
                {
                    throw new IOException(reply.Message);
                }

                // Write the file to the data channel
                using (BinaryWriter w = new BinaryWriter(ConnectDataStream()))
                    input.CopyTo(w.BaseStream);
            }

            // Confirm done
            reply = ReadReply();
            if (reply.Code != Status.DataConnectionClosing && reply.Code != Status.RequestedActionOkay)
            {
                throw new IOException(reply.Message);
            }
        }
Beispiel #18
0
        public History(MainModel model)
        {
            Model = model;

            // Ensure the acct data cache directory exists
            if (!Path_.DirExists(Model.Settings.General.AcctDataCacheDir))
            {
                Directory.CreateDirectory(Model.Settings.General.AcctDataCacheDir);
            }
        }
        /// <summary></summary>
        private void InitJournalFiles()
        {
            // Parse all of the available journal files, in order
            var journal_files = Path_.EnumFileSystem(Settings.Instance.JournalFilesDir, SearchOption.TopDirectoryOnly, JournalRegex).OrderBy(x => x.Name);

            foreach (var file in journal_files)
            {
                JournalFilepath = file.FullName;
                JournalOffset   = Parse(JournalFilepath, 0L);
            }
        }
Beispiel #20
0
 // Example Use:
 //	<TextBlock>
 //		<TextBlock.Text>
 //			<MultiBinding Converter="{conv:RelativePath}">
 //				<Binding Path="FullPath" />
 //				<Binding Path="BasePath" />
 //			</MultiBinding>
 //		</TextBlock.Text>
 //	</TextBlock>
 public object?Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
 {
     if (!(values[0] is string full_path))
     {
         return(null);
     }
     if (!(values[1] is string base_path))
     {
         return(null);
     }
     return(Path_.RelativePath(base_path, full_path));
 }
Beispiel #21
0
 public object?Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     if (!(value is string path))
     {
         return(value);
     }
     if (!Path_.IsValidFilepath(path, false))
     {
         return(value);
     }
     return(Path_.FileName(path));
 }
Beispiel #22
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();
        }
Beispiel #23
0
            public WatchedDir(string dirpath, ChangedHandler onchange, int id, object?ctx)
            {
                m_files    = new Dictionary <string, WatchedFile>();
                Path       = dirpath;
                m_onchange = onchange;
                m_ctx      = ctx;
                Id         = id;

                // Get the files in the directory and create a watcher for each
                var files = Path_.EnumFileSystem(Path, SearchOption.TopDirectoryOnly, exclude: FileAttributes.Hidden | FileAttributes.Directory).ToList();

                m_files = files.ToDictionary(x => x.FullName.ToLowerInvariant(), x => new WatchedFile(x.FullName, onchange, id, ctx));
            }
Beispiel #24
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);
        }
Beispiel #25
0
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (!(value is string path))
            {
                return(new ValidationResult(false, $"Value '{value}' is not a string"));
            }

            if (!Path_.IsValidFilepath(path, true))
            {
                return(new ValidationResult(false, $"Path '{path}' is not a valid or is a relative path"));
            }

            return(ValidationResult.ValidResult);
        }
Beispiel #26
0
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (!(value is string path))
            {
                return(new ValidationResult(false, $"Value '{value}' is not a string"));
            }

            if (!Path_.PathExists(path))
            {
                return(new ValidationResult(false, $"Path '{path}' does not exist"));
            }

            return(ValidationResult.ValidResult);
        }
Beispiel #27
0
        public StrategyDataCollector(Rylobot bot)
            : base(bot, "StrategyDataCollector")
        {
            NNet = new PredictorNeuralNet(bot);

            WindowSize   = 20;
            RtRThreshold = 2.0;

            // Generate the training and test data
            var outdir = @"P:\projects\Tradee\Rylobot\Rylobot\net\Data";

            m_training = new StreamWriter(Path_.CombinePath(outdir, "training.txt"));
            m_testing  = new StreamWriter(Path_.CombinePath(outdir, "testing.txt"));
        }
        /// <summary>Called after 'path' has been removed from the collection</summary>
        private void HandlePathRemoved(Path path)
        {
            // Remember, 'path' may not have been in the collection, but may be a child
            // of a path that is in the collection.
            var p     = new StringBuilder();
            var parts = path.Name.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);

            // Look for a path that is an ancestral parent of 'path'
            var part_idx = 0;

            for (; part_idx != parts.Length; ++part_idx)
            {
                p.Append(parts[part_idx]).Append("\\");

                // If the parent path is in the collection, we need to replace
                // it with its children except for 'p.Append(parts[i+1])'
                var idx = Paths.BinarySearch(p.ToString(), Path.Compare);
                if (idx >= 0)
                {
                    break;
                }
            }

            // If a parent is found, we need to add child paths for the ancestral siblings of 'path'
            if (part_idx != parts.Length)
            {
                // Remove the parent path
                var idx = Paths.BinarySearch(p.ToString(), Path.Compare);
                Paths.RemoveAt(idx);

                // Add the child paths for the ancestral siblings of 'path'
                for (++part_idx; part_idx != parts.Length; ++part_idx)
                {
                    var siblings = Path_.EnumFileSystem(path.Text.Substring(0, p.Length), SearchOption.TopDirectoryOnly).Where(x => x.IsDirectory());
                    foreach (var sib in siblings)
                    {
                        if (string.CompareOrdinal(parts[part_idx], sib.Name.ToLowerInvariant()) == 0)
                        {
                            continue;
                        }
                        Paths.AddOrdered(sib.FullName, Path.Compare);
                    }
                    p.Append(parts[part_idx]).Append("\\");
                }
            }

            // Update the check boxes
            UpdateTree();
        }
Beispiel #29
0
        /// <summary>Load an instance of each type that implements the interface 'TInterface' in 'ass'</summary>
        public Plugins <TInterface> Load(Assembly ass, object[]?args = null, Func <Type, object[]?, TInterface>?factory = null)
        {
            foreach (var type in ass.GetExportedTypes())
            {
                var attr = type.FindAttribute <PluginAttribute>(false);
                if (attr == null || attr.Interface != typeof(TInterface))
                {
                    continue;
                }

                // Return the type that implements the interface
                Load(Path_.FileTitle(ass.Location), type, args, factory);
            }
            return(this);
        }
Beispiel #30
0
        /// <summary>Enumerate the types that implement the interface 'TInterface'</summary>
        public static IEnumerable <PluginFile> Enumerate(string directory, SearchOption search = SearchOption.TopDirectoryOnly, string regex_filter = DefaultRegexPattern)
        {
            // Build a list of assemblies to check
            var filedata = Path_.EnumFileSystem(directory, search, regex_filter, exclude: FileAttributes.Directory).ToList();

            // Load each assembly and look for types that are flagged with the Plugin attribute
            foreach (var fd in filedata)
            {
                var ass = Assembly.LoadFile(fd.FullName);
                foreach (var plugin in Enumerate(ass))
                {
                    yield return(plugin);
                }
            }
        }
Beispiel #31
0
        /// <summary>Enumerate the types that implement the interface 'TInterface'</summary>
        public static IEnumerable <PluginFile> Enumerate(Assembly ass)
        {
            foreach (var type in ass.GetExportedTypes())
            {
                var attr = type.FindAttribute <PluginAttribute>(false);
                if (attr == null || attr.Interface != typeof(TInterface))
                {
                    continue;
                }

                // Return the type that implements the interface
                var fd = new FileInfo(ass.Location);
                yield return(new PluginFile(Path_.FileTitle(fd.Name), type, ass, fd, attr.Unique));
            }
        }
Beispiel #32
0
    public static Path_ ReadFromFile(string fileName)
    {
        using (StreamReader reader = new StreamReader(fileName))
        {
            Path_ path = new Path_();
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                string[] nums = line.Split(' ');
                path.AddPointToPath(new Point3D(double.Parse(nums[0]), double.Parse(nums[1]), double.Parse(nums[2])));
            }

            return path;
        }
    }