public ConsoleSimulation(string inputFileName, CommandInterpreter interpreter) { m_Terminal = new ConsoleEmulator(interpreter); m_Logger = new ConsoleLogger(); m_TerminationMgr = new TerminationManager(inputFileName); var fileParserFac = new FileReaderFactory(); ICompiledFileReader fileParser = fileParserFac.GetFileParser(inputFileName); DisassembledFileBase file = fileParser.ParseFile(inputFileName, m_Logger); m_Terminal.PrintString("Successfully loaded " + inputFileName + " (source file: " + file.SourceInformation.SourceFilePath + "; " + file.TotalFileSize + " bytes)\n"); m_ExecCtx = new RuntimeProcess(file, m_Terminal); IEnumerable <InstructionData> programInstructions = DisassemblerServices.GenerateInstructionData(file.SymbolTable, file.TextSegment, file.SourceInformation); m_SrcMapping = new Dictionary <int, SourceLineInformation>(); foreach (InstructionData instructionElem in programInstructions) { m_SrcMapping.Add(instructionElem.ProgramCounterLocation, new SourceLineInformation(instructionElem)); } m_CmdTable = new CommandTable(m_SrcMapping, m_ExecCtx, m_Terminal, m_TerminationMgr); m_Terminal.AddAvailableCommands(m_CmdTable.AllCommands); }
private static void ReadFile(FileReadRequest request) { var fileReader = new FileReaderFactory().CreateReader(request.FilePath); var content = fileReader.Read(request); Console.WriteLine(content); }
public List <ControllerEntities.Shop> GetShops() { string absolutePath = Directory.GetCurrentDirectory(); string fileFolder = absolutePath + Path.DirectorySeparatorChar + "data"; string fileName = "siparis_ve_bayi_koordinatlari.xlsx"; FileReaderFactory factory = new FileReaderFactory(); IFileReader reader = factory.createFileReader(fileName.Split('.')[1]); ReadFileEntity fileEntity = reader.ReadFile(fileFolder, fileName, "shop"); return(fileEntity.shopList.Select((shop) => new ControllerEntities.Shop { name = shop.name, latitudeInteger = Convert.ToString(shop.latitude).Split(",")[0], latitudeDecimal = Convert.ToString(shop.latitude).Split(",")[1], longitudeInteger = Convert.ToString(shop.longitude).Split(",")[0], longitudeDecimal = Convert.ToString(shop.longitude).Split(",")[1], minOrderLimit = shop.minOrderLimit, maxOrderLimit = shop.maxOrderLimit }).ToList()); }
public void Then_returns_the_expected_result() { var expectedResult = new List <Row> { new Row { new Column("ID", "2"), new Column("First name", "Foo"), new Column("Last name", "Bar"), new Column("Address", "Main street 1") }, new Row { new Column("ID", "3"), new Column("First name", "Fïrst"), new Column("Last name", "Last"), new Column("Address", "Other street 2") }, new Row { new Column("ID", "9"), new Column("First name", "John"), new Column("Last name", "Smith"), new Column("Address", "Second street 96") }, new Row { new Column("ID", "10"), new Column("First name", "John"), new Column("Last name", "Doe"), new Column("Address", "Happy road 32") }, new Row { new Column("ID", "10"), new Column("First name", "John"), new Column("Last name", "Doe"), new Column("Address", "Not happy road 32") }, new Row { new Column("ID", "12"), new Column("First name", "Deleted"), new Column("Last name", "Name"), new Column("Address", "Hell 109") }, new Row { new Column("ID", "23"), new Column("First name", "D Family"), new Column("Last name", "Name"), new Column("Address", "ABC Road 1") } }; var result = new FileReaderFactory().CreateFromFileName(new FileInfoWrapper(new FileInfo(CsvFilePath))).Read(0); result.ShouldAllBeEquivalentTo(expectedResult); }
private static async Task AssertPackagesUpgradable(string package1Path, string package2Path, bool ignoreVersionCheck = false) { if (string.IsNullOrEmpty(package1Path)) { throw new ArgumentNullException(nameof(package1Path)); } if (string.IsNullOrEmpty(package2Path)) { throw new ArgumentNullException(nameof(package2Path)); } var manifestReader = new AppxManifestReader(); string packageFamily1, packageFamily2, version1, version2, name1, name2; try { using var fileReader1 = FileReaderFactory.CreateFileReader(package1Path); var file1 = await manifestReader.Read(fileReader1).ConfigureAwait(false); packageFamily1 = file1.FamilyName; version1 = file1.Version; name1 = file1.DisplayName; } catch (Exception e) { throw new UpdateImpactException($"Could not read the package. File {package1Path} has invalid or unsupported format.", UpgradeImpactError.WrongPackageFormat, e); } try { using var fileReader2 = FileReaderFactory.CreateFileReader(package2Path); var file2 = await manifestReader.Read(fileReader2).ConfigureAwait(false); packageFamily2 = file2.FamilyName; version2 = file2.Version; name2 = file2.DisplayName; } catch (Exception e) { throw new UpdateImpactException($"Could not read the package. File {package2Path} has invalid or unsupported format.", UpgradeImpactError.WrongPackageFormat, e); } if (!string.Equals(packageFamily1, packageFamily2)) { throw new UpdateImpactException($"Package '{name2}' cannot upgrade the package '{name1}' because they do not share the same family name.", UpgradeImpactError.WrongFamilyName); } if (ignoreVersionCheck) { return; } if (Version.Parse(version2) <= Version.Parse(version1)) { throw new UpdateImpactException($"Package '{name2}' version '{version2}' cannot update the package '{name1}' version '{version1}'. The version of the upgrade package must be higher than '{version1}'.", UpgradeImpactError.WrongPackageVersion); } }
public void LoadFile() { var fileSplit = _filePath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); var lastPartSplit = fileSplit[fileSplit.Length - 1] .Split('.'); _reader = FileReaderFactory.GetReader(lastPartSplit[lastPartSplit.Length - 1]); _reader.OpenFile(_filePath); }
public async Task Load() { using var cts = new CancellationTokenSource(); using var reader = FileReaderFactory.CreateFileReader(this.packagePath); var canElevate = await UserHelper.IsAdministratorAsync(cts.Token) || await this.interProcessCommunicationManager.Test(cts.Token); var progress = new Progress <ProgressData>(); // Load manifest var taskLoadPackage = this.LoadManifest(reader, cts.Token); // Load certificate trust var taskLoadSignature = this.Trust.LoadSignature(cts.Token); // Load PSF var manifest = await taskLoadPackage.ConfigureAwait(false); var taskPsf = this.LoadPsf(reader, manifest); // Load add-ons var taskAddOns = this.GetAddOns(manifest, cts.Token); // Load drive // var taskDisk = this.Disk.Load(this.LoadDisk()); // Load users Task <FoundUsersViewModel> taskUsers; try { taskUsers = this.GetUsers(manifest, canElevate, cts.Token); } catch (Exception) { taskUsers = this.GetUsers(manifest, false, cts.Token); } await this.Manifest.Load(Task.FromResult(new PackageExpertPropertiesViewModel(manifest, this.packagePath))).ConfigureAwait(false); await this.PackageSupportFramework.Load(taskPsf).ConfigureAwait(false); await this.AddOns.Load(taskAddOns).ConfigureAwait(false); await this.Users.Load(taskUsers).ConfigureAwait(false); this.Registry = new AppxRegistryViewModel(this.packagePath); this.OnPropertyChanged(nameof(this.Registry)); this.Files = new AppxFilesViewModel(this.packagePath, this.fileViewer, this.fileInvoker); this.OnPropertyChanged(nameof(this.Files)); // Wait for them all var allTasks = Task.WhenAll(taskLoadPackage, taskLoadSignature, taskPsf, taskAddOns, taskUsers); this.Progress.MonitorProgress(allTasks, cts, progress); await allTasks; }
private void PrepareData(bool isTrain) { var reader = new FileReaderFactory().GetEnglishReaderForPhase2(isTrain); Documents = reader.ReadFile().Select(x => new DocumentWrapper(x)).ToDictionary(x => x.Document.Id); var generator = new VectorGenerator(Documents, true); generator.Process(); }
static int Main(string[] args) { var result = 0; //args = new[] { "compress", @"D:\Data\data.dat", @"d:\Data\data.dat.compressed" }; //args = new[] { "decompress", @"D:\Data\data.dat.compressed", @"D:\Data\data.dat.decompressed"}; //args = new[] { "compress", @"D:\Data\data.dat.small", @"D:\Data\data.dat.small.compressed" }; //args = new[] { "decompress", @"D:\Data\data.dat.small.compressed", @"D:\Data\data.dat.small.decompressed" }; try { var startParams = ParseCommandLine(args); var readerFactory = new FileReaderFactory(startParams.SrcFilePath); var writerFactory = new FileWriterFactory(startParams.DstFilePath); IDataDispatcher dispatcher; if (startParams.Compress) { var readThreadsCount = Math.Max(1, Environment.ProcessorCount / 4); var writeThreadsCount = Math.Max(1, Environment.ProcessorCount - readThreadsCount); dispatcher = new CompressDataDispatcher(readerFactory, writerFactory, readThreadsCount, writeThreadsCount); } else { var writeThreadsCount = Math.Max(1, Environment.ProcessorCount / 4); var readThreadsCount = Math.Max(1, Environment.ProcessorCount - writeThreadsCount); dispatcher = new DecompressDataDispatcher(readerFactory, writerFactory, readThreadsCount, writeThreadsCount); } Stopwatch stopwatch = Stopwatch.StartNew(); dispatcher.Start(); var exception = dispatcher.WaitForCompletion(); stopwatch.Stop(); Console.WriteLine($"Time elapsed: {stopwatch.ElapsedMilliseconds}"); if (exception != null) { throw exception; } } catch (Exception ex) { PrintException(ex); result = 1; } //Console.ReadKey(); return(result); }
public async Task <DependencyGraph> GetGraph(string initialPackage, CancellationToken cancellationToken = default, IProgress <ProgressData> progress = null) { progress?.Report(new ProgressData(0, $"Reading {Path.GetFileName(initialPackage)}...")); var reader = new AppxManifestReader(); using var fileReader = FileReaderFactory.CreateFileReader(initialPackage); var pkg = await reader.Read(fileReader, cancellationToken).ConfigureAwait(false); return(await this.GetGraph(pkg, cancellationToken, progress).ConfigureAwait(false)); }
public DebugWindowViewModel(int viewId, MessageManager msgMgr) : base(msgMgr) { m_ViewId = viewId; m_LoggerVm = new LoggerViewModel(); m_FilesToExecute = new ObservableCollection <DisassembledFileViewModel>(); m_FileProc = new FileReaderFactory(); m_LoadFileCmd = new RelayCommand <string>((param) => LoadFile(param), true); m_HandleAssembledFileCmd = new RelayCommand <string>((compiledFileName) => HandleFileAssembledMsg(compiledFileName), true); }
public MainWindow(FileReaderFactory readerFactory) { _readerFactory = readerFactory ?? throw new ArgumentNullException(nameof(readerFactory)); InitializeComponent(); DataContext = _model; DataObject.AddPastingHandler(GridWidth, NumericOnly_OnPaste); DataObject.AddPastingHandler(GridHeight, NumericOnly_OnPaste); DataObject.AddPastingHandler(FluidContact, NumericOnly_OnPaste); }
public void Given_excel_file_Then_expected_names_are_returned() { var expectedDictionary = new Dictionary <int, string> { { 0, "Data" }, { 1, "Small Set" }, { 2, "Tab3" } }; var reader = new FileReaderFactory().CreateFromFileName(new FileInfoWrapper(new FileInfo(XlsxWithMultipeTabsPath))); reader.GetTabNamesByIndex().ShouldAllBeEquivalentTo(expectedDictionary); }
public async Task TestWildcard() { var msixHeroPackage = new FileInfo(Path.Combine("Resources", "SamplePackages", "CreatedByMsixHero.msix")); var reader = FileReaderFactory.CreateFileReader(msixHeroPackage.FullName); var files = new List <AppxFileInfo>(); await foreach (var file in reader.EnumerateFiles(@"VFS\AppVPackageDrive\ConEmuPack", "psf*.exe")) { files.Add(file); } Assert.AreEqual(@"VFS\AppVPackageDrive\ConEmuPack\PsfLauncher1.exe", files.Single().FullPath); }
private async void OnView() { var selectedFile = this.SelectedNode; if (selectedFile == null) { return; } using var reader = FileReaderFactory.CreateFileReader(this.PackageFile); var path = await this.fileViewer.GetDiskPath(reader, selectedFile.Path).ConfigureAwait(false); ExceptionGuard.Guard(() => { this.fileInvoker.Execute(path, true); }); }
public async Task <bool> IsInstalled(string manifestPath, PackageFindMode mode = PackageFindMode.CurrentUser, CancellationToken cancellationToken = default, IProgress <ProgressData> progress = default) { PackageFindMode actualMode = mode; if (actualMode == PackageFindMode.Auto) { var isAdmin = await UserHelper.IsAdministratorAsync(cancellationToken).ConfigureAwait(false); if (isAdmin) { actualMode = PackageFindMode.AllUsers; } else { actualMode = PackageFindMode.CurrentUser; } } string pkgFullName; using (var src = FileReaderFactory.CreateFileReader(manifestPath)) { var manifestReader = new AppxManifestReader(); var parsed = await manifestReader.Read(src, false, cancellationToken).ConfigureAwait(false); pkgFullName = parsed.FullName; } switch (actualMode) { case PackageFindMode.CurrentUser: var pkg = await Task.Run( () => PackageManagerWrapper.Instance.FindPackageForUser(string.Empty, pkgFullName), cancellationToken).ConfigureAwait(false); return(pkg != null); case PackageFindMode.AllUsers: var pkgAllUsers = await Task.Run( () => PackageManagerWrapper.Instance.FindPackage(pkgFullName), cancellationToken).ConfigureAwait(false); return(pkgAllUsers != null); default: throw new NotSupportedException(); } }
public void TestMsixHeroDetection() { var msixHeroPackage = new FileInfo(Path.Combine("Resources", "SamplePackages", "CreatedByMsixHero.msix")); using (var reader = FileReaderFactory.CreateFileReader(msixHeroPackage.FullName)) { var packagingToolDetector = new AuthoringAppDetector(reader); var buildParams = new Dictionary <string, string> { { "MsixHero", "1.5.0" } }; Assert.IsTrue(packagingToolDetector.TryDetectMsixHero(buildParams, out _)); } }
public void ShouldBeNotGrantedToReadIfUseSecurityAndNotAuthorizedRole (string textReaderName, string fileNameWithContentToRead) { // Arrange var role = "roleB"; // Act var readerResult = FileReaderFactory.InitializeReader() .UsingTextReader(_readers[textReaderName]) .WithoutEncryption() .WithSecurityAsUser(new SimpleAccessManager(), role) .ReadFile($"Resources\\{fileNameWithContentToRead}"); // Assert Assert.IsFalse(readerResult.AccessGranted); Assert.AreEqual(string.Empty, readerResult.Content); }
public void Then_returns_the_expected_result() { var expectedResult = new List <Row> { new Row { new Column("Nr", "2"), new Column("Name", "New name"), new Column("Address", "Test street 123") }, new Row { new Column("Nr", "4"), new Column("Name", "Bar Foo"), new Column("Address", "Main street 1") }, new Row { new Column("Nr", "5"), new Column("Name", "First Middle Last"), new Column("Address", "Other street 2") }, new Row { new Column("Nr", "6"), new Column("Name", "Smith J. John"), new Column("Address", "Second street 98") }, new Row { new Column("Nr", "7"), new Column("Name", "Doe John Jr."), new Column("Address", "Happy road 32") }, new Row { new Column("Nr", "8"), new Column("Name", "D'Family Name"), new Column("Address", "ABC Road 1") } }; var result = new FileReaderFactory().CreateFromFileName(new FileInfoWrapper(new FileInfo(ExcelFilePath))).Read(0); result.ShouldAllBeEquivalentTo(expectedResult); }
public void ShouldBeGrantedToReadIfUseSecurityAndAdminUser(string textReaderName, string fileNameWithContentToRead) { // Arrange var expectedContent = File.ReadAllText($"Resources\\{fileNameWithContentToRead}"); var adminRole = SimpleAccessManager.adminRole; // Act var readerResult = FileReaderFactory.InitializeReader() .UsingTextReader(_readers[textReaderName]) .WithoutEncryption() .WithSecurityAsUser(new SimpleAccessManager(), adminRole) .ReadFile($"Resources\\{fileNameWithContentToRead}"); // Assert Assert.IsTrue(readerResult.AccessGranted); Assert.AreEqual(expectedContent, readerResult.Content); }
private void App_Startup(object sender, StartupEventArgs e) { // Force US culture for clarity (only period is allowed as decimal separator) var cultureInfo = new CultureInfo("en-US"); CultureInfo.CurrentCulture = cultureInfo; CultureInfo.DefaultThreadCurrentCulture = cultureInfo; CultureInfo.DefaultThreadCurrentUICulture = cultureInfo; Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; var readerFactory = new FileReaderFactory(); var window = new MainWindow(readerFactory); window.Show(); }
public void Must_Import_Data_And_Calculate_For_Csv(FileReaderTypeEnum fileReaderTypeEnum, string extension) { IFileReader reader = FileReaderFactory.GetReader(fileReaderTypeEnum); List <BlackScholesInput> blackScholesInputData = reader.Read <BlackScholesInput>($"{FullPath}{extension}"); var optionPricingCalculator = new BlackScholesCalculator(); List <BlackScholesResult> blackScholesResultData = optionPricingCalculator.CalculateFor(blackScholesInputData); List <double> expectedResults = new List <double>() { 110, 30, 0, 0, 110, 1.2444594168143162E-196, 110, 0 }; List <double> results = optionPricingCalculator.CalculateFor(blackScholesInputData).Select(r => r.Result).ToList(); CollectionAssert.AreEqual(expectedResults, results); }
public void ShouldBeAbleToReadReversedFile(string textReaderName, string fileNameWithExpected, string fileNameWithContentToRead) { // Arrange var expectedContent = File.ReadAllText($"Resources\\{fileNameWithExpected}"); // Act var readerResult = FileReaderFactory.InitializeReader() .UsingTextReader(_readers[textReaderName]) .WithEncryptor(new ReverseEncryptor()) .WithoutSecurity() .ReadFile($"Resources\\{fileNameWithContentToRead}"); File.WriteAllText("text", readerResult.Content); // Assert Assert.IsTrue(readerResult.AccessGranted); Assert.AreEqual(expectedContent, readerResult.Content); }
private static void Main() { Console.WriteLine("Welcome to File Reader!"); while (true) { var fileType = GetFileType(); var useEncryption = GetEncryptionInput(); var useAuthorization = false; if (!useEncryption) { useAuthorization = GetAuthorizationInput(); } var role = string.Empty; if (useAuthorization) { role = GetRoleInput(); } var fileReader = FileReaderFactory.FromFileType(fileType); Console.WriteLine("\n---------------------------------------------------------------------"); if (useEncryption) { Console.WriteLine(fileReader.ReadEncryptedFile()); } else if (useAuthorization) { Console.WriteLine(fileReader.ReadProtectedFile(role)); } else { Console.WriteLine(fileReader.ReadFile()); } Console.WriteLine("---------------------------------------------------------------------\n"); } }
public async Task TestRootItems() { var msixHeroPackage = new FileInfo(Path.Combine("Resources", "SamplePackages", "CreatedByMsixHero.msix")); var reader = FileReaderFactory.CreateFileReader(msixHeroPackage.FullName); var folders = new List <string>(); var files = new List <AppxFileInfo>(); await foreach (var dir in reader.EnumerateDirectories()) { folders.Add(dir); } await foreach (var file in reader.EnumerateFiles()) { files.Add(file); } Assert.IsTrue(new[] { "AppxMetadata", "Assets", "VFS" }.OrderBy(c => c).SequenceEqual(folders.OrderBy(d => d))); Assert.IsTrue(new[] { "AppxBlockMap.xml", "AppxManifest.xml", "AppxSignature.p7x", "Registry.dat", "Resources.pri", "User.dat", "UserClasses.dat", "[Content_Types].xml" }.OrderBy(c => c).SequenceEqual(files.Select(f => f.FullPath).OrderBy(f => f))); }
public async Task TestSubitems() { var msixHeroPackage = new FileInfo(Path.Combine("Resources", "SamplePackages", "CreatedByMsixHero.msix")); var reader = FileReaderFactory.CreateFileReader(msixHeroPackage.FullName); var folders = new List <string>(); var files = new List <AppxFileInfo>(); await foreach (var dir in reader.EnumerateDirectories(@"VFS\AppVPackageDrive")) { folders.Add(dir); } await foreach (var file in reader.EnumerateFiles(@"VFS\AppVPackageDrive\ConEmuPack")) { files.Add(file); } Assert.IsTrue(new[] { @"VFS\AppVPackageDrive\ConEmuPack" }.OrderBy(c => c).SequenceEqual(folders.OrderBy(d => d))); Assert.IsTrue(new[] { @"VFS\AppVPackageDrive\ConEmuPack\ConEmu.exe", @"VFS\AppVPackageDrive\ConEmuPack\ConEmu64.exe", @"VFS\AppVPackageDrive\ConEmuPack\PsfLauncher1.exe" }.OrderBy(c => c).SequenceEqual(files.Select(f => f.FullPath).OrderBy(f => f))); }
public List <ControllerEntities.Order> GetOrders() { string absolutePath = Directory.GetCurrentDirectory(); string fileFolder = absolutePath + Path.DirectorySeparatorChar + "data"; string fileName = "siparis_ve_bayi_koordinatlari.xlsx"; FileReaderFactory factory = new FileReaderFactory(); IFileReader reader = factory.createFileReader(fileName.Split('.')[1]); ReadFileEntity fileEntity = reader.ReadFile(fileFolder, fileName, "order"); return(fileEntity.orderList.Select((order) => new ControllerEntities.Order { orderNumber = order.orderNumber, latitudeInteger = Convert.ToString(order.latitude).Split(",")[0], latitudeDecimal = Convert.ToString(order.latitude).Split(",")[1], longitudeInteger = Convert.ToString(order.longitude).Split(",")[0], longitudeDecimal = Convert.ToString(order.longitude).Split(",")[1], }).ToList()); }
private void SourcePathOnValueChanged(object sender, ValueChangedEventArgs e) { try { using IAppxFileReader reader = FileReaderFactory.CreateFileReader((string)e.NewValue); var mr = new AppxManifestReader(); var read = mr.Read(reader).GetAwaiter().GetResult(); if (string.IsNullOrWhiteSpace(this.DisplayName.CurrentValue)) { this.DisplayName.CurrentValue = read.DisplayName + " - Modification package"; } this.ParentName.CurrentValue = read.Name; this.ParentPublisher.CurrentValue = read.Publisher; this.OnPropertyChanged(nameof(IsIncludeVfsFoldersEnabled)); } catch (Exception exception) { Logger.Error(exception); this.interactionService.ShowError("Could not read the properties from the package.", exception); } }
private void btnInputFile_Click(object sender, EventArgs e) { DialogResult result = openFileDialogCsv.ShowDialog(); if (result == DialogResult.OK) { try { FileReaderTypeEnum fileReaderTypeEnum = GetFileReaderTypeFor(openFileDialogCsv.FileName); IFileReader reader = FileReaderFactory.GetReader(fileReaderTypeEnum); List <BlackScholesInput> blackScholesInputData = reader.Read <BlackScholesInput>(openFileDialogCsv.FileName); var optionPricingCalculator = new BlackScholesCalculator(); List <BlackScholesResult> blackScholesResultData = optionPricingCalculator.CalculateFor(blackScholesInputData); ShowResultsOnScreen(blackScholesResultData); } catch (Exception ex) { string message = $"{ErrorsResource.ErrorToProcessData} Error: {ex.Message}"; MessageBox.Show(message, ErrorsResource.TitleErrorToProcessData, MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private static SerializableExpando GetReading(string path) { var reader = FileReaderFactory.GetReader(path); return(reader.ParseFile(path)); }