public void TestDirPathTranslation() { CvsRoot cvsRoot; WorkingDirectory workingDirectory; PathTranslator pathTranslator; cvsRoot = new CvsRoot(ROOT_ENTRY1); workingDirectory = new WorkingDirectory(cvsRoot, LOCAL_ROOT_DIR1, REPOS_NAME1); pathTranslator = new PathTranslator(workingDirectory, REPOS_DIR_PATH1); Assert.AreEqual("/cvsroot/sharpcvslib", pathTranslator.CvsRoot.CvsRepository, pathTranslator.CvsRoot.CvsRepository); Assert.AreEqual("src/ICSharpCode/SharpCvsLib/FileSystem/", pathTranslator.RelativePath, pathTranslator.RelativePath); Assert.AreEqual("dev-src", pathTranslator.BaseDir.Name); String expectedLocalPath = PathTranslator.ConvertToOSSpecificPath(Path.Combine(LOCAL_DIR1, "src/ICSharpCode/SharpCvsLib/FileSystem/")); Assert.AreEqual(expectedLocalPath, pathTranslator.CurrentDir.FullName); Assert.AreEqual(expectedLocalPath, pathTranslator.LocalPathAndFilename); Assert.IsTrue(pathTranslator.IsDirectory == true); }
public void MakeConnection_Bad() { CvsRoot root = new CvsRoot(this.Settings.Config.Cvsroot); root.User = "******"; WorkingDirectory working = new WorkingDirectory(root, this.Settings.Config.LocalPath, this.Settings.Config.Module); CVSServerConnection connection = new CVSServerConnection(); Assert.IsNotNull(connection, "Should have a connection object."); try { connection.Connect(working, this.Settings.Config.InvalidPassword); } catch (AuthenticationException e) { connection.Close(); throw e; } }
private void Checkout() { CvsRoot root = new CvsRoot(this.settings.Config.Cvsroot); WorkingDirectory working = new WorkingDirectory(root, this.settings.Config.LocalPath, this.settings.Config.Module); CVSServerConnection connection = new CVSServerConnection(); Assert.IsNotNull(connection, "Should have a connection object."); ICommand command = new CheckoutModuleCommand(working); Assert.IsNotNull(command, "Should have a command object."); connection.Connect(working, this.settings.Config.ValidPassword); command.Execute(connection); connection.Close(); }
public void ShouldReportWhenFileInArchiveIsNotReferencedInAddml() { WorkingDirectory workingDirectory = new WorkingDirectory(null, new DirectoryInfo(TestUtil.TestDataDirectory + "noark3")); AddmlFlatFileDefinition flatFileDefinition1 = new AddmlFlatFileDefinitionBuilder() .WithFileInfo(new FileInfo(workingDirectory.Content().DirectoryInfo().FullName + Path.DirectorySeparatorChar + "nosuchfile.txt")) .WithFileName("nosuchfile.txt") .Build(); AddmlFlatFileDefinition flatFileDefinition2 = new AddmlFlatFileDefinitionBuilder() .WithFileInfo(new FileInfo(workingDirectory.Content().DirectoryInfo().FullName + Path.DirectorySeparatorChar + "ARKIV.DAT")) .WithFileName("ARKIV.DAT") .Build(); AddmlDefinition addmlDefinition = new AddmlDefinitionBuilder() .WithAddmlFlatFileDefinitions(new List <AddmlFlatFileDefinition> { flatFileDefinition1, flatFileDefinition2 }) .Build(); Archive archive = new Archive(ArchiveType.Fagsystem, Uuid.Random(), workingDirectory); ControlExtraOrMissingFiles test = new ControlExtraOrMissingFiles(addmlDefinition, archive); TestRun testRun = test.GetTestRun(); testRun.IsSuccess().Should().BeFalse(); testRun.Results.Count.Should().Be(4); string errorMessage = "Finnes i arkiv, men ikke i ADDML"; testRun.Results[0].Location.ToString().Should().Contain("DOK.DAT"); testRun.Results[0].Message.Should().Be(errorMessage); testRun.Results[1].Location.ToString().Should().Contain("noark_3_arkivuttrekk_med_prosesser.xml"); testRun.Results[1].Message.Should().Be(errorMessage); testRun.Results[2].Location.ToString().Should().Contain("SAK.DAT"); testRun.Results[2].Message.Should().Be(errorMessage); testRun.Results[3].Location.ToString().Should().Contain("nosuchfile.txt"); testRun.Results[3].Message.Should().Be("Finnes i ADDML, men ikke i arkiv"); }
public override string ToArgs() { List <string> options = new List <string> { Url.Formatted(), Driver.Formatted(), User.Formatted(), Password.Formatted(), ConnectRetries.Formatted(), InitSql.Formatted(), DefaultSchema.Formatted(), Schemas.Formatted(), Table.Formatted(), Locations.Formatted(), Color.Formatted(), JarDirs.Formatted(), SqlMigrationPrefix.Formatted(), UndoSqlMigrationPrefix.Formatted(), RepeatableSqlMigrationPrefix.Formatted(), SqlMigrationSeparator.Formatted(), SqlMigrationSuffixes.Formatted(), ValidateMigrationNaming.Formatted(), Encoding.Formatted(), PlaceholderReplacement.Formatted(), Placeholders.Formatted(), PlaceholderPrefix.Formatted(), PlaceholderSuffix.Formatted(), Resolvers.Formatted(), SkipDefaultResolvers.Formatted(), Callbacks.Formatted(), SkipDefaultCallbacks.Formatted(), Target.Formatted(), OutOfOrder.Formatted(), WorkingDirectory.Formatted(), LicenseKey.Formatted() }; return(ToArgs(options)); }
public void FindAllWorkingFolders() { Manager manager = new Manager(Path.Combine(this.settings.LocalPath, this.settings.Module)); string rootDir = Path.Combine(this.settings.Config.LocalPath, this.settings.Config.Module); CvsRoot root = new CvsRoot(this.settings.Config.Cvsroot); WorkingDirectory working = new WorkingDirectory(root, rootDir, this.settings.Config.Module); this.WriteTestDirectoryEntries(rootDir); Repository repository = new Repository(rootDir, this.REPOSITORY_ENTRY); manager.AddRepository(repository); working.FoldersToUpdate = manager.FetchFilesToUpdate(rootDir); Assert.IsTrue(working.FoldersToUpdate.Length > 1, "Working folders count should be greater than 1."); }
private TestSession NewSession(WorkingDirectory workingDirectory, ArchiveType archiveType, Uuid uuid) { Archive archive = new Archive(archiveType, uuid, workingDirectory); workingDirectory.CopyAddmlFileToAdministrativeMetadata(); ConvertNoarkihToAddmlIfNoark4(archive); var testSession = new TestSession(archive); if (archiveType != ArchiveType.Noark5) { FileInfo addmlFile = archive.GetStructureDescriptionFile(); if (addmlFile.Exists) // file does not exist when user want to just do a simple packaging job { AddmlInfo addml = AddmlUtil.ReadFromFile(addmlFile.FullName); testSession.AddmlDefinition = new AddmlDefinitionParser(addml, workingDirectory, _statusEventHandler).GetAddmlDefinition(); } } return(testSession); }
/// <summary> /// Create the command object that will be used to act on the repository. /// </summary> /// <returns>The command object that will be used to act on the /// repository.</returns> /// <exception cref="Exception">TODO: Make a more specific exception</exception> /// <exception cref="NotImplementedException">If the command argument /// is not implemented currently. TODO: Implement the argument.</exception> public override ICommand CreateCommand() { ICSharpCode.SharpCvsLib.Commands.LogCommand logCommand; DirectoryInfo dir = new DirectoryInfo(Directory.GetCurrentDirectory()); this.ParseOptions(this.unparsedOptions); try { Repository repository = Repository.Load(dir); if (null == repository || null == repository.FileContents) { throw new CvsFileNotFoundException( string.Format("Valid CVS\\Repository file not found in {0}", dir)); } this.repository = repository.FileContents; Root root = Root.Load(dir); if (null == root || null == root.FileContents) { throw new CvsFileNotFoundException( string.Format("Valid CVS\\Root file not found in {0}", dir)); } this.cvsRoot = new CvsRoot(root.FileContents); } catch (CvsFileNotFoundException e) { LOGGER.Error(e); ConsoleMain.ExitProgram("Not a CVS repository.", e); } CurrentWorkingDirectory = new WorkingDirectory(this.cvsRoot, dir.FullName, this.repository); logCommand = new ICSharpCode.SharpCvsLib.Commands.LogCommand( CurrentWorkingDirectory, folders); return(logCommand); }
public LocalProcess Start() { Verify.IsNotEmpty(nameof(File), File); Process = new Process(); Process.StartInfo.FileName = File; Process.StartInfo.Arguments = Arguments.IsNotEmpty() ? Arguments : null; Process.StartInfo.WorkingDirectory = WorkingDirectory.IsNotEmpty() ? WorkingDirectory : null; Process.StartInfo.UseShellExecute = UseShellExecute; Process.StartInfo.CreateNoWindow = CreateNoWindow; if (!UseShellExecute) { Process.StartInfo.RedirectStandardOutput = true; Process.StartInfo.RedirectStandardError = true; } // Start process Verify.Assert <InvalidOperationException>(Process.Start(), "Could not start process"); return(this); }
protected override ProcessTaskResult HandleResult(ProcessTaskResult result) { if (result.ExitCode != 0) { if (result.StdErr.Count > 0) { var folderName = WorkingDirectory.Split(Path.AltDirectorySeparatorChar).Last(); var errMessage = result.StdErr[0]; var message = string.Format( "Failed to checkout submodule: {0}:{1}\r\n{2}", folderName, version, errMessage); result.Err(message); } else { result.Err(); } } return(result); }
private string GetPassword(CommandLineParser parser, WorkingDirectory workingDir) { string pwd = null; if (null != parser && null != parser.Password && parser.Password.Length != 0) { pwd = parser.Password; } else { LoginCommand loginCommand = new LoginCommand(workingDir.CvsRoot); loginCommand.Execute(); pwd = loginCommand.Password; } if (null == pwd) { pwd = String.Empty; } return(pwd); }
public void OneValidOneInvalidSource() { using var tempDir = TempDir.Create(); using var wd = WorkingDirectory.ChangeTo(tempDir); var dataProvider = new DataProvider(); var iecCddPath = Path.Combine(tempDir, "iec-cdd"); Directory.CreateDirectory(iecCddPath); using var source1 = TempDir.Create(iecCddPath); CreateEmptyXls(source1, GetExportFileName("class", "12345")); CreateEmptyXls(source1, GetExportFileName("property", "12345")); using var source2 = TempDir.Create(iecCddPath); CreateEmptyXls(source2, GetExportFileName("class", "67890")); CreateEmptyXls(source2, GetExportFileName("property", "67890")); CreateEmptyXls(source2, GetExportFileName("class", "12345")); Assert.That(dataProvider.FindDefaultDataSources(), Is.EquivalentTo(new[] { new DataSource(dataProvider, source1, Model.DataSourceType.Default), })); }
public void ShouldReturnTestSuiteFromTests() { var workingDirectory = new WorkingDirectory(ArkadeConstants.GetArkadeWorkDirectory(), new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\..\\..\\TestData\\noark3\\")); AddmlInfo addml = AddmlUtil.ReadFromFile(workingDirectory.Root().WithFile("noark_3_arkivuttrekk_med_prosesser.xml").FullName); AddmlDefinition addmlDefinition = new AddmlDefinitionParser(addml, workingDirectory).GetAddmlDefinition(); var testSession = new TestSession(new Archive(ArchiveType.Noark3, Uuid.Random(), workingDirectory)); testSession.AddmlDefinition = addmlDefinition; var addmlDatasetTestEngine = new AddmlDatasetTestEngine(new FlatFileReaderFactory(), new AddmlProcessRunner(), new StatusEventHandler()); TestSuite testSuite = addmlDatasetTestEngine.RunTestsOnArchive(testSession); testSuite.Should().NotBeNull(); testSuite.TestRuns.Should().NotBeNullOrEmpty(); List <TestRun> analyseFindMinMaxValues = testSuite.TestRuns .Where(run => run.TestName == AnalyseFindMinMaxValues.Name) .ToList(); analyseFindMinMaxValues.Count.Should().Be(1); }
private void btnRemove_Click(object sender, EventArgs e) { if (tbcMain.SelectedIndex == 0) { ClassData removed = lstClasses.Remove(); if (removed != null) // Delete images { for (int i = 0; i < removed.BattleAnimations.Count; i++) { string fileName = @"Images\ClassBattleAnimations\" + removed.Name + @"\" + removed.BattleAnimations[i].Name; if (WorkingDirectory.CheckFileExist(fileName + WorkingDirectory.DefultImageFileFormat)) { DeleteFile(fileName, WorkingDirectory, false, WorkingDirectory.DefultImageFileFormat); } } // TBA: Delete folders } } else { UnitData removed = lstUnits.Remove(); // There isn't much to do with it - units have no images } }
public void ShouldParseNoark4ConvertedArkivuttrekkXml() { // Code to convert NOARKIH.XML to addml.xml //string noarkihString = TestUtil.ReadFromFileInTestDataDir("noark4\\NOARKIH.XML"); //string addmlString = NoarkihToAddmlTransformer.Transform(noarkihString); // File is converted from NOARKIH.XML format var testDataDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\TestData\\noark4"); var workingDirectory = new WorkingDirectory(testDataDirectory, testDataDirectory); AddmlInfo addml = AddmlUtil.ReadFromFile(workingDirectory.Content().WithFile("addml.xml").FullName); AddmlDefinitionParser parser = new AddmlDefinitionParser(addml, workingDirectory, new StatusEventHandler()); AddmlDefinition addmlDefinition = parser.GetAddmlDefinition(); List <AddmlFlatFileDefinition> addmlFlatFileDefinitions = addmlDefinition.AddmlFlatFileDefinitions; addmlFlatFileDefinitions.Count.Should().Be(63); addmlFlatFileDefinitions[0].Name.Should().Be("ORDNPRINSTYPE"); addmlFlatFileDefinitions[0].FileName.Should().Be("OPRITYP.XML"); addmlFlatFileDefinitions[0].Encoding.Should().Be(Encodings.ISO_8859_1); addmlFlatFileDefinitions[0].RecordSeparator.Should().BeNull(); addmlFlatFileDefinitions[0].AddmlRecordDefinitions.Count.Should().Be(1); AddmlRecordDefinition addmlRecordDefinition = addmlFlatFileDefinitions[0].AddmlRecordDefinitions[0]; addmlRecordDefinition.Name.Should().Be("ORDNPRINSTYPE"); List <AddmlFieldDefinition> addmlFieldDefinitions = addmlRecordDefinition.AddmlFieldDefinitions; addmlFieldDefinitions.Count.Should().Be(2); addmlFieldDefinitions[0].Name.Should().Be("OT.KODE"); addmlFieldDefinitions[0].Type.Should().Be(StringDataType.Default); addmlFieldDefinitions[1].Name.Should().Be("OT.BETEGN"); addmlFieldDefinitions[1].Type.Should().Be(StringDataType.Default); addmlRecordDefinition.PrimaryKey.Should().BeNull(); }
protected override void Action(string[] args) { // Minimum number of args is 2 if (args[0] == "" || args[1] == "") { Log.PrintLineError("You should specify to files!"); return; } // Get full paths of "from" and "to" files var sourceFilePath = WorkingDirectory.GetCombinedWith(args[0]); var destinationFilePath = WorkingDirectory.GetCombinedWith(args[1]); // Source should be and output shouldn`t exist if (!File.Exists(sourceFilePath)) { Log.PrintLineError("File you specified is not exists!"); return; } if (File.Exists((destinationFilePath))) { Log.PrintLineError("Destination file shouldn`t be exists!"); return; } // Actual copying with error handling try { File.Copy(sourceFilePath, destinationFilePath); } catch (Exception e) { Log.PrintLineError("Can`t copy a file!"); throw; } }
public void RunMultiyearTest() { PrepareUnitTest(); string fn = WorkingDirectory.Combine("trend.xlsx"); Config.LimitToScenarios.Clear(); Config.InitializeSlices(Logger); MultiyearTrend trend = new MultiyearTrend(); Random rnd = new Random(); if (Config.Slices == null) { throw new FlaException("No slices"); } trend[Constants.PresentSlice].AddValue("MyValue", 50, DisplayUnit.Stk); foreach (var slice in Config.Slices) { trend[slice].AddValue("MyValue", rnd.Next(100), DisplayUnit.Stk); } XlsxDumper.DumpMultiyearTrendToExcel(fn, trend); Info("Wrote to " + fn); Process.Start(fn); }
protected virtual void ValidateFilename(CodeActivityContext context, bool lookForFilesInPATH) { var workingDirectory = WorkingDirectory.Get(context); if (string.IsNullOrEmpty(workingDirectory)) { workingDirectory = Directory.GetCurrentDirectory(); } var filename = FileName.Get(context); if (Path.IsPathRooted(filename) && !File.Exists(filename)) { throw new ArgumentException("Filename with absolute path could not be found."); } else { if (Path.GetFileName(filename) == filename) { if (lookForFilesInPATH && !Environment.GetEnvironmentVariable("PATH").Split(';'). Any(dir => (string.IsNullOrEmpty(Path.GetExtension(filename)) && // The given filename does not have an extension but matches one file from the directories in PATH Directory.GetFiles(dir).Any(file => Path.GetFileNameWithoutExtension(file) == filename)) || File.Exists(Path.Combine(dir, filename)))) // Filename is present in one of the directories from PATH { throw new ArgumentException("Filename could not be found in the working directory or in any directory from the PATH Environment Variable."); } } else { if (!File.Exists(Path.Combine(workingDirectory, filename))) { throw new ArgumentException("Filename with relative path could not be found in the current working directory."); } } } }
public override string ToArgs() { List <string> options = new List <string> { Url.Formatted(), Driver.Formatted(), User.Formatted(), Password.Formatted(), ConnectRetries.Formatted(), InitSql.Formatted(), Schemas.Formatted(), Color.Formatted(), DefaultSchema.Formatted(), JarDirs.Formatted(), Callbacks.Formatted(), SkipDefaultCallbacks.Formatted(), CleanDisabled.Formatted(), ValidateMigrationNaming.Formatted(), WorkingDirectory.Formatted(), LicenseKey.Formatted() }; return(ToArgs(options)); }
public CakeHost(IFrostingContext context, Container container, CakeHostOptions options, IFileSystem fileSystem, ICakeEnvironment environment, ICakeEngine engine, ICakeLog log, IToolInstaller installer, IEnumerable <PackageReference> tools, EngineInitializer engineInitializer, CommandFactory commandFactory, WorkingDirectory workingDirectory = null, IEnumerable <IFrostingTask> tasks = null, IFrostingLifetime lifetime = null, IFrostingTaskLifetime taskLifetime = null) { Guard.ArgumentNotNull(context, nameof(context)); Guard.ArgumentNotNull(container, nameof(container)); Guard.ArgumentNotNull(options, nameof(options)); Guard.ArgumentNotNull(fileSystem, nameof(fileSystem)); Guard.ArgumentNotNull(environment, nameof(environment)); Guard.ArgumentNotNull(engine, nameof(engine)); Guard.ArgumentNotNull(log, nameof(log)); Guard.ArgumentNotNull(engineInitializer, nameof(engineInitializer)); Guard.ArgumentNotNull(commandFactory, nameof(commandFactory)); // Mandatory arguments. _context = context; _container = container; _options = options; _fileSystem = fileSystem; _environment = environment; _engine = engine; _log = log; _installer = installer; _tools = new List <PackageReference>(tools ?? Enumerable.Empty <PackageReference>()); _engineInitializer = engineInitializer; _commandFactory = commandFactory; // Optional arguments. _workingDirectory = workingDirectory; _tasks = tasks; _lifetime = lifetime; _taskLifetime = taskLifetime; }
/// <summary> /// Constructor /// </summary> /// <param name="workingDirectory"></param> public ListCommand(WorkingDirectory workingDirectory) { this.workingDirectory = workingDirectory; }
private void DoExecute() { string[] args = this._args; CommandLineParser parser = new CommandLineParser(args); ICommand command = null; try { command = parser.Execute(); } catch (CommandLineParseException e) { Writer.WriteLine( String.Format("{0}{1}{2}", Usage.General, Environment.NewLine, e.Message)); return; } catch (Exception e) { ExitProgram("Exception parsing command.", e); } if (null != command) { // might need to move this up to the library, make working // directory a public property?? Not sure. WorkingDirectory workingDirectory = parser.CurrentWorkingDirectory; string password = this.GetPassword(parser, workingDirectory); // Create CVSServerConnection object that has the ICommandConnection CVSServerConnection serverConn = new CVSServerConnection(workingDirectory); if (parser.Verbose) { serverConn.RequestMessageEvent += new MessageEventHandler(Writer.WriteLine); serverConn.ResponseMessageEvent += new MessageEventHandler(Writer.WriteLine); } serverConn.StartProcessEvent += new ProcessEventHandler(Writer.StartProcess); serverConn.StopProcessEvent += new ProcessEventHandler(Writer.StopProcess); serverConn.ResponseMessageEvents.UpdatedResponseMessageEvent += new MessageEventHandler(Writer.WriteLine); serverConn.ResponseMessageEvents.ClearStaticDirectoryResponseMessageEvent += new MessageEventHandler(Writer.WriteLine); serverConn.ResponseMessageEvents.SetStaticDirectoryResponseMessageEvent += new MessageEventHandler(Writer.WriteLine); serverConn.ResponseMessageEvents.ErrorResponseMessageEvent += new MessageEventHandler(Writer.WriteError); serverConn.ResponseMessageEvents.ListResponseMessageEvent += new MessageEventHandler(Writer.WriteLine); if (null == serverConn) { string msg = "Unable to connect to server."; ExitProgram(msg); } try{ // try connecting with empty password for anonymous users serverConn.Connect(workingDirectory, password); } catch (AuthenticationException e) { string msg = String.Format("Fatal error, aborting. cvs [login aborted]: {0}: unknown user or bad password.", workingDirectory.CvsRoot.User); ExitProgram(msg, e); } catch (Exception ex) { string msg = String.Format("Fatal cvs error ( {0} ).", ex.Message); ExitProgram(msg, ex); } // Execute the command on cvs repository. command.Execute(serverConn); serverConn.Close(); } }
public void Dispose() { WorkingDirectory.Dispose(); }
public void ShouldParseJegerreg98ArkivuttrekkXml() { var externalContentDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\..\\..\\TestData\\jegerreg-98-dos\\"); var workingDirectory = new WorkingDirectory(ArkadeConstants.GetArkadeWorkDirectory(), externalContentDirectory); AddmlInfo addml = AddmlUtil.ReadFromFile(workingDirectory.Content().WithFile("arkivuttrekk.xml").FullName); AddmlDefinition addmlDefinition = new AddmlDefinitionParser(addml, workingDirectory).GetAddmlDefinition(); List <AddmlFlatFileDefinition> addmlFlatFileDefinitions = addmlDefinition.AddmlFlatFileDefinitions; addmlFlatFileDefinitions.Count.Should().Be(10); { addmlFlatFileDefinitions[0].Name.Should().Be("ffd_3"); addmlFlatFileDefinitions[0].FileName.Should().Be("jeger.dat"); addmlFlatFileDefinitions[0].Encoding.Should().Be(Encodings.ISO_8859_1); addmlFlatFileDefinitions[0].RecordSeparator.Should().Be(Separator.CRLF); addmlFlatFileDefinitions[0].AddmlRecordDefinitions.Count.Should().Be(1); AddmlRecordDefinition addmlRecordDefinition = addmlFlatFileDefinitions[0].AddmlRecordDefinitions[0]; List <AddmlFieldDefinition> addmlFieldDefinitions = addmlRecordDefinition.AddmlFieldDefinitions; addmlFieldDefinitions.Count.Should().Be(36); addmlFieldDefinitions[0].Name.Should().Be("fodselsnummer"); addmlRecordDefinition.PrimaryKey.Should() .Equal(new List <AddmlFieldDefinition>() { addmlFieldDefinitions[0] }); } { addmlFlatFileDefinitions[1].Name.Should().Be("ffd_4"); addmlFlatFileDefinitions[1].FileName.Should().Be("ut_jeger.dat"); addmlFlatFileDefinitions[1].Encoding.Should().Be(Encodings.ISO_8859_1); addmlFlatFileDefinitions[1].RecordSeparator.Should().Be(Separator.CRLF); addmlFlatFileDefinitions[1].AddmlRecordDefinitions.Count.Should().Be(1); AddmlRecordDefinition addmlRecordDefinition = addmlFlatFileDefinitions[1].AddmlRecordDefinitions[0]; List <AddmlFieldDefinition> addmlFieldDefinitions = addmlRecordDefinition.AddmlFieldDefinitions; addmlFieldDefinitions.Count.Should().Be(37); addmlFieldDefinitions[0].Name.Should().Be("plassnummer"); addmlFieldDefinitions[0].Type.Should().Be(IntegerDataType.Default); addmlFieldDefinitions[1].Name.Should().Be("landkort"); addmlFieldDefinitions[8].Name.Should().Be("personnummer"); addmlRecordDefinition.PrimaryKey.Should() .Equal(new List <AddmlFieldDefinition>() { addmlFieldDefinitions[0], addmlFieldDefinitions[1], addmlFieldDefinitions[8] }); } { addmlFlatFileDefinitions[2].Name.Should().Be("ffd_5"); addmlFlatFileDefinitions[2].FileName.Should().Be("ikkejeg.dat"); addmlFlatFileDefinitions[2].Encoding.Should().Be(Encodings.ISO_8859_1); addmlFlatFileDefinitions[2].RecordSeparator.Should().Be(Separator.CRLF); addmlFlatFileDefinitions[2].AddmlRecordDefinitions.Count.Should().Be(1); AddmlRecordDefinition addmlRecordDefinition = addmlFlatFileDefinitions[2].AddmlRecordDefinitions[0]; List <AddmlFieldDefinition> addmlFieldDefinitions = addmlRecordDefinition.AddmlFieldDefinitions; addmlFieldDefinitions.Count.Should().Be(44); addmlFieldDefinitions[0].Name.Should().Be("fodselsnummer"); addmlFieldDefinitions[0].StartPosition.Should().Be(1); addmlFieldDefinitions[0].FixedLength.Should().Be(11); addmlFieldDefinitions[0].IsUnique.Should().BeTrue(); addmlFieldDefinitions[0].IsNullable.Should().BeFalse(); addmlFieldDefinitions[0].MaxLength.Should().NotHaveValue(); addmlFieldDefinitions[0].MinLength.Should().NotHaveValue(); addmlFieldDefinitions[0].Type.Should().Be(StringDataType.Default); addmlFieldDefinitions[0].ForeignKey.Should().Be( addmlFlatFileDefinitions[0].AddmlRecordDefinitions[0].AddmlFieldDefinitions[0] ); addmlFieldDefinitions[1].Name.Should().Be("etternavn"); addmlFieldDefinitions[1].StartPosition.Should().Be(12); addmlFieldDefinitions[1].FixedLength.Should().Be(25); addmlFieldDefinitions[1].IsUnique.Should().BeFalse(); addmlFieldDefinitions[1].IsNullable.Should().BeTrue(); addmlFieldDefinitions[1].MaxLength.Should().NotHaveValue(); addmlFieldDefinitions[1].MinLength.Should().NotHaveValue(); addmlFieldDefinitions[1].Type.Should().Be(StringDataType.Default); addmlFieldDefinitions[1].ForeignKey.Should().BeNull(); addmlRecordDefinition.PrimaryKey.Should() .Equal(new List <AddmlFieldDefinition>() { addmlFieldDefinitions[0] }); TestDateDataType(addmlDefinition); TestBooleanDataType(addmlDefinition); TestFloatDataType(addmlDefinition); } }
public override int GetHashCode() { return(ProjectHome.GetHashCode() ^ WorkingDirectory.GetHashCode() ^ InterpreterPath.GetHashCode()); }
/// <summary> /// Produce the report /// Alternate interface for when we are given a server cooection /// This is needed for the SharpCvsLib command line client /// </summary> public LogReport Run(ICommandConnection connection) { // read Root and Repository from local directory if (null == this.cvsRoot) { Manager manager = new Manager(localDirectory); Root root = (Root)manager.FetchSingle(localDirectory, Factory.FileType.Root); this.cvsRoot = new CvsRoot(root.FileContents); } if (null == workingDirectory) { Manager manager = new Manager(localDirectory); Repository repository = (Repository)manager.FetchSingle(localDirectory, Factory.FileType.Repository); this.workingDirectory = new WorkingDirectory(cvsRoot, localDirectory, repository.FileContents); } ILogCommand command; // Recursively add all cvs folders/files under the localDirectory System.Console.WriteLine("GNE workingDirectory.WorkingPath = {0}", workingDirectory.WorkingPath); System.Console.WriteLine("GNE localDirectory: {0}", localDirectory); // if (Directory.Exists(workingDirectory.WorkingPath)) { if (Directory.Exists(localDirectory) && File.Exists(Path.Combine(localDirectory, "Repository"))) { workingDirectory.FoldersToUpdate = FetchFiles(localDirectory); command = new LogCommand(workingDirectory, this.workingDirectory.ModuleName, null); } else { command = // GNE - this wont compile new LogCommand(workingDirectory, this.workingDirectory.ModuleName); new RLogCommand(workingDirectory, this.workingDirectory.ModuleName); } // add any date restrictions if (hasStartDate && hasEndDate) { command.AddInclusiveDateRange(startDate, endDate); } else if (hasStartDate) { command.AddInclusiveDateStart(startDate); } else if (hasEndDate) { command.AddInclusiveDateEnd(endDate); } // Initialse state machine curLogReport = new LogReport(); // this is what we are going to return to the caller curLogFile = new LogFile(this.cvsRoot); curLogRevision = new LogRevision(); logState = LogState.WANT_FILE_HEADER_START; if (connection.GetType() == typeof(CVSServerConnection)) { CVSServerConnection cvsServerConnection = (CVSServerConnection)connection; cvsServerConnection.MessageEvent.MessageEvent += new EncodedMessage.MessageHandler(OnMessage); } command.Execute(connection); // return curLogReport but clear our reference to it LogReport report = curLogReport; curLogReport = null; return(report); }
public void RunMultiHpTest() { PrepareUnitTest(); // ReSharper disable twice AssignNullToNotNullAttribute ServiceRepository services = new ServiceRepository(null, null, Logger, Config, new Random()); var dbRaw = services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Raw, Constants.PresentSlice); var dbHouse = services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, new ScenarioSliceParameters(Scenario.FromEnum(ScenarioEnum.Utopia), 2050, null)); var temperatures = dbRaw.Fetch <TemperatureProfileImport>(); var heatPumpEntries = dbHouse.Fetch <HeatingSystemEntry>(); Profile temperaturProfileHourly = new Profile(temperatures[0].Profile ?? throw new FlaException("was null")); Random rnd = new Random(); //make heatpumpprofile Profile houseEnergy = Profile.MakeConstantProfile(0, "House Energy", Profile.ProfileResolution.QuarterHour); Profile heatPumpEnergysupply = Profile.MakeConstantProfile(0, "Heat pump Energy supply", Profile.ProfileResolution.QuarterHour); Profile heatPumpEnergyDemand = Profile.MakeConstantProfile(0, "Heat pump Energy Demand", Profile.ProfileResolution.QuarterHour); Profile temperatureProfile15Min = null; List <Profile> allHouseDemandProfiles = new List <Profile>(); foreach (var entry in heatPumpEntries) { HeatpumpProfileGenerator chp = new HeatpumpProfileGenerator(temperaturProfileHourly, 15, 20, Logger); var hpcp = HeatpumpCalculationParameters.MakeDefaults(); hpcp.StartingTimeStepEvenings = (21 * 4) + rnd.Next(12); hpcp.StoppingTimeStepMorning = (4 * 4) + rnd.Next(12); hpcp.HouseMinimumEnergyTriggerinPercent = 0.70 - rnd.NextDouble() * 0.2; hpcp.TargetMaximumRuntimePerDay = 16 + rnd.NextDouble() * 4; hpcp.TimingMode = HeatPumpTimingMode.OverTheEntireDay; hpcp.StartLevelPercent = 1 - rnd.NextDouble() * .5; HeatPumpResult hpr = chp.Run(hpcp, entry.EffectiveEnergyDemand, rnd); var result = hpr.GetEnergyDemandProfile(); result.Name += entry.Standort; allHouseDemandProfiles.Add(result); result.Values.Sum().Should().BeApproximately(entry.EffectiveEnergyDemand * .333, entry.EffectiveEnergyDemand * 0.1); heatPumpEnergyDemand = heatPumpEnergyDemand.Add(result, heatPumpEnergyDemand.Name); houseEnergy = houseEnergy.Add(hpr.HouseEnergyTracker.AsReadOnly()); heatPumpEnergysupply = heatPumpEnergysupply.Add(hpr.HeatpumpEnergySupply.AsReadOnly()); if (temperatureProfile15Min == null) { temperatureProfile15Min = new Profile("Temperatures", hpr.DailyAvgTemperatures15Min.ToList().AsReadOnly(), EnergyOrPower.Energy); } } allHouseDemandProfiles.Sort((x, y) => y.EnergySum().CompareTo(x.EnergySum())); var profilesToShow = allHouseDemandProfiles.Take(5).ToList(); var profilesToMerge = allHouseDemandProfiles.Skip(6).ToList(); var mergedProfiles = allHouseDemandProfiles[5].Add(profilesToMerge, "MergedProfiles"); if (temperatureProfile15Min == null) { throw new FlaException("no temperatures"); } ProfileWorksheetContent biggestConsumers = new ProfileWorksheetContent("Biggest Consumers", "Last", profilesToShow); biggestConsumers.Profiles.Add(mergedProfiles); string fullFileName = WorkingDirectory.Combine("heatpump_profiles_multi-WithChart.xlsx"); XlsxDumper.DumpProfilesToExcel(fullFileName, 2017, 15, new ProfileWorksheetContent("Energy Demand", "Last", 240, heatPumpEnergyDemand), new ProfileWorksheetContent("Energy Supply", "Energieversorgung", 240, heatPumpEnergysupply), new ProfileWorksheetContent("Temperatures", "Temperatur", 240, temperatureProfile15Min), new ProfileWorksheetContent("House Energy", "Haus Energiegehalt", 240, houseEnergy), biggestConsumers); //WriteProfilesToExcel(temperatureProfile15Min, houseEnergy, heatPumpEnergysupply,file); }
/// <summary> /// Constructor /// </summary> /// <param name="workingDirectory"></param> /// <param name="directory">relative to the root of the working directory. /// null for the entire working directory</param> /// <param name="entry">null for all files</param> public ListCommand(WorkingDirectory workingDirectory, string directory, Entry entry) { this.workingDirectory = workingDirectory; this.directory = directory; this.entry = entry; }
internal static string GetWorkingDirectory(WorkingDirectory wd) { string path = Path.Combine(Application.StartupPath, wd.ToString()); DirectoryInfo di = new DirectoryInfo(path); if (!di.Exists) di.Create(); return path; }
/// <summary> /// Parse the command line options. There are two (2) general sweeps /// at parsing the command line. The first sweep looks for command line /// help switches, denoted by -- parameters. /// </summary> /// <returns>A command object from the library which will be used to /// access the repsository.</returns> /// <exception cref="CommandLineParseException">If there is a problem /// parsing the command line arguments (i.e. if invalid arguments /// are entered.</exception> public ICommand Execute() { if (LOGGER.IsDebugEnabled) { StringBuilder msg = new StringBuilder(); msg.Append("\n Command line arguments:"); foreach (String argument in this.arguments) { msg.Append("\n\t argument=[").Append(argument).Append("]"); } LOGGER.Debug(msg); } bool isHelp = this.ParseHelp(this.arguments); if (isHelp) { return(null); } int startIndex = 0; // TODO: Remove = null when all other code paths return a value, // this was just put in so it would compile. ICommand command = null; if (arguments.Length < 1) { System.Console.WriteLine(Usage.General); } if (arguments.Length > 0 && (arguments[0] == "-d")) { this.cvsRoot = new CvsRoot(this.arguments[1]); startIndex = 2; } else if (arguments.Length > 0 && (arguments[0].Length > 2) && arguments[0].Substring(0, 2) == "-d") { this.cvsRoot = new CvsRoot(this.arguments[0].Substring(2).Trim()); startIndex = 1; } for (int i = startIndex; i < arguments.Length; i++) { if (LOGGER.IsDebugEnabled) { StringBuilder msg = new StringBuilder(); msg.Append("arguments[").Append(i).Append("]=[").Append(arguments[i]).Append("]"); LOGGER.Debug(msg); } LOGGER.Debug("Before we grab the arguments."); string commandString = arguments[i].Trim(); CommandParserFactory factory; ICommandParser parser; switch (commandString) { case "add": case "ad": case "new": // no single options for the Add command this.commandTxt = arguments[i]; i++; // get rest of arguments which is options on the commit command. while (arguments.Length > i && arguments[i].IndexOf("-", 0, 1) >= 0) { // Get options with second parameters? if (arguments[i].IndexOfAny(singleOptions.ToCharArray(), 1, 1) >= 0) { for (int cnt = 1; cnt < arguments[i].Length; cnt++) { this.options = this.options + "-" + arguments[i][cnt] + " "; // No } } else { this.options = this.options + arguments[i++]; // Yes this.options = this.options + arguments[i] + " "; } i++; } if (arguments.Length > i) { // Safely grab the module, if not specified then // pass null into the repository...the cvs command // line for cvsnt/ cvs seems to bomb out when // it sends to the server this.repository = arguments[i]; } else { this.repository = String.Empty; } AddCommandParser addCommand = new AddCommandParser(this.CvsRoot, repository, options); command = addCommand.CreateCommand(); this.currentWorkingDirectory = addCommand.CurrentWorkingDirectory; break; case "commit": case "ci": case "com": singleOptions = "DRcfln"; this.commandTxt = arguments[i]; i++; // get rest of arguments which is options on the commit command. while (arguments.Length > i && arguments[i].IndexOf("-", 0, 1) >= 0) { LOGGER.Debug("Parsing arguments. Argument[" + i + "]=[" + arguments[i]); // Get options with second parameters? if (arguments[i].IndexOfAny(singleOptions.ToCharArray(), 1, 1) >= 0) { for (int cnt = 1; cnt < arguments[i].Length; cnt++) { this.options = this.options + "-" + arguments[i][cnt] + " "; // No } } else { this.options = this.options + arguments[i++]; // Yes this.options = this.options + arguments[i] + " "; } i++; } if (arguments.Length > i) { // Safely grab the module, if not specified then // pass null into the repository...the cvs command // line for cvsnt/ cvs seems to bomb out when // it sends to the server this.repository = arguments[i]; } else { this.repository = String.Empty; } CommitCommandParser commitCommand = new CommitCommandParser(this.CvsRoot, repository, options); command = commitCommand.CreateCommand(); this.currentWorkingDirectory = commitCommand.CurrentWorkingDirectory; break; case "checkout": case "co": case "get": singleOptions = "ANPRcflnps"; this.commandTxt = arguments[i]; i++; // get rest of arguments which is options on the checkout command. while (arguments.Length > i && arguments[i].Trim().IndexOf("-") == 0) { // Get options with second parameters? if (arguments[i].Trim().IndexOfAny(singleOptions.ToCharArray(), 1, 1) >= 0) { for (int cnt = 1; cnt < arguments[i].Length; cnt++) { this.options = this.options + "-" + arguments[i][cnt] + " "; // No } } else { this.options = this.options + arguments[i++]; // Yes this.options = this.options + arguments[i] + " "; } i++; } if (arguments.Length > i) { // Safely grab the module, if not specified then // pass null into the repository...the cvs command // line for cvsnt/ cvs seems to bomb out when // it sends to the server this.repository = arguments[i]; } else { this.repository = String.Empty; } CheckoutCommandParser checkoutCommand = new CheckoutCommandParser(this.CvsRoot, this.Repository, options); command = checkoutCommand.CreateCommand(); this.currentWorkingDirectory = checkoutCommand.CurrentWorkingDirectory; break; case "import": case "imp": case "im": i++; string [] tempArgs = new string[arguments.Length - i]; Array.Copy(arguments, i, tempArgs, 0, arguments.Length - i); ImportCommandParser importCommand = new ImportCommandParser(this.CvsRoot, tempArgs); command = importCommand.CreateCommand(); this.currentWorkingDirectory = importCommand.CurrentWorkingDirectory; i = arguments.Length; break; case "init": this.commandTxt = arguments[i]; InitCommandParser initCommand = new InitCommandParser(this.CvsRoot); command = initCommand.CreateCommand(); this.currentWorkingDirectory = initCommand.CurrentWorkingDirectory; break; case "log": case "lo": this.commandTxt = arguments[i++]; string[] logArgs = new string[arguments.Length - i]; Array.Copy(arguments, i, logArgs, 0, arguments.Length - i); LogCommandParser logCommandParser = new LogCommandParser(this.CvsRoot, logArgs); command = logCommandParser.CreateCommand(); this.currentWorkingDirectory = logCommandParser.CurrentWorkingDirectory; i = arguments.Length; break; case "login": case "logon": case "lgn": // login to server this.commandTxt = arguments[i]; LoginCommand loginCommand = new LoginCommand(this.CvsRoot, this.currentWorkingDirectory); loginCommand.Args = arguments; this.currentWorkingDirectory = loginCommand.CurrentWorkingDirectory; command = loginCommand; break; case "dir": case "list": case "ls": factory = new CommandParserFactory("ls", arguments, this.cvsRoot, this.currentWorkingDirectory); parser = factory.GetCommandParser(); i = arguments.Length; command = parser.CreateCommand(); this.currentWorkingDirectory = parser.CurrentWorkingDirectory; break; case "passwd": case "password": case "setpass": this.commandTxt = arguments[i]; break; case "remove": case "delete": case "rm": singleOptions = "Rfl"; this.commandTxt = arguments[i]; i++; // get rest of arguments which is options on the update command. while (arguments.Length > i && arguments[i].IndexOf("-", 0, 1) >= 0) { // Get options with second parameters? if (arguments[i].IndexOfAny(singleOptions.ToCharArray(), 1, 1) >= 0) { for (int cnt = 1; cnt < arguments[i].Length; cnt++) { this.options = this.options + "-" + arguments[i][cnt] + " "; // No } } else { this.options = this.options + arguments[i]; // Yes this.options = this.options + arguments[i] + " "; } i++; } if (arguments.Length > i) { // Safely grab the module, if not specified then // pass null into the repository...the cvs command // line for cvsnt/ cvs seems to bomb out when // it sends to the server this.files = arguments[i++]; } else { this.files = String.Empty; } RemoveCommandParser removeCommand = new RemoveCommandParser(this.CvsRoot, files, options); command = removeCommand.CreateCommand(); this.currentWorkingDirectory = removeCommand.CurrentWorkingDirectory; break; case "rt": case "rtag": case "rtfreeze": singleOptions = "abBdfFlMnR"; this.commandTxt = arguments[i++]; // get rest of arguments which is options on the rtag command. while (arguments.Length > i && arguments[i].IndexOf("-", 0, 1) >= 0) { // Get options with second parameters? if (arguments[i].IndexOfAny(singleOptions.ToCharArray(), 1, 1) >= 0) { for (int cnt = 1; cnt < arguments[i].Length; cnt++) { this.options = this.options + "-" + arguments[i][cnt] + " "; // No } } else { this.options = this.options + arguments[i]; // Yes this.options = this.options + arguments[i] + " "; } i++; } if (arguments.Length > i) { // Safely grab the module, if not specified then // pass null into the repository...the cvs command // line for cvsnt/ cvs seems to bomb out when // it sends to the server this.repository = arguments[i++]; } else { this.repository = String.Empty; } RTagCommandParser rtagCommand = new RTagCommandParser(this.CvsRoot, repository, options); command = rtagCommand.CreateCommand(); this.currentWorkingDirectory = rtagCommand.CurrentWorkingDirectory; break; case "st": case "stat": case "status": string[] commandArgs = new string[arguments.Length - i]; Array.Copy(arguments, i, commandArgs, 0, arguments.Length - i); factory = new CommandParserFactory("status", commandArgs, this.cvsRoot, this.currentWorkingDirectory); parser = factory.GetCommandParser(); i = arguments.Length; command = parser.CreateCommand(); this.currentWorkingDirectory = parser.CurrentWorkingDirectory; break; case "up": case "upd": case "update": singleOptions = "ACPRbdfmp"; this.commandTxt = arguments[i++]; // get rest of arguments which is options on the update command. while (arguments.Length > i && arguments[i].IndexOf("-", 0, 1) >= 0) { // Get options with second parameters? if (arguments[i].IndexOfAny(singleOptions.ToCharArray(), 1, 1) >= 0) { for (int cnt = 1; cnt < arguments[i].Length; cnt++) { this.options = this.options + "-" + arguments[i][cnt] + " "; // No } } else { this.options = this.options + arguments[i]; // Yes this.options = this.options + arguments[i] + " "; } i++; } if (arguments.Length > i) { // Safely grab the module, if not specified then // pass null into the repository...the cvs command // line for cvsnt/ cvs seems to bomb out when // it sends to the server this.repository = arguments[i++]; } else { this.repository = String.Empty; } UpdateCommandParser updateCommand = new UpdateCommandParser(this.CvsRoot, repository, options); command = updateCommand.CreateCommand(); this.currentWorkingDirectory = updateCommand.CurrentWorkingDirectory; break; case "xml": factory = new CommandParserFactory("xml", arguments, this.cvsRoot, this.currentWorkingDirectory); // TODO: Move this outside of case statement when all commands use same pattern parser = factory.GetCommandParser(); i = arguments.Length; command = parser.CreateCommand(); this.currentWorkingDirectory = parser.CurrentWorkingDirectory; break; default: StringBuilder msg = new StringBuilder(); msg.Append("Unknown command entered. "); msg.Append("command=[").Append(arguments[i]).Append("]"); throw new CommandLineParseException(msg.ToString()); } } return(command); }
private void SetupSerilog() { LoggerConfiguration loggerConfiguration; try { var loggingPath = Path.Combine(WorkingDirectory, "logging.yaml"); if (!File.Exists(loggingPath)) { // First run, logging.yaml doesn't exist yet. // We can't wait for auto-copy from the assembly as it would be too late. using var stream = typeof(AsyncHelper).Assembly.GetManifestResourceStream("OpenMod.Core.logging.yaml"); using var reader = new StreamReader( stream ?? throw new MissingManifestResourceException( "Couldn't find resource: OpenMod.Core.logging.yaml")); var fileContent = reader.ReadToEnd(); File.WriteAllText(loggingPath, fileContent); } var configuration = new ConfigurationBuilder() .SetBasePath(WorkingDirectory) .AddYamlFileEx(s => { s.Path = "logging.yaml"; s.Optional = false; s.Variables = new Dictionary <string, string> { { "workingDirectory", WorkingDirectory.Replace(@"\", @"/") }, { "date", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") } }; s.ResolveFileProvider(); }) .AddEnvironmentVariables() .Build(); loggerConfiguration = new LoggerConfiguration() .ReadFrom.Configuration(configuration); } catch (Exception ex) { var previousColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("Failed to setup Serilog; logging will not work correctly."); Console.WriteLine("Setting up console only logging as workaround."); Console.WriteLine("Please fix your logging.yaml file or delete it to restore the default one."); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex); Console.ForegroundColor = previousColor; loggerConfiguration = new LoggerConfiguration() .WriteTo.Async(c => c.Console()); } var serilogLogger = Log.Logger = loggerConfiguration.CreateLogger(); m_LoggerFactory = new SerilogLoggerFactory(serilogLogger); m_Logger = m_LoggerFactory.CreateLogger <Runtime>(); }
/// <summary> /// Initializes a new instance of the VerbSyncWorker class. /// </summary> /// <param name="workingDirectory"> /// The private working directory for this worker to work in. /// </param> /// <param name="result">The Disposition to return on complete.</param> public VerbSyncWorker(WorkingDirectory workingDirectory, Disposition result) { this.workingDirectory = workingDirectory; this.result = result; }