private void GenerateTreeNodes(FolderStructure Folder, TreeViewItem rootNode)
 {
     Folder.Files.OrderBy(i => i.Key);
     foreach (KeyValuePair <string, bool> file in Folder.Files)
     {
         TreeViewItem newnode = new TreeViewItem
         {
             Header     = file.Key,
             FontWeight = FontWeights.Normal
         };
         if (file.Value)
         {
             newnode.Foreground = new SolidColorBrush(Colors.Red);
         }
         rootNode.Items.Add(newnode);
     }
     Folder.Subdirectories.OrderBy(i => i.Key);
     foreach (KeyValuePair <string, FolderStructure> subdir in Folder.Subdirectories)
     {
         TreeViewItem newnode = new TreeViewItem
         {
             Header     = subdir.Key,
             FontWeight = FontWeights.Normal
         };
         if (subdir.Value.Duplicate)
         {
             newnode.Foreground = new SolidColorBrush(Colors.Red);
         }
         rootNode.Items.Add(newnode);
         GenerateTreeNodes(subdir.Value, newnode);
     }
 }
Esempio n. 2
0
 internal ActivitySound(STFReader stf)
 {
     stf.MustMatchBlockStart();
     stf.ParseBlock(new STFReader.TokenProcessor[] {
         new STFReader.TokenProcessor("ortsactsoundfile", () =>
         {
             stf.MustMatchBlockStart();
             string soundFile = stf.ReadString();
             SoundFile        = Path.Combine(FolderStructure.RouteFromActivity(stf.FileName).SoundFile(soundFile));
             if (!EnumExtension.GetValue(stf.ReadString(), out OrtsActivitySoundFileType soundFileType))
             {
                 stf.StepBackOneItem();
                 STFException.TraceInformation(stf, "Skipped unknown activity sound file type " + stf.ReadString());
                 SoundFileType = OrtsActivitySoundFileType.None;
             }
             else
             {
                 SoundFileType = soundFileType;
             }
             stf.MustMatchBlockEnd();
         }),
         new STFReader.TokenProcessor("ortssoundlocation", () => {
             stf.MustMatchBlockStart();
             location = new WorldLocation(stf.ReadInt(null), stf.ReadInt(null),
                                          stf.ReadFloat(STFReader.Units.None, null), stf.ReadFloat(STFReader.Units.None, null), stf.ReadFloat(STFReader.Units.None, null));
             stf.MustMatchBlockEnd();
         }),
     });
Esempio n. 3
0
        internal Route(string path)
        {
            RouteFolder = FolderStructure.Route(path);
            string trkFilePath = RouteFolder.TrackFileName;

            try
            {
                RouteFile trkFile = new RouteFile(trkFilePath);
                Name        = trkFile.Route.Name;
                RouteID     = trkFile.Route.RouteID;
                Description = trkFile.Route.Description;
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch
#pragma warning restore CA1031 // Do not catch general exception types
            {
                Name = $"<{catalog.GetString("load error:")} {System.IO.Path.GetFileName(path)}>";
            }
            if (string.IsNullOrEmpty(Name))
            {
                Name = $"<{catalog.GetString("unnamed:")} {System.IO.Path.GetFileNameWithoutExtension(path)}>";
            }
            if (string.IsNullOrEmpty(Description))
            {
                Description = null;
            }
            Path = path;
        }
Esempio n. 4
0
        internal Route(string path)
        {
            RouteFolder = FolderStructure.Route(path);
            string trkFilePath = RouteFolder.TrackFileName;

            try
            {
                var trkFile = new RouteFile(trkFilePath);
                Name        = trkFile.Route.Name;
                RouteID     = trkFile.Route.RouteID;
                Description = trkFile.Route.Description;
            }
            catch
            {
                Name = $"<{catalog.GetString("load error:")} {System.IO.Path.GetFileName(path)}>";
            }
            if (string.IsNullOrEmpty(Name))
            {
                Name = $"<{catalog.GetString("unnamed:")} {System.IO.Path.GetFileNameWithoutExtension(path)}>";
            }
            if (string.IsNullOrEmpty(Description))
            {
                Description = null;
            }
            Path = path;
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            Console.WriteLine(args.Length);
            foreach (string arg in args)
            {
                Console.WriteLine($"\t{arg}");
            }

            //string structures = @"C:\Users\micha\Desktop\Tests\structures.xml";

            string target       = args[0];
            string structureKey = args[1];
            string structures   = args[2];

            Console.WriteLine(target);
            Console.WriteLine(structureKey);
            Console.WriteLine(structures);

            FolderStructure fs = ReadStructure(structures, structureKey);

            if (fs != null)
            {
                fs.CreateStructure(target);
            }
        }
Esempio n. 6
0
        protected override void AddReferencedFiles()
        {
            string routePath;
            string basePath;

            GetRouteAndBasePath(loadedFile, out routePath, out basePath);

            List <string> possiblePaths = new List <string>
            {
                Path.GetDirectoryName(loadedFile)
            };

            if (routePath != null)
            {
                possiblePaths.Add(Path.Combine(routePath, "SOUND"));
            }
            if (basePath != null)
            {
                possiblePaths.Add(Path.Combine(basePath, "SOUND"));
            }

            // Try to also load all sound files. This is tricky, because quite deep into the structure of a sms
            foreach (var group in sms.ScalabiltyGroups)
            {
                if (group.Streams == null)
                {
                    continue;
                }
                foreach (var stream in group.Streams)
                {
                    foreach (var trigger in stream.Triggers)
                    {
                        SoundPlayCommand playCommand = trigger.SoundCommand as SoundPlayCommand;
                        if (playCommand == null)
                        {
                            continue;
                        }
                        foreach (string file in playCommand.Files)
                        {
                            if (file == null)
                            {
                                Trace.TraceWarning("Missing well-defined file name in {0}\n", loadedFile);
                                continue;
                            }

                            //The file can be in multiple places
                            //Assume .wav file for now
                            var fullPath = FolderStructure.FindFileFromFolders(possiblePaths, file);
                            if (fullPath == null)
                            {
                                //apparently the file does not exist, but we want to make that known to the user, so we make a path anyway
                                fullPath = Path.Combine(possiblePaths[0], file);
                            }
                            AddAdditionalFileAction.Invoke(fullPath, new WavLoader());
                        }
                    }
                }
            }
        }
        public void GetFileHierarchyTest()
        {
            var folderStructure = new FolderStructure();
            var item            = folderStructure.GetFilesAndFolders(@"c:\temp\clienttools");

            Assert.IsNotNull(item);
            Assert.IsTrue(item.Files.Count > 0);

            Console.WriteLine("+" + item.DisplayName);
            WriteChildFiles(item, 1);
        }
Esempio n. 8
0
        internal Traffic(STFReader stf)
        {
            stf.MustMatchBlockStart();
            Name = stf.ReadString();
            stf.ParseBlock(new STFReader.TokenProcessor[] {
                new STFReader.TokenProcessor("service_definition", () => { Services.Add(new Services(stf)); }),
            });

            //            TrafficFile = new TrafficFile(FolderStructure.TrafficFile(Name));
            TrafficFile = new TrafficFile(FolderStructure.RouteFromActivity(stf.FileName).TrafficFile(Name));
        }
        public void GetFileFlatFolderTest()
        {
            var folderStructure = new FolderStructure(null);
            var item            = folderStructure.GetFilesAndFolders(@"c:\wwapps\wwclient", nonRecursive: true);

            Assert.IsNotNull(item);
            Assert.IsTrue(item.Files.Count > 0);

            Console.WriteLine("+" + item.DisplayName);
            WriteChildFiles(item, 1);
        }
        public static FolderStructure CountFilesModelsFolders(string folder)
        {
            FolderStructure OutputOfFolders = new FolderStructure();

            string[] directories          = Directory.GetDirectories(currentDir.ToString() + folder);
            int      fileDirectoriesCount = directories.Length;

            numOfFiles = 0;

            string[] arrayOfDirectoriesName = new string[fileDirectoriesCount];

            // Getting the names for the files//

            for (int numFolders = 0; numFolders < fileDirectoriesCount; numFolders++)
            {
                /*string folderName = directories[numFolders]; //This grabs path for file//
                 * string lastWord = folderName.Trim().Split('\\').LastOrDefault();
                 * string final = lastWord.Split('.').LastOrDefault();*/
                //All the above in one line ;P
                arrayOfDirectoriesName[numFolders] = directories[numFolders].Trim().Split('\\').LastOrDefault().Split('.').LastOrDefault();
                numOfFiles++;

                //Debug.WriteLine(final);
            }


            OutputOfFolders.arrayOfDirectoriesName = arrayOfDirectoriesName;
            string[] files     = Directory.GetFiles(currentDir.ToString() + folder);
            int      fileCount = Directory.GetFiles(currentDir.ToString() + folder).Length;

            OutputOfFolders.arrayOfModelsName   = new string[fileCount];
            OutputOfFolders.arrayOfModelsImages = new Image[fileCount];

            // Getting the names for the files//

            for (int numFiles = 0; numFiles < fileCount; numFiles++)
            {
                string fileName = files[numFiles]; //This grabs path for file//
                string lastWord = fileName.Trim().Split('\\').LastOrDefault();
                string final    = lastWord.Split('.').FirstOrDefault();

                OutputOfFolders.arrayOfModelsName[numFiles] = final;

                OutputOfFolders.arrayOfModelsImages[numFiles] = Image.FromFile(fileName);

                Debug.WriteLine(arrayOfOutputInfo[1]);
            }

            return(OutputOfFolders);
        }
        public void ListChangesRepoTest()
        {
            string path   = @"c:\projects2010\markdownmonster\markdownmonster";
            var    helper = new GitHelper();

            using (var repo = helper.OpenRepository(path))
            {
                Assert.IsNotNull(repo);

                var folder   = new FolderStructure();
                var pathItem = folder.GetFilesAndFolders(path);

                folder.UpdateGitFileStatus(pathItem);
            }
        }
Esempio n. 12
0
File: Import.cs Progetto: F-D-R/FDR
        private static void CopyFile(string destRoot, FileInfo file, FolderStructure destStruct, string dateFormat, int progressPercent)
        {
            var destfolder = GetAbsoluteDestFolder(destRoot, destStruct, file.CreationTime, dateFormat);

            if (!Directory.Exists(destfolder))
            {
                Directory.CreateDirectory(destfolder);
            }

            var dest = Path.Combine(destfolder, file.Name);

            Trace.WriteLine($"Copying {file.FullName} to {dest}");
            Common.Progress(progressPercent);
            file.CopyTo(dest);
        }
Esempio n. 13
0
        public static async Task <IEnumerable <Route> > GetRoutes(Folder folder, CancellationToken token)
        {
            if (null == folder)
            {
                throw new ArgumentNullException(nameof(folder));
            }

            using (SemaphoreSlim addItem = new SemaphoreSlim(1))
            {
                List <Route> result = new List <Route>();

                string routesDirectory = folder.ContentFolder.RoutesFolder;
                if (Directory.Exists(routesDirectory))
                {
                    ActionBlock <string> actionBlock = new ActionBlock <string>
                                                           (async routeDirectory =>
                    {
                        if (FolderStructure.Route(routeDirectory).IsValid)
                        {
                            try
                            {
                                Route route = new Route(routeDirectory);
                                await addItem.WaitAsync(token).ConfigureAwait(false);
                                result.Add(route);
                            }
                            finally
                            {
                                addItem.Release();
                            }
                        }
                    },
                                                           new ExecutionDataflowBlockOptions {
                        MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = token
                    });

                    foreach (string routeDirectory in Directory.EnumerateDirectories(routesDirectory))
                    {
                        await actionBlock.SendAsync(routeDirectory).ConfigureAwait(false);
                    }

                    actionBlock.Complete();
                    await actionBlock.Completion.ConfigureAwait(false);
                }

                return(result);
            }
        }
        private void BrowseFolder2_Click(object sender, RoutedEventArgs e)
        {
            CommonOpenFileDialog dialog = new CommonOpenFileDialog
            {
                IsFolderPicker = true
            };

            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                URLFolder2.Text = dialog.FileName;
                Folder2         = new FolderStructure
                {
                    Name       = dialog.FileName.Split('\\').Last(),
                    FolderPath = dialog.FileName
                };
            }
        }
Esempio n. 15
0
        private protected void OrtsActivitySoundProcessor(STFReader stf)
        {
            stf.MustMatchBlockStart();
            string soundFile = stf.ReadString();

            SoundFile = FolderStructure.RouteFromActivity(stf.FileName).SoundFile(soundFile);
            if (!EnumExtension.GetValue(stf.ReadString(), out OrtsActivitySoundFileType soundFileType))
            {
                stf.StepBackOneItem();
                STFException.TraceInformation(stf, "Skipped unknown activity sound file type " + stf.ReadString());
                SoundFileType = OrtsActivitySoundFileType.None;
            }
            else
            {
                SoundFileType = soundFileType;
            }
            stf.MustMatchBlockEnd();
        }
        public void MyTestMethod()
        {
            var folderStructure = new FolderStructure(null);
            var item            = folderStructure.GetFilesAndFolders(@"c:\wwapps\wwclient", nonRecursive: false);

            Assert.IsNotNull(item);
            Assert.IsTrue(item.Files.Count > 0);

            Console.WriteLine("+" + item.DisplayName);
            WriteChildFiles(item, 1);

            var pi = folderStructure.FindPathItemByFilename(item, @"c:\wwapps\wwclient\console\wc.ico");

            Assert.IsNotNull(pi);

            Console.WriteLine(pi);
            Console.WriteLine(pi.Parent);
            Console.WriteLine(pi.Parent.Parent);
        }
Esempio n. 17
0
        internal async Task LoadTrackData(bool?useMetricUnits, CancellationToken cancellationToken)
        {
            List <Task> loadTasks = new List <Task>();

            FolderStructure.ContentFolder.RouteFolder routeFolder = FolderStructure.Route(routePath);
            RouteFile routeFile = new RouteFile(routeFolder.TrackFileName);

            RouteName      = routeFile.Route.Name;
            UseMetricUnits = useMetricUnits.GetValueOrDefault(routeFile.Route.MilepostUnitsMetric);

            loadTasks.Add(Task.Run(() =>
            {
                string tdbFile = routeFolder.TrackDatabaseFile(routeFile);
                if (!File.Exists(tdbFile))
                {
                    Trace.TraceError($"Track Database File not found in {tdbFile}");
                    return;
                }
                TrackDB = new TrackDatabaseFile(tdbFile).TrackDB;
            }, cancellationToken));
            loadTasks.Add(Task.Run(() =>
            {
                TrackSections = new TrackSectionsFile(routeFolder.TrackSectionFile);
                if (File.Exists(routeFolder.RouteTrackSectionFile))
                {
                    TrackSections.AddRouteTSectionDatFile(routeFolder.RouteTrackSectionFile);
                }
            }, cancellationToken));
            loadTasks.Add(Task.Run(() =>
            {
                string rdbFile = routeFolder.RoadTrackDatabaseFile(routeFile);
                if (!File.Exists(rdbFile))
                {
                    Trace.TraceError($"Road Database File not found in {rdbFile}");
                    return;
                }
                RoadTrackDB = new RoadDatabaseFile(rdbFile).RoadTrackDB;
            }, cancellationToken));
            loadTasks.Add(Task.Run(() => SignalConfig = new SignalConfigurationFile(routeFolder.SignalConfigurationFile, routeFolder.ORSignalConfigFile), cancellationToken));

            await Task.WhenAll(loadTasks).ConfigureAwait(false);
        }
        public static void SetupApp()
        {
            studentName        = "error";
            secondsTimer       = 0;
            inputOption        = -1;
            arrayOfOutputInfo  = new string[4];
            arrayOfOutputImage = new Image[4];


            currentDir = new DirectoryInfo(Directory.GetCurrentDirectory());

            CountFilesCategoriesFolder();
            FolderStructure x = CountFilesModelsFolders("\\Categories\\Category Models");

            ColourSelect();
            SizeSelect();

            arrayOfSPImage.Clear();
            arrayOfSPColour.Clear();
            arrayOfSPInfo.Clear();
        }
Esempio n. 19
0
File: Import.cs Progetto: F-D-R/FDR
        private static string GetRelativeDestFolder(FolderStructure destStruct, DateTime date, string dateFormat)
        {
            var sep        = Path.DirectorySeparatorChar;
            var dateString = date.ToString(dateFormat);

            switch (destStruct)
            {
            case FolderStructure.date: return($"{dateString}");

            case FolderStructure.year_date: return($"{date:yyyy}{sep}{dateString}");

            case FolderStructure.year_month_date: return($"{date:yyyy}{sep}{date:MM}{sep}{dateString}");

            case FolderStructure.year_month_day: return($"{date:yyyy}{sep}{date:MM}{sep}{date:dd}");

            case FolderStructure.year_month: return($"{date:yyyy}{sep}{date:MM}");

            default:
                throw new NotImplementedException($"Unhandled destination structure: {destStruct}");
            }
        }
        private void CompareFolders(FolderStructure firstFolder, FolderStructure secondFolder)
        {
            foreach (KeyValuePair <string, bool> file in firstFolder.Files)
            {
                if (secondFolder.Files.ContainsKey(file.Key))
                {
                    secondFolder.Files[file.Key] = true;
                }
            }

            foreach (KeyValuePair <string, FolderStructure> subdir in firstFolder.Subdirectories)
            {
                secondFolder.Subdirectories.TryGetValue(subdir.Key, out FolderStructure subdiredit);

                if (subdiredit != null)
                {
                    subdiredit.Duplicate = true;
                    CompareFolders(subdir.Value, subdiredit);
                    secondFolder.Subdirectories[subdir.Key] = subdiredit;
                }
            }
        }
        private static void ProcessSubdirectory(FolderStructure thisDirectory, string directoryPath)
        {
            // Process the list of files found in the directory.
            string[] fileslist = Directory.GetFiles(directoryPath);
            foreach (string filename in fileslist)
            {
                string scrubbedname = filename.Split('\\').Last();
                thisDirectory.Files.Add(scrubbedname, false);
            }

            // Recurse into subdirectories of this directory.
            string[] subdirslist = Directory.GetDirectories(directoryPath);
            foreach (string subdir in subdirslist)
            {
                FolderStructure NewSubfolder = new FolderStructure
                {
                    Name       = subdir.Split('\\').Last(),
                    FolderPath = subdir
                };
                thisDirectory.Subdirectories.Add(NewSubfolder.Name, NewSubfolder);

                ProcessSubdirectory(NewSubfolder, subdir);
            }
        }
Esempio n. 22
0
        public static async Task<IEnumerable<TestActivity>> GetTestActivities(Dictionary<string, string> folders, CancellationToken token)
        {
            if (null == folders)
                throw new ArgumentNullException(nameof(folders));

            using (SemaphoreSlim addItem = new SemaphoreSlim(1))
            {
                List<TestActivity> result = new List<TestActivity>();

                TransformManyBlock<KeyValuePair<string, string>, (Folder, string)> inputBlock = new TransformManyBlock<KeyValuePair<string, string>, (Folder, string)>
                    (folderName =>
                    {
                        Folder folder = new Folder(folderName.Key, folderName.Value);
                        string routesDirectory = folder.ContentFolder.RoutesFolder;
                        if (Directory.Exists(routesDirectory))
                        {
                            return Directory.EnumerateDirectories(routesDirectory).Select(r => (folder, r));
                        }
                        else
                            return Array.Empty<(Folder, string)>();
                    },
                        new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = token });

                TransformManyBlock<(Folder, string), (Folder, Route, string)> routeBlock = new TransformManyBlock<(Folder folder, string routeDirectory), (Folder, Route, string)>
                    (routeFile =>
                    {
                        if (FolderStructure.Route(routeFile.routeDirectory).IsValid)
                        {
                            Route route = new Route(routeFile.routeDirectory);
                            string activitiesDirectory = route.RouteFolder.ActivitiesFolder;
                            if (Directory.Exists(activitiesDirectory))
                            {
                                return Directory.EnumerateFiles(activitiesDirectory, "*.act").Select(a => (routeFile.folder, route, a));
                            }
                        }
                        return Array.Empty<(Folder, Route, string)>();

                    },
                    new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = token });

                TransformBlock<(Folder, Route, string), TestActivity> activityBlock = new TransformBlock<(Folder folder, Route route, string activity), TestActivity>
                    (activityInput =>
                    {
                        Activity activity = Simplified.Activity.FromPathShallow(activityInput.activity);
                        return activity != null ? new TestActivity(activityInput.folder, activityInput.route, activity) : null;
                    },
                    new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = token });

                ActionBlock<TestActivity> actionBlock = new ActionBlock<TestActivity>
                        (async activity =>
                        {
                            if (null == activity)
                                return;
                            try
                            {
                                await addItem.WaitAsync(token).ConfigureAwait(false);
                                result.Add(activity);
                            }
                            finally
                            {
                                addItem.Release();
                            }
                        });

                inputBlock.LinkTo(routeBlock, new DataflowLinkOptions { PropagateCompletion = true });
                routeBlock.LinkTo(activityBlock, new DataflowLinkOptions { PropagateCompletion = true });
                activityBlock.LinkTo(actionBlock, new DataflowLinkOptions { PropagateCompletion = true });

                foreach (KeyValuePair<string, string> folder in folders)
                    await inputBlock.SendAsync(folder).ConfigureAwait(false);

                inputBlock.Complete();
                await actionBlock.Completion.ConfigureAwait(false);
                return result;
            }
        }
Esempio n. 23
0
 public Folder(string name, string path)
 {
     Name          = name;
     Path          = path;
     ContentFolder = FolderStructure.Content(path);
 }
Esempio n. 24
0
File: Import.cs Progetto: F-D-R/FDR
 private static string GetAbsoluteDestFolder(string destRoot, FolderStructure destStruct, DateTime date, string dateFormat)
 {
     return(Path.Combine(destRoot, GetRelativeDestFolder(destStruct, date, dateFormat)));
 }
Esempio n. 25
0
        /// <summary>
        /// Executes the specified filter action on the event.  Returns true if filter execution against this event should cease immediately.
        /// </summary>
        /// <param name="action">Action</param>
        /// <param name="e">Event</param>
        /// <param name="isEventSubmission">Pass true if the current operation is an event submission and this is the automatic filtering run. Additional logging may be performed for debugging purposes.</param>
        /// <returns></returns>
        private bool DeferredExecAction(FilterAction action, Event e, bool isEventSubmission)
        {
            if (action.Enabled)
            {
                if (action.Operator == FilterActionType.MoveTo)
                {
                    FolderStructure targetFolder = folderStructure.Value.ResolvePath(action.Argument.Trim(), null);
                    if (targetFolder == null)
                    {
                        targetFolder = db.FolderResolvePath(action.Argument.Trim());
                    }
                    if (targetFolder != null)
                    {
                        if (isEventSubmission && Settings.data.verboseSubmitLogging)
                        {
                            string currentFolderPathLabel = "";
                            if (folderStructure.Value.TryGetNode(e.FolderId, out FolderStructure currentFolder))
                            {
                                currentFolderPathLabel = " (" + currentFolder.AbsolutePath + ")";
                            }
                            Util.SubmitLog(ProjectName, "Event " + e.EventId + " Filter " + action.FilterId + " Action " + action.FilterActionId + " (MoveTo) deferred move from folder " + e.FolderId + currentFolderPathLabel + " to folder " + targetFolder.FolderId + " (" + targetFolder.AbsolutePath + ")");
                        }

                        deferredActions.MoveEventTo(e, targetFolder.FolderId);
                        // Make change in memory so that later filters during this filtering operation can see and act upon the new value.
                        e.FolderId = targetFolder.FolderId;
                    }
                    else
                    {
                        Logger.Info("[Filter " + action.FilterId + "] FilterAction " + action.FilterActionId + " was unable to resolve path \"" + action.Argument + "\"");

                        if (isEventSubmission && Settings.data.verboseSubmitLogging)
                        {
                            Util.SubmitLog(ProjectName, "Event " + e.EventId + " Filter " + action.FilterId + " Action " + action.FilterActionId + " (MoveTo) failed: unable to resolve path \"" + action.Argument + "\"");
                        }
                    }
                    return(false);
                }
                else if (action.Operator == FilterActionType.Delete)
                {
                    if (isEventSubmission && Settings.data.verboseSubmitLogging)
                    {
                        Util.SubmitLog(ProjectName, "Event " + e.EventId + " Filter " + action.FilterId + " Action " + action.FilterActionId + " (Delete) deferred");
                    }

                    deferredActions.DeleteEvent(e);
                    return(true);
                }
                else if (action.Operator == FilterActionType.SetColor)
                {
                    uint color = 0;
                    try
                    {
                        string hex = action.Argument;
                        if (hex.StartsWith("#"))
                        {
                            hex = hex.Substring(1);
                        }
                        color = Convert.ToUInt32(hex, 16);

                        if (isEventSubmission && Settings.data.verboseSubmitLogging)
                        {
                            Util.SubmitLog(ProjectName, "Event " + e.EventId + " Filter " + action.FilterId + " Action " + action.FilterActionId + " (SetColor) deferred set color to #" + hex);
                        }
                    }
                    catch
                    {
                        Logger.Info("[Filter " + action.FilterId + "] FilterAction " + action.FilterActionId + " with Operator \"SetColor\" has invalid Argument \"" + action.Argument + "\"");

                        if (isEventSubmission && Settings.data.verboseSubmitLogging)
                        {
                            Util.SubmitLog(ProjectName, "Event " + e.EventId + " Filter " + action.FilterId + " Action " + action.FilterActionId + " (SetColor) failed: invalid Argument \"" + action.Argument + "\"");
                        }

                        return(false);
                    }
                    deferredActions.SetEventColor(e, color);
                    // Make change in memory so that later filters during this filtering operation can see and act upon the new value.
                    e.Color = color;
                    return(false);
                }
                else if (action.Operator == FilterActionType.StopExecution)
                {
                    if (isEventSubmission && Settings.data.verboseSubmitLogging)
                    {
                        Util.SubmitLog(ProjectName, "Event " + e.EventId + " Filter " + action.FilterId + " Action " + action.FilterActionId + " (StopExecution)");
                    }
                    return(true);
                }
                else if (action.Operator == FilterActionType.MarkRead)
                {
                    if (isEventSubmission && Settings.data.verboseSubmitLogging)
                    {
                        Util.SubmitLog(ProjectName, "Event " + e.EventId + " Filter " + action.FilterId + " Action " + action.FilterActionId + " (MarkRead) deferred");
                    }

                    deferredActions.SetReadState(e, true);
                    return(false);
                }
                else if (action.Operator == FilterActionType.MarkUnread)
                {
                    if (isEventSubmission && Settings.data.verboseSubmitLogging)
                    {
                        Util.SubmitLog(ProjectName, "Event " + e.EventId + " Filter " + action.FilterId + " Action " + action.FilterActionId + " (MarkUnread) deferred");
                    }

                    deferredActions.SetReadState(e, false);
                    return(false);
                }
                else
                {
                    throw new Exception("Unsupported filter action operator: " + action.Operator);
                }
            }
            return(false);
        }
Esempio n. 26
0
        public void BuildFolderStructure()
        {
            var folders = new MyFolderTreeResult[]
            {
                new MyFolderTreeResult()
                {
                    Id = -23, Name = "root", ParentId = 0
                },
                // some random states
                new MyFolderTreeResult()
                {
                    Id = 454, Name = "Wyoming", ParentId = -23
                },
                new MyFolderTreeResult()
                {
                    Id = 594, Name = "Virginia", ParentId = -23
                },
                new MyFolderTreeResult()
                {
                    Id = 996, Name = "Nebraska", ParentId = -23
                },
                // random cities in WY
                new MyFolderTreeResult()
                {
                    Id = 29, Name = "Buford", ParentId = 454
                },
                new MyFolderTreeResult()
                {
                    Id = 37, Name = "Lusk", ParentId = 454
                },
                new MyFolderTreeResult()
                {
                    Id = 927, Name = "Farson", ParentId = 454
                },
                // random cities in VA
                new MyFolderTreeResult()
                {
                    Id = 64, Name = "Bodtyon", ParentId = 594
                },
                new MyFolderTreeResult()
                {
                    Id = 68, Name = "Goshen", ParentId = 594
                },
                new MyFolderTreeResult()
                {
                    Id = 713, Name = "Wise", ParentId = 594
                },
                // random cities in NE
                new MyFolderTreeResult()
                {
                    Id = 436, Name = "Gothenburg", ParentId = 996
                },
                new MyFolderTreeResult()
                {
                    Id = 413, Name = "Wahoo", ParentId = 996
                },
                new MyFolderTreeResult()
                {
                    Id = 217, Name = "Neligh", ParentId = 996
                }
            };

            var structure = FolderStructure.FromFolders(folders);

            var json     = JsonConvert.SerializeObject(structure, Formatting.Indented);
            var expected = GetResourceText("Testing.Resources.FolderStructure.txt");

            Assert.IsTrue(json.Equals(expected));
        }
Esempio n. 27
0
        public void Initialize()
        {
            if (!Simulator.Settings.DisableTCSScripts && ScriptName != null && ScriptName != "MSTS")
            {
                Script = Simulator.ScriptManager.Load(Path.Combine(Path.GetDirectoryName(Locomotive.WagFilePath), "Script"), ScriptName) as TrainControlSystem;
            }

            if (ParametersFileName != null)
            {
                ParametersFileName = Path.Combine(Path.Combine(Path.GetDirectoryName(Locomotive.WagFilePath), "Script"), ParametersFileName);
            }

            if (Script == null)
            {
                Script = new MSTSTrainControlSystem();
                ((MSTSTrainControlSystem)Script).VigilanceMonitor            = VigilanceMonitor;
                ((MSTSTrainControlSystem)Script).OverspeedMonitor            = OverspeedMonitor;
                ((MSTSTrainControlSystem)Script).EmergencyStopMonitor        = EmergencyStopMonitor;
                ((MSTSTrainControlSystem)Script).AWSMonitor                  = AWSMonitor;
                ((MSTSTrainControlSystem)Script).EmergencyCausesThrottleDown = Locomotive.EmergencyCausesThrottleDown;
                ((MSTSTrainControlSystem)Script).EmergencyEngagesHorn        = Locomotive.EmergencyEngagesHorn;
            }

            if (SoundFileName != null)
            {
                var soundPathArray = new[] {
                    Path.Combine(Path.GetDirectoryName(Locomotive.WagFilePath), "SOUND"),
                    Path.Combine(Simulator.BasePath, "SOUND"),
                };
                var soundPath = FolderStructure.FindFileFromFolders(soundPathArray, SoundFileName);
                if (File.Exists(soundPath))
                {
                    Sounds.Add(Script, soundPath);
                }
            }

            // AbstractScriptClass
            Script.ClockTime          = () => (float)Simulator.ClockTime;
            Script.GameTime           = () => (float)Simulator.GameTime;
            Script.DistanceM          = () => Locomotive.DistanceM;
            Script.Confirm            = Locomotive.Simulator.Confirmer.Confirm;
            Script.Message            = Locomotive.Simulator.Confirmer.Message;
            Script.SignalEvent        = Locomotive.SignalEvent;
            Script.SignalEventToTrain = (evt) =>
            {
                if (Locomotive.Train != null)
                {
                    Locomotive.Train.SignalEvent(evt);
                }
            };

            // TrainControlSystem getters
            Script.IsTrainControlEnabled = () => Locomotive == Locomotive.Train.LeadLocomotive && Locomotive.Train.TrainType != Train.TRAINTYPE.AI_PLAYERHOSTING;
            Script.IsAlerterEnabled      = () =>
            {
                return(Simulator.Settings.Alerter &&
                       !(Simulator.Settings.AlerterDisableExternal &&
                         !Simulator.PlayerIsInCab
                         ));
            };
            Script.IsSpeedControlEnabled      = () => Simulator.Settings.SpeedControl;
            Script.AlerterSound               = () => Locomotive.AlerterSnd;
            Script.TrainSpeedLimitMpS         = () => TrainInfo.allowedSpeedMpS;
            Script.CurrentSignalSpeedLimitMpS = () => Locomotive.Train.allowedMaxSpeedSignalMpS;
            Script.NextSignalSpeedLimitMpS    = (value) => NextSignalItem <float>(value, ref SignalSpeedLimits, Train.TrainObjectItem.TRAINOBJECTTYPE.SIGNAL);
            Script.NextSignalAspect           = (value) => NextSignalItem <TrackMonitorSignalAspect>(value,ref SignalAspects,Train.TrainObjectItem.TRAINOBJECTTYPE.SIGNAL);
            Script.NextSignalDistanceM        = (value) => NextSignalItem <float>(value,ref SignalDistances,Train.TrainObjectItem.TRAINOBJECTTYPE.SIGNAL);
            Script.CurrentPostSpeedLimitMpS   = () => Locomotive.Train.allowedMaxSpeedLimitMpS;
            Script.NextPostSpeedLimitMpS      = (value) => NextSignalItem <float>(value,ref PostSpeedLimits,Train.TrainObjectItem.TRAINOBJECTTYPE.SPEEDPOST);
            Script.NextPostDistanceM          = (value) => NextSignalItem <float>(value,ref PostDistances,Train.TrainObjectItem.TRAINOBJECTTYPE.SPEEDPOST);
            Script.TrainLengthM               = () => Locomotive.Train != null ? Locomotive.Train.Length : 0f;
            Script.SpeedMpS                                 = () => Math.Abs(Locomotive.SpeedMpS);
            Script.CurrentDirection                         = () => Locomotive.Direction;
            Script.IsDirectionForward                       = () => Locomotive.Direction == Direction.Forward;
            Script.IsDirectionNeutral                       = () => Locomotive.Direction == Direction.N;
            Script.IsDirectionReverse                       = () => Locomotive.Direction == Direction.Reverse;
            Script.IsBrakeEmergency                         = () => Locomotive.TrainBrakeController.EmergencyBraking;
            Script.IsBrakeFullService                       = () => Locomotive.TrainBrakeController.TCSFullServiceBraking;
            Script.PowerAuthorization                       = () => PowerAuthorization;
            Script.CircuitBreakerClosingOrder               = () => CircuitBreakerClosingOrder;
            Script.CircuitBreakerOpeningOrder               = () => CircuitBreakerOpeningOrder;
            Script.TractionAuthorization                    = () => TractionAuthorization;
            Script.BrakePipePressureBar                     = () => Locomotive.BrakeSystem != null ? (float)Pressure.Atmospheric.FromPSI(Locomotive.BrakeSystem.BrakeLine1PressurePSI) : float.MaxValue;
            Script.LocomotiveBrakeCylinderPressureBar       = () => Locomotive.BrakeSystem != null ? (float)Pressure.Atmospheric.FromPSI(Locomotive.BrakeSystem.GetCylPressurePSI()) : float.MaxValue;
            Script.DoesBrakeCutPower                        = () => Locomotive.DoesBrakeCutPower;
            Script.BrakeCutsPowerAtBrakeCylinderPressureBar = () => (float)Pressure.Atmospheric.FromPSI(Locomotive.BrakeCutsPowerAtBrakeCylinderPressurePSI);

            // TrainControlSystem functions
            Script.SpeedCurve    = (arg1,arg2,arg3,arg4,arg5) => SpeedCurve(arg1,arg2,arg3,arg4,arg5);
            Script.DistanceCurve = (arg1,arg2,arg3,arg4,arg5) => DistanceCurve(arg1,arg2,arg3,arg4,arg5);
            Script.Deceleration  = (arg1,arg2,arg3) => Deceleration(arg1,arg2,arg3);

            // TrainControlSystem setters
            Script.SetFullBrake = (value) =>
            {
                if (Locomotive.TrainBrakeController.TCSFullServiceBraking != value)
                {
                    Locomotive.TrainBrakeController.TCSFullServiceBraking = value;

                    //Debrief Eval
                    if (value && Locomotive.IsPlayerTrain && !ldbfevalfullbrakeabove16kmh && Math.Abs(Locomotive.SpeedMpS) > 4.44444)
                    {
                        var train = Simulator.PlayerLocomotive.Train;//Debrief Eval
                        DbfevalFullBrakeAbove16kmh++;
                        ldbfevalfullbrakeabove16kmh = true;
                        train.DbfEvalValueChanged   = true;//Debrief eval
                    }
                    if (!value)
                    {
                        ldbfevalfullbrakeabove16kmh = false;
                    }
                }
            };
            Script.SetEmergencyBrake = (value) =>
            {
                if (Locomotive.TrainBrakeController.TCSEmergencyBraking != value)
                {
                    Locomotive.TrainBrakeController.TCSEmergencyBraking = value;
                }
            };
            Script.SetThrottleController     = (value) => Locomotive.ThrottleController.SetValue(value);
            Script.SetDynamicBrakeController = (value) => Locomotive.DynamicBrakeController.SetValue(value);
            Script.SetPantographsDown        = () =>
            {
                if (Locomotive.Pantographs.State == PantographState.Up)
                {
                    Locomotive.Train.SignalEvent(PowerSupplyEvent.LowerPantograph);
                }
            };
            Script.SetPowerAuthorization         = (value) => PowerAuthorization = value;
            Script.SetCircuitBreakerClosingOrder = (value) => CircuitBreakerClosingOrder = value;
            Script.SetCircuitBreakerOpeningOrder = (value) => CircuitBreakerOpeningOrder = value;
            Script.SetTractionAuthorization      = (value) => TractionAuthorization = value;
            Script.SetVigilanceAlarm             = (value) => Locomotive.SignalEvent(value ? TrainEvent.VigilanceAlarmOn : TrainEvent.VigilanceAlarmOff);
            Script.SetHorn                      = (value) => Locomotive.TCSHorn = value;
            Script.TriggerSoundAlert1           = () => this.SignalEvent(TrainEvent.TrainControlSystemAlert1,Script);
            Script.TriggerSoundAlert2           = () => this.SignalEvent(TrainEvent.TrainControlSystemAlert2,Script);
            Script.TriggerSoundInfo1            = () => this.SignalEvent(TrainEvent.TrainControlSystemInfo1,Script);
            Script.TriggerSoundInfo2            = () => this.SignalEvent(TrainEvent.TrainControlSystemInfo2,Script);
            Script.TriggerSoundPenalty1         = () => this.SignalEvent(TrainEvent.TrainControlSystemPenalty1,Script);
            Script.TriggerSoundPenalty2         = () => this.SignalEvent(TrainEvent.TrainControlSystemPenalty2,Script);
            Script.TriggerSoundWarning1         = () => this.SignalEvent(TrainEvent.TrainControlSystemWarning1,Script);
            Script.TriggerSoundWarning2         = () => this.SignalEvent(TrainEvent.TrainControlSystemWarning2,Script);
            Script.TriggerSoundSystemActivate   = () => this.SignalEvent(TrainEvent.TrainControlSystemActivate,Script);
            Script.TriggerSoundSystemDeactivate = () => this.SignalEvent(TrainEvent.TrainControlSystemDeactivate,Script);
            Script.SetVigilanceAlarmDisplay     = (value) => this.VigilanceAlarm = value;
            Script.SetVigilanceEmergencyDisplay = (value) => this.VigilanceEmergency = value;
            Script.SetOverspeedWarningDisplay   = (value) => this.OverspeedWarning = value;
            Script.SetPenaltyApplicationDisplay = (value) => this.PenaltyApplication = value;
            Script.SetMonitoringStatus          = (value) => this.MonitoringStatus = value;
            Script.SetCurrentSpeedLimitMpS      = (value) => this.CurrentSpeedLimitMpS = value;
            Script.SetNextSpeedLimitMpS         = (value) => this.NextSpeedLimitMpS = value;
            Script.SetInterventionSpeedLimitMpS = (value) => this.InterventionSpeedLimitMpS = value;
            Script.SetNextSignalAspect          = (value) => this.CabSignalAspect = (TrackMonitorSignalAspect)value;

            // TrainControlSystem INI configuration file
            Script.GetBoolParameter   = (arg1,arg2,arg3) => LoadParameter <bool>(arg1,arg2,arg3);
            Script.GetIntParameter    = (arg1,arg2,arg3) => LoadParameter <int>(arg1,arg2,arg3);
            Script.GetFloatParameter  = (arg1,arg2,arg3) => LoadParameter <float>(arg1,arg2,arg3);
            Script.GetStringParameter = (arg1,arg2,arg3) => LoadParameter <string>(arg1,arg2,arg3);

            Script.Initialize();
        }