private static void RunTest([NotNull] Action <GeneralConfig> setOption, [NotNull] string name) { CleanTestBase.RunAutomatically(false); using (var wd1 = new WorkingDir(Utili.GetCurrentMethodAndClass() + name)) { Logger.Threshold = Severity.Error; var path = wd1.WorkingDirectory; if (Directory.Exists(path)) { Directory.Delete(path, true); } Directory.CreateDirectory(path); using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) { var sim = new Simulator(db.ConnectionString); Config.IsInUnitTesting = true; Config.ExtraUnitTestChecking = false; sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.NoFiles); sim.MyGeneralConfig.WriteExcelColumn = "False"; //if (setOption == null) { throw new LPGException("Action was null."); } setOption(sim.MyGeneralConfig); Logger.Info("Temperature:" + sim.MyGeneralConfig.SelectedTemperatureProfile); Logger.Info("Geographic:" + sim.MyGeneralConfig.GeographicLocation); sim.Should().NotBeNull(); var cmf = new CalcManagerFactory(); CalculationProfiler calculationProfiler = new CalculationProfiler(); CalcStartParameterSet csps = new CalcStartParameterSet(sim.GeographicLocations[0], sim.TemperatureProfiles[0], sim.ModularHouseholds[0], EnergyIntensityType.Random, false, null, LoadTypePriority.All, null, null, null, sim.MyGeneralConfig.AllEnabledOptions(), new DateTime(2018, 1, 1), new DateTime(2018, 1, 2), new TimeSpan(0, 1, 0), ";", 5, new TimeSpan(0, 10, 0), false, false, false, 3, 3, calculationProfiler, wd1.WorkingDirectory, false); var cm = cmf.GetCalcManager(sim, csps, false);
public void GetDuplicateCalcManagerHouseholdTest() { using (var wd1 = new WorkingDir("GetDuplicateCalcManagerHouseholdTest1")) { CalculateOneHousehold(wd1.WorkingDirectory); using (var wd2 = new WorkingDir("GetDuplicateCalcManagerHouseholdTest2")) { CalculateOneHousehold(wd2.WorkingDirectory); var hhkeys = HouseholdKeyLogger.Load(wd1.SqlResultLoggingService); var afts1 = new CalcDeviceDtoLogger(wd1.SqlResultLoggingService); var aft1 = afts1.Load(hhkeys.Where(x => x.KeyType == HouseholdKeyType.Household).ToList()); var afts2 = new CalcDeviceDtoLogger(wd2.SqlResultLoggingService); var aft2 = afts2.Load(hhkeys.Where(x => x.KeyType == HouseholdKeyType.Household).ToList()); var devices1 = aft1.Select(x => x.Name).OrderBy(x => x).ToList(); var devices2 = aft2.Select(x => x.Name).OrderBy(x => x).ToList(); devices1.Should().BeEquivalentTo(devices2); var rfel1 = new ResultFileEntryLogger(wd1.SqlResultLoggingService); var rfes1 = rfel1.Load(); var rfel2 = new ResultFileEntryLogger(wd2.SqlResultLoggingService); var rfes2 = rfel2.Load(); rfes1.Should().BeEquivalentTo(rfes2, o => o.Excluding( x => x.SelectedMemberPath.EndsWith("FullFileName", StringComparison.InvariantCultureIgnoreCase))); CompareCsv(rfes1, rfes2); wd1.CleanUp(); wd2.CleanUp(); } } }
public void TestParallelLaunch() { WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass()); ParallelJsonLauncher.CopyAll(DatabaseSetup.AssemblyDirectory, wd.WorkingDirectory); using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) { Logger.Info("Assembly directory: " + DatabaseSetup.AssemblyDirectory); Directory.SetCurrentDirectory(wd.WorkingDirectory); HouseCreationAndCalculationJob hcj = new HouseCreationAndCalculationJob(); Simulator sim = new Simulator(db.ConnectionString); JsonCalcSpecification cspec = JsonCalcSpecification.MakeDefaultsForTesting(); cspec.DefaultForOutputFiles = OutputFileDefault.OnlySums; cspec.CalcOptions = new List <CalcOption>(); cspec.CalcOptions.Add(CalcOption.SumProfileExternalEntireHouse); hcj.CalcSpec = cspec; MakeSingleHouse(cspec, wd, hcj, sim.Houses[0], "house1"); MakeSingleHouse(cspec, wd, hcj, sim.Houses[1], "house2"); var fn = wd.Combine("profilegenerator.db3"); hcj.PathToDatabase = fn; HouseJobSerializer.WriteJsonToFile(wd.Combine("hj2.json"), hcj); File.Copy(db.FileName, fn, true); } ParallelJsonLauncher.ThrowOnInvalidFile = true; ParallelJsonLauncher.ParallelJsonLauncherOptions options = new ParallelJsonLauncher.ParallelJsonLauncherOptions(); options.JsonDirectory = wd.WorkingDirectory; ParallelJsonLauncher.LaunchParallel(options); //wd.CleanUp(1); }
public void RunJsonCalculatorTestForExternalTimeResolutionJsonFile() { Logger.Get().StartCollectingAllMessages(); using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { Directory.SetCurrentDirectory(wd.WorkingDirectory); using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) { string dbPath = wd.Combine("my.db3"); File.Copy(db.FileName, dbPath); Logger.Info("DB File Path: " + dbPath); JsonCalcSpecification jcs = new JsonCalcSpecification(); if (jcs.CalcOptions == null) { throw new LPGException("Calcoptions was null"); } jcs.DefaultForOutputFiles = OutputFileDefault.NoFiles; jcs.CalcOptions.Add(CalcOption.SumProfileExternalIndividualHouseholdsAsJson); jcs.StartDate = new DateTime(2019, 1, 1); jcs.EndDate = new DateTime(2019, 1, 3); jcs.ExternalTimeResolution = "00:15:00"; jcs.LoadTypePriority = LoadTypePriority.RecommendedForHouses; Simulator sim = new Simulator(db.ConnectionString); JsonCalculator jc = new JsonCalculator(); jc.StartHousehold(sim, jcs, sim.Houses[0].GetJsonReference(), null); } Directory.SetCurrentDirectory(wd.PreviousCurrentDir); wd.CleanUp(); } }
public void GetCalcManagerHouseTest() { using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) { var sim = new Simulator(db.ConnectionString); sim.MyGeneralConfig.ApplyOptionDefault(OutputFileDefault.OnlyOverallSum); //ConfigSetter.SetGlobalTimeParameters(sim.MyGeneralConfig); sim.Should().NotBeNull(); var cmf = new CalcManagerFactory(); CalculationProfiler calculationProfiler = new CalculationProfiler(); CalcStartParameterSet csps = new CalcStartParameterSet(sim.GeographicLocations[0], sim.TemperatureProfiles[0], sim.Houses[sim.Houses.MyItems.Count - 1], EnergyIntensityType.Random, false, null, LoadTypePriority.RecommendedForHouses, null, null, null, sim.MyGeneralConfig.AllEnabledOptions(), new DateTime(2015, 1, 15), new DateTime(2015, 1, 18), new TimeSpan(0, 1, 0), ";", -1, new TimeSpan(0, 1, 0), false, false, false, 3, 3, calculationProfiler, wd.WorkingDirectory, false); var cm = cmf.GetCalcManager(sim, csps, false); cm.Run(ReportCancelFunc); db.Cleanup(); } wd.CleanUp(); } }
public void RunColumnEntryLoggerTest() { using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { ColumnEntryLogger ael = new ColumnEntryLogger(wd.SqlResultLoggingService); HouseholdKey key = new HouseholdKey("hhkey"); List <IDataSaverBase> savers = new List <IDataSaverBase> { ael }; InputDataLogger idl = new InputDataLogger(savers.ToArray()); CalcLoadTypeDto cltd = new CalcLoadTypeDto("ltname", "kw", "kwh", 1, false, "guid".ToStrGuid()); CalcDeviceDto cdd = new CalcDeviceDto("device", "guid".ToStrGuid(), key, OefcDeviceType.Device, "devcatname", "", "guid".ToStrGuid(), "guid".ToStrGuid(), "loc"); ColumnEntry ce = new ColumnEntry("name", 1, "locname", "guid".ToStrGuid(), key, cltd, "oefckey", "devicecategory", cdd); List <ColumnEntry> aes = new List <ColumnEntry> { ce }; idl.Save(aes); var res = ael.Read(key); var s1 = JsonConvert.SerializeObject(aes, Formatting.Indented); var s2 = JsonConvert.SerializeObject(res, Formatting.Indented); File.WriteAllText(wd.Combine("original.json"), s1); File.WriteAllText(wd.Combine("deserialized.json"), s2); s1.Should().Be(s2); } //wd.CleanUp(); }
public void CalcAffordanceDtoLoggerTest() { using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { CalcAffordanceDtoLogger ael = new CalcAffordanceDtoLogger(wd.SqlResultLoggingService); HouseholdKey key = new HouseholdKey("hhkey"); List <IDataSaverBase> savers = new List <IDataSaverBase> { ael }; InputDataLogger idl = new InputDataLogger(savers.ToArray()); //CalcLoadTypeDto cldto = new CalcLoadTypeDto("loadtype", 1, "kw", "kwh", 1, true, "guid"); CalcProfileDto cpd = new CalcProfileDto("name", 1, ProfileType.Absolute, "source", Guid.NewGuid().ToStrGuid()); AvailabilityDataReferenceDto adrd = new AvailabilityDataReferenceDto("blub", "availguid".ToStrGuid()); CalcAffordanceDto cadto = new CalcAffordanceDto("blub", 1, cpd, "locname", "locguid".ToStrGuid(), true, new List <CalcDesireDto>(), 1, 100, PermittedGender.All, true, 1, 1, 1, 1, "affcat", false, false, new List <CalcAffordanceVariableOpDto>(), new List <VariableRequirementDto>(), ActionAfterInterruption.GoBackToOld, "timelimitname", 100, true, "srctrait", "guid".ToStrGuid(), adrd, key, BodilyActivityLevel.Low); cadto.AddDeviceTuple("devname", "deviguid".ToStrGuid(), cpd, "calcloadtypename", "loadtypeguid".ToStrGuid(), 1, new TimeSpan(0, 1, 0), 1, 1); List <IHouseholdKey> aes = new List <IHouseholdKey> { cadto }; idl.SaveList(aes); var res = ael.Load(key); var s1 = JsonConvert.SerializeObject(aes, Formatting.Indented); var s2 = JsonConvert.SerializeObject(res, Formatting.Indented); s1.Should().Be(s2); wd.CleanUp(); } }
public void TestLocationEntryBasics() { Config.IsInUnitTesting = true; using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { DateTime startdate = new DateTime(2018, 1, 1); DateTime enddate = startdate.AddMinutes(1000); CalcParameters calcParameters = CalcParametersFactory.MakeGoodDefaults().SetStartDate(startdate).SetEndDate(enddate).SetSettlingDays(0).EnableShowSettlingPeriod(); calcParameters.Options.Add(CalcOption.LocationsEntries); //FileFactoryAndTracker fft = new FileFactoryAndTracker(wd.WorkingDirectory,"blub",wd.InputDataLogger); //CalcLocation cl = new CalcLocation("blub", 1, Guid.NewGuid().ToStrGuid()); //Mock<ILogFile> lf = new Mock<ILogFile>(); //CalcPerson cp = MakeCalcPerson(cl,calcParameters,lf.Object); HouseholdKey key = new HouseholdKey("hh1"); TimeStep ts = new TimeStep(1, 0, false); LocationEntry le = new LocationEntry(key, "personName", "personGuid".ToStrGuid(), ts, "locname", "locguid".ToStrGuid()); DateStampCreator dsc = new DateStampCreator(calcParameters); using (OnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters)) { wd.InputDataLogger.AddSaver(new LocationEntryLogger(wd.SqlResultLoggingService)); old.AddLocationEntry(le); old.FinalSaveToDatabase(); } var lel = new LocationEntryLogger(wd.SqlResultLoggingService); var e = lel.Load(key); e.Count.Should().Be(1); wd.CleanUp(); } }
public void RegisterDeviceActivationTest() { using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService)); wd.InputDataLogger.AddSaver(new DeviceActivationEntryLogger(wd.SqlResultLoggingService)); wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService)); CalcParameters cp = CalcParametersFactory.MakeGoodDefaults().EnableShowSettlingPeriod(); using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hhname", wd.InputDataLogger)) { var key = new HouseholdKey(" hh1"); fft.HouseholdRegistry.RegisterHousehold(key, "hh key", HouseholdKeyType.Household, wd.InputDataLogger, "desc", null, null); fft.HouseholdRegistry.RegisterHousehold(Constants.GeneralHouseholdKey, "general", HouseholdKeyType.General, wd.InputDataLogger, "desc", null, null); DateStampCreator dsc = new DateStampCreator(cp); using OnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, cp); fft.HouseholdRegistry.RegisterHousehold(key, "hh key", HouseholdKeyType.Household, wd.InputDataLogger, "desc", null, null); CalcLoadTypeDto clt = new CalcLoadTypeDto("lt", "unitofpower", "unitofsum", 1, true, "guid".ToStrGuid()); TimeStep ts = new TimeStep(1, 1, true); CalcDeviceDto cdd = new CalcDeviceDto("devname", "".ToStrGuid(), key, OefcDeviceType.Device, "devcatname", "", Guid.NewGuid().ToStrGuid(), "locguid".ToStrGuid(), "locname"); DeviceActivationEntry aeue = new DeviceActivationEntry("affname", clt, 1, "activatorname", 1, ts, cdd); old.RegisterDeviceActivation(aeue); old.FinalSaveToDatabase(); } wd.CleanUp(); } }
protected override int Execute(string[] args) { using var executor = CreateExecutor(args); var sql = executor.ScriptDbContext(Context.Value()); if (!_output.HasValue()) { Reporter.WriteData(sql); } else { var output = _output.Value(); if (WorkingDir.HasValue()) { output = Path.Combine(WorkingDir.Value(), output); } var directory = Path.GetDirectoryName(output); if (!string.IsNullOrEmpty(directory)) { Directory.CreateDirectory(directory); } Reporter.WriteVerbose(Resources.WritingFile(_output.Value())); File.WriteAllText(output, sql, Encoding.UTF8); } return(base.Execute(args)); }
public void SaveTo(MsBuildConfiguration[] configs) { foreach (var cfg in configs) { if (StartActionQ != null) { cfg.SetConfigurationProperty("StartAction", StartActionQToString(StartActionQ)); } if (ExternalProgram != null) { cfg.SetConfigurationProperty("StartProgram", ExternalProgram.ToString()); } if (CommandLineArgs != null) { cfg.SetConfigurationProperty("StartArguments", CommandLineArgs.ToString()); } if (WorkingDir != null) { cfg.SetConfigurationProperty("StartWorkingDirectory", WorkingDir.ToString()); } if (DebuggerScript != null) { cfg.SetConfigurationProperty("StartDebuggerScript", DebuggerScript.ToString()); } } }
private void MakeWavFile() { using (WorkingDir wd = new WorkingDir()) { string audioExt = Path.GetExtension(this.AudioFile); #if true // .wav にもサラウンドとかある様なのでステレオにする。 File.Copy(this.AudioFile, wd.GetPath("1" + audioExt)); this.Batch( Consts.FFMPEG_FILE + " -i 1" + audioExt + " -ac 2 2.wav", wd.GetPath(".") ); #else if (StringTools.EqualsIgnoreCase(audioExt, ".wav")) { File.Copy(this.AudioFile, wd.GetPath("2.wav")); } else { File.Copy(this.AudioFile, wd.GetPath("1" + audioExt)); this.Run( Consts.FFMPEG_FILE + " -i 1" + audioExt + " 2.wav", wd.GetPath(".") ); } #endif File.Move(wd.GetPath("2.wav"), this.WavFile); } }
public static int wavFileToCsvFile(string rFile, string wFile, string stdoutFile) { int hz; if (File.Exists(rFile) == false) { throw new FileNotFoundException(rFile); } using (WorkingDir wd = new WorkingDir()) { string wHzFile = wd.makePath(); runCTools("/W2C " + rFile + " " + wFile + " " + wHzFile + " > " + stdoutFile); if (File.Exists(wFile) == false) { throw new FileNotFoundException(wFile); } hz = int.Parse(File.ReadAllText(wHzFile, Encoding.ASCII)); } if (IntTools.isRange(hz, 1, IntTools.IMAX) == false) { throw new Exception(".wav ファイルのサンプリングレートを認識出来ません。" + hz); } return(hz); }
/* * private static void CopyAll([NotNull] DirectoryInfo source, [NotNull] DirectoryInfo target) * { * Directory.CreateDirectory(target.FullName); * * // Copy each file into the new directory. * foreach (var fi in source.GetFiles()) * { * Logger.Info(string.Format(CultureInfo.CurrentCulture, @"Copying {0}\{1}", target.FullName, fi.Name)); * fi.CopyTo(Path.Combine(target.FullName, fi.Name), true); * } * * // Copy each subdirectory using recursion. * foreach (var diSourceSubDir in source.GetDirectories()) * { * var nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name); * CopyAll(diSourceSubDir, nextTargetSubDir); * } * }*/ public void RunDirectHouseholds() { using (DatabaseSetup db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) { using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { Simulator sim = new Simulator(db.ConnectionString); string dir = wd.Combine("DirectHouseJobs"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } foreach (var mhh in sim.ModularHouseholds.It) { HouseCreationAndCalculationJob hj = new HouseCreationAndCalculationJob("Households", "2019", "TK", HouseDefinitionType.HouseData); hj.House = new HouseData(Guid.NewGuid().ToStrGuid(), "HT01", 10000, 10000, "House for " + mhh.Name); hj.House.Households.Add(new HouseholdData(Guid.NewGuid().ToString(), mhh.Name, null, null, null, null, HouseholdDataSpecificationType.ByHouseholdName)); hj.House.Households[0].HouseholdNameSpec = new HouseholdNameSpecification(mhh.GetJsonReference()); SetCalcSpec(hj, sim); string fn = Path.Combine(dir, AutomationUtili.CleanFileName(mhh.Name) + ".json"); File.WriteAllText(fn, JsonConvert.SerializeObject(hj, Formatting.Indented)); } //CopyAll(new DirectoryInfo(dir), new DirectoryInfo(@"X:\HouseJobs\Blockstrom\DirectHouseholds")); } } }
public void RunTest() { using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { HouseholdKeyLogger ael = new HouseholdKeyLogger(wd.SqlResultLoggingService); HouseholdKey key = new HouseholdKey("hhkey"); List <IDataSaverBase> savers = new List <IDataSaverBase> { ael }; InputDataLogger idl = new InputDataLogger(savers.ToArray()); HouseholdKeyEntry ae1 = new HouseholdKeyEntry(key, "hhname", HouseholdKeyType.House, "desc", null, null); idl.Save(ae1); List <HouseholdKeyEntry> aes = new List <HouseholdKeyEntry> { ae1 }; var res = ael.Load(); var s1 = JsonConvert.SerializeObject(aes, Formatting.Indented); var s2 = JsonConvert.SerializeObject(res, Formatting.Indented); s1.Should().Be(s2); wd.CleanUp(); } }
public void CalcParameterLoggerTest() { CalcParameters cp = CalcParameters.GetNew(); cp.SetStartDate(2017, 1, 1); cp.SetEndDate(2018, 1, 1); cp.Enable(CalcOption.ActivationsPerHour); using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { SqlResultLoggingService srls = new SqlResultLoggingService(wd.WorkingDirectory); CalcParameterLogger cpl = new CalcParameterLogger(srls); cpl.Run(Constants.GeneralHouseholdKey, cp); GC.Collect(); GC.WaitForPendingFinalizers(); CalcParameters cp2 = cpl.Load(); GC.Collect(); GC.WaitForPendingFinalizers(); string s1 = JsonConvert.SerializeObject(cp, Formatting.Indented); string s2 = JsonConvert.SerializeObject(cp2, Formatting.Indented); s1.Should().Be(s2); cp2.IsSet(CalcOption.ActivationsPerHour).Should().BeTrue(); Assert.NotNull(cp2); wd.CleanUp(); } }
public static string GetFairFullPath(string path) { using (WorkingDir wd = new WorkingDir()) { string argsFile = wd.MakePath(); string outFile = wd.MakePath(); string molp = SecurityTools.MakePassword_9(); string[] args = { "//O", outFile, "//MOLP", molp, "//-E", "//$", JString.AsLine(path), }; File.WriteAllLines(argsFile, args, StringTools.ENCODING_SJIS); ProcessTools.Start(@"C:\Factory\Bodewig\DenebolaToolkit\FairFullPath.exe", "//R \"" + argsFile + "\"").WaitForExit(); string[] outLines = File.ReadAllLines(outFile, StringTools.ENCODING_SJIS) .Where(v => v.StartsWith(molp)) .Select(v => v.Substring(molp.Length)).ToArray(); if (outLines.Length != 1) { throw new Exception("不正なパス文字列です。"); } return(outLines[0]); } }
public void MakeMovie() { this.WD = new WorkingDir(); try { this.FFmpeg = new FFmpeg(); try { this.FFmpeg.Audio = new FFmpegMedia(); try { this.MakeMovie_Main(); } finally { this.FFmpeg.Audio.Dispose(); this.FFmpeg.Audio = null; } } finally { this.FFmpeg.Dispose(); this.FFmpeg = null; } } finally { this.WD.Dispose(); this.WD = null; } }
static void Main(string[] args) { try { onBoot(); // clear TMP -- HACK 何か変だ.. { using (WorkingDir wd = new WorkingDir()) { } FileTools.clearTMP(); } if (1 <= args.Length && args[0].ToUpper() == "//R") { main2(File.ReadAllLines(args[1], Encoding.GetEncoding(932))); } else if (1 <= args.Length && args[0].ToUpper() == "//R8") { main2(File.ReadAllLines(args[1], Encoding.UTF8)); } else { main2(args); } } catch (Exception e) { Console.WriteLine(e); } }
public void RunTest() { using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { ActionEntryLogger ael = new ActionEntryLogger(wd.SqlResultLoggingService); HouseholdKey key = new HouseholdKey("hhkey"); List <IDataSaverBase> savers = new List <IDataSaverBase> { ael }; InputDataLogger idl = new InputDataLogger(savers.ToArray()); TimeStep ts = new TimeStep(1, 0, true); ActionEntry ae1 = new ActionEntry("blub", key, ts, DateTime.Now, "123".ToStrGuid(), "name", false, "affname", "affguid".ToStrGuid(), 0, BodilyActivityLevel.Low); List <IHouseholdKey> aes = new List <IHouseholdKey> { ae1 }; idl.SaveList(aes); var res = ael.Read(key); var s1 = JsonConvert.SerializeObject(aes, Formatting.Indented); var s2 = JsonConvert.SerializeObject(res, Formatting.Indented); s1.Should().Be(s2); wd.CleanUp(); } }
public void TestImportWithHouseholdTemplateDelete880() { const string srcFileName = "profilegenerator880.db3"; string sourcepath = DatabaseSetup.GetImportFileFullPath(srcFileName); if (!File.Exists(sourcepath)) { throw new LPGException("Missing file!"); } using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { var newpath = Path.Combine(wd.WorkingDirectory, "mergertest.db3"); File.Copy(sourcepath, newpath); using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) { var mainSim = new Simulator(db.ConnectionString); db.ClearTable(HouseholdTemplate.TableName); Database.DatabaseMerger.DatabaseMerger dbm = new Database.DatabaseMerger.DatabaseMerger(mainSim); dbm.RunFindItems(newpath, null); dbm.RunImport(null); db.Cleanup(); } wd.CleanUp(); } }
private static void TestImport([JetBrains.Annotations.NotNull] string path, [JetBrains.Annotations.NotNull] out Simulator mainsim, [JetBrains.Annotations.NotNull] out Database.DatabaseMerger.DatabaseMerger dbm) { var di = new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), path)); Logger.Debug(di.FullName); var fi = FindImportFiles(path); using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { var newpath = Path.Combine(wd.WorkingDirectory, "mergertest.db3"); File.Copy(fi.FullName, newpath); using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) { var mainSim = new Simulator(db.ConnectionString); dbm = new Database.DatabaseMerger.DatabaseMerger(mainSim); dbm.RunFindItems(newpath, null); dbm.RunImport(null); mainsim = mainSim; db.Cleanup(); } wd.CleanUp(); } }
public void ReadTest() { using (WorkingDir wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { DeviceActivationEntryLogger ael = new DeviceActivationEntryLogger(wd.SqlResultLoggingService); HouseholdKey key = new HouseholdKey("hhkey"); List <IDataSaverBase> savers = new List <IDataSaverBase> { ael }; InputDataLogger idl = new InputDataLogger(savers.ToArray()); CalcLoadTypeDto cldto = new CalcLoadTypeDto("loadtype", "kw", "kwh", 1, true, "guid".ToStrGuid()); TimeStep ts = new TimeStep(1, 1, true); CalcDeviceDto cdd = new CalcDeviceDto("devicename", "device".ToStrGuid(), key, OefcDeviceType.Device, "devicecategoryname", "additionalname", "deviceguid".ToStrGuid(), "locationguid".ToStrGuid(), "locationname"); DeviceActivationEntry ae1 = new DeviceActivationEntry("affordancename", cldto, 1, "activator", 1, ts, cdd); List <IHouseholdKey> aes = new List <IHouseholdKey> { ae1 }; idl.SaveList(aes); var res = ael.Read(key); var s1 = JsonConvert.SerializeObject(aes, Formatting.Indented); var s2 = JsonConvert.SerializeObject(res, Formatting.Indented); s1.Should().Be(s2); wd.CleanUp(); } }
private void refreshUI_main() { int quality = this.barQuality.Value; if (quality == _lastQuality) { return; } if (quality <= 100) { using (WorkingDir wd = new WorkingDir()) { string imgFile = wd.makePath() + ".jpg"; { EncoderParameters eps = new EncoderParameters(1); eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); _imgSample.Save(imgFile, Utils.getImageCodecInfo(ImageFormat.Jpeg), eps); } this.pbSample.Image = Bitmap.FromStream(new MemoryStream(File.ReadAllBytes(imgFile))); } } else { this.pbSample.Image = _imgSample; } this.lblQuality.Text = "画質 = " + quality; _lastQuality = quality; GC.Collect(); }
public static WorkingDir SetupDB3([JetBrains.Annotations.NotNull] string name, bool clearTemplatedFirst = false) { var srcPath = DatabaseSetup.GetSourcepath(null); Config.CatchErrors = false; var wd = new WorkingDir(name); var dstfullName = Path.Combine(wd.WorkingDirectory, "profilegenerator.db3"); Config.IsInUnitTesting = true; if (File.Exists("profilegenerator.db3")) { File.Delete("profilegenerator.db3"); } File.Copy(srcPath, dstfullName); Directory.SetCurrentDirectory(wd.WorkingDirectory); Logger.Info("Using directory:" + Directory.GetCurrentDirectory()); var connectionString = "Data Source=" + dstfullName; // ReSharper disable once UseObjectOrCollectionInitializer Simulator sim = new Simulator(connectionString); sim.MyGeneralConfig.DeviceProfileHeaderMode = DeviceProfileHeaderMode.Standard; if (clearTemplatedFirst) { sim.FindAndDeleteAllTemplated(); } DatabaseVersionChecker.CheckVersion(connectionString); Logger.Info("Checked database version. It is ok."); return(wd); }
private void MasteringWavFile() { using (WorkingDir wd = new WorkingDir()) { File.Copy(this.WavFile, wd.GetPath("1.wav")); this.Batch( Consts.MASTER_FILE + " /E " + Consts.EV_STOP_MASTER + " /-LV 1.wav 2.wav 3.txt", wd.GetPath(".") ); Ground.I.Logger.Info("Master.exe Log: " + File.ReadAllText(wd.GetPath("3.txt"), StringTools.ENCODING_SJIS)); if (File.Exists(wd.GetPath("2.wav"))) // ? 音量調整した。 { Ground.I.Logger.Info("音量調整_Y"); } else // ? 音量調整しなかった。 { Ground.I.Logger.Info("音量調整_N"); File.Copy(wd.GetPath("1.wav"), wd.GetPath("2.wav")); // そのままコピー } File.Move(wd.GetPath("2.wav"), this.MasterWavFile); } }
public void Test01() { PictureData picture = new PictureData(new Canvas2(@"C:\wb2\20191204_ジャケット的な\バンドリ_イニシャル.jpg"), 1920, 1080); const int FRAME_NUM = 200; const int D_MAX = 20; int dTarg = D_MAX; int d = D_MAX; using (WorkingDir wd = new WorkingDir()) { FileTools.CreateDir(wd.GetPath("img")); for (int frame = 0; frame < FRAME_NUM; frame++) { Console.WriteLine(frame); // test picture.SetFrame(frame * 1.0 / FRAME_NUM); // ---- 暗くする ---- if (frame == 10) { dTarg = 0; } else if (frame + 10 + D_MAX == FRAME_NUM) { dTarg = D_MAX; } if (d < dTarg) { d++; } else if (dTarg < d) { d--; } if (0 < d) { picture.SetDrakness(d * 1.0 / D_MAX); } // ---- picture.Save(wd.GetPath("img\\" + frame + ".jpg")); } ProcessTools.Batch(new string[] { @"C:\app\ffmpeg-4.1.3-win64-shared\bin\ffmpeg.exe -r 20 -i %%d.jpg ..\out.mp4", }, wd.GetPath("img") ); File.Copy(wd.GetPath("out.mp4"), @"C:\temp\1.mp4", true); } }
protected override int Execute() { var sql = CreateExecutor().ScriptMigration( _from.Value, _to.Value, _idempotent.HasValue(), Context.Value()); if (!_output.HasValue()) { Reporter.WriteData(sql); } else { var output = _output.Value(); if (WorkingDir.HasValue()) { output = Path.Combine(WorkingDir.Value(), output); } var directory = Path.GetDirectoryName(output); if (!string.IsNullOrEmpty(directory)) { Directory.CreateDirectory(directory); } Reporter.WriteVerbose(Resources.WritingFile(_output.Value())); File.WriteAllText(output, sql, Encoding.UTF8); } return(base.Execute()); }
public void RunTestCurrentVersionIdentical() { // tests with the current database without any changes. this should find nothing to import HouseholdPlan.FailOnIncorrectImport = true; using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { var path = Path.Combine(wd.WorkingDirectory, "profilegeneratorNothingImportTest.db3"); if (File.Exists(path)) { File.Delete(path); Thread.Sleep(3000); } File.Copy(DatabaseSetup.GetSourcepath(null), path); using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) { var mainSim = new Simulator(db.ConnectionString); var dbm = new DatabaseMerger(mainSim); dbm.RunFindItems(path, null); Logger.Info("Found " + dbm.ItemsToImport.Count + " items."); if (dbm.ItemsToImport.Count != 0) { throw new LPGException("This should not import anything, since its the same database."); } db.Cleanup(); } wd.CleanUp(); } }
public void OnlineDeviceActivationProcessorArrayTest() { var rnd = new Random(1); var nr = new NormalRandom(0, 1, rnd); using (var wd = new WorkingDir(Utili.GetCurrentMethodAndClass())) { wd.InputDataLogger.AddSaver(new ColumnEntryLogger(wd.SqlResultLoggingService)); wd.InputDataLogger.AddSaver(new ResultFileEntryLogger(wd.SqlResultLoggingService)); wd.InputDataLogger.AddSaver(new HouseholdKeyLogger(wd.SqlResultLoggingService)); var calcParameters = CalcParametersFactory.MakeGoodDefaults().EnableShowSettlingPeriod(); //calcParameters.Enable(CalcOption.ActionsLogfile); calcParameters.Enable(CalcOption.DeviceProfilesIndividualHouseholds); calcParameters.Enable(CalcOption.DetailedDatFiles); using (var fft = new FileFactoryAndTracker(wd.WorkingDirectory, "hh1", wd.InputDataLogger)) { //SqlResultLoggingService srls = new SqlResultLoggingService(Path.Combine(wd.WorkingDirectory, "results.sqlite")); var dsc = new DateStampCreator(calcParameters); using (IOnlineLoggingData old = new OnlineLoggingData(dsc, wd.InputDataLogger, calcParameters)) { var hhkey = new HouseholdKey("HH1"); fft.RegisterHousehold(Constants.GeneralHouseholdKey, "generalhousehold", HouseholdKeyType.General, "Description", null, null); fft.RegisterHousehold(hhkey, "hh1", HouseholdKeyType.Household, "Description", null, null); var odap = new OnlineDeviceActivationProcessor(old, calcParameters, fft); var deviceGuid = "devguid".ToStrGuid(); var locationGuid = "locationGuid".ToStrGuid(); var loadtypeGuid = "ltguid".ToStrGuid(); var cdd = new CalcDeviceDto("devicename", "devcatguid".ToStrGuid(), hhkey, OefcDeviceType.Device, "devcatname", "", deviceGuid, locationGuid, "loc"); var key = new OefcKey(cdd, loadtypeGuid); var clt = new CalcLoadType("lt1", "W", "kWh", 1, true, loadtypeGuid); odap.RegisterDevice(clt.ConvertToDto(), cdd); double[] stepValues = { 1.0, 0 }; var valueList = new List <double>(stepValues); var cp = new CalcProfile("myCalcProfile", Guid.NewGuid().ToStrGuid(), valueList, ProfileType.Absolute, "synthetic"); var ts1 = new TimeStep(1, 0, false); var cdl = new CalcDeviceLoad("", 1, clt, 0, 0); var sv = StepValues.MakeStepValues(cp, 10, RandomValueProfile.MakeStepValues(cp.StepValues.Count, nr, 0), cdl); odap.AddNewStateMachine(ts1, clt.ConvertToDto(), "name1", "p1", key, cdd, sv); double[] resultValues = { 0, 10.0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (var i = 0; i < 10; i++) { var ts = new TimeStep(i, 0, true); var filerows = odap.ProcessOneTimestep(ts); filerows.Count.Should().Be(1); filerows[0].EnergyEntries.Count.Should().Be(1); Logger.Info(filerows[0].EnergyEntries[0].ToString(CultureInfo.CurrentCulture)); resultValues[i].Should().Be(filerows[0].EnergyEntries[0]); foreach (var fileRow in filerows) { fileRow.Save(odap.BinaryOutStreams[fileRow.LoadType]); } } } } Logger.Info(wd.WorkingDirectory); wd.CleanUp(); } }
/// <summary> /// Applies a <see cref="WorkingDir"/> change to the <see cref="ProcessStartInfo"/>. /// </summary> /// <param name="binding">The <see cref="WorkingDir"/> to apply.</param> /// <param name="implementation">The implementation to be made available via the <see cref="WorkingDir"/> change.</param> /// <param name="startInfo">The process launch environment to apply the <see cref="WorkingDir"/> change to.</param> /// <exception cref="ImplementationNotFoundException">The <paramref name="implementation"/> is not cached yet.</exception> /// <exception cref="ExecutorException">The <paramref name="binding"/> has an invalid path or another working directory has already been set.</exception> /// <remarks>This method can only be called successfully once per <see cref="BuildStartInfoWithBindings()"/>.</remarks> private void ApplyWorkingDir(WorkingDir binding, ImplementationSelection implementation, ProcessStartInfo startInfo) { Log.Debug("Applying " + binding + " for " + implementation); string source = FileUtils.UnifySlashes(binding.Source) ?? ""; if (Path.IsPathRooted(source) || source.Contains(".." + Path.DirectorySeparatorChar)) throw new ExecutorException(Resources.WorkingDirInvalidPath); // Only allow working directory to be changed once if (!string.IsNullOrEmpty(startInfo.WorkingDirectory)) throw new ExecutorException(Resources.Working); startInfo.WorkingDirectory = Path.Combine(GetImplementationPath(implementation), source); }