public LogKeyValueItem ToFile() { var controllerName = FocusOnSegmentName.EnsureFirstCharacterToUpper() + "Controller"; var file = Util.GetCsFileNameForEndpoints(ApiProjectOptions.PathForEndpoints, controllerName); return(TextFileHelper.Save(file, ToCodeAsString())); }
public static void Main(string[] args) { try { InitializeInvariantCuluture(); var options = CommandLineOptions.CreateAndParse(args); if (LoadSettingFromArguments(options)) { var textFile = TextFileHelper.ReadAllTextFileWithDefaultEncoding(options.Path); var builder = TemplateBuilderParser.CreateBuilderText(textFile); Console.WriteLine(builder.CreateDataGenerator().GetData()); } else { // Display the default usage information Console.WriteLine(options.GetUsage()); } } catch (BuilderParserException bex) { Console.Error.WriteLine(ExceptionHelper.ToStringFull(bex)); } catch (Exception ex) { Console.Error.WriteLine("An error has occurred!"); Console.Error.WriteLine(ExceptionHelper.ToStringFull(ex)); } }
private static void _loadDataQuest(AbstractDb <int> db, string file) { var table = db.Table; TextFileHelper.LatestFile = file; try { foreach (string[] elements in TextFileHelper.GetElementsInt(db.ProjectDatabase.MetaGrf.GetData(file))) { int itemId = Int32.Parse(elements[0]); table.SetRaw(itemId, ClientQuestsAttributes.Name, elements[1]); table.SetRaw(itemId, ClientQuestsAttributes.SG, elements[2]); table.SetRaw(itemId, ClientQuestsAttributes.QUE, elements[3]); table.SetRaw(itemId, ClientQuestsAttributes.FullDesc, elements[4]); table.SetRaw(itemId, ClientQuestsAttributes.ShortDesc, elements[5]); } Debug.Ignore(() => DbDebugHelper.OnLoaded(db.DbSource, db.ProjectDatabase.MetaGrf.FindTkPath(file), db)); } catch (Exception err) { Debug.Ignore(() => DbDebugHelper.OnExceptionThrown(db.DbSource, file, db)); throw new Exception(TextFileHelper.GetLastError(), err); } }
public LogKeyValueItem ToFile() { var area = FocusOnSegmentName.EnsureFirstCharacterToUpper(); var file = Util.GetCsFileNameForHandler(DomainProjectOptions.PathForSrcHandlers !, area, HandlerTypeName); return(TextFileHelper.Save(file, ToCodeAsString(), false)); }
private static void ScaffoldBasicFileDomainRegistration(DomainProjectOptions domainProjectOptions) { // Create compilationUnit var compilationUnit = SyntaxFactory.CompilationUnit(); // Create a namespace var @namespace = SyntaxProjectFactory.CreateNamespace(domainProjectOptions); // Create class var classDeclaration = SyntaxClassDeclarationFactory.Create("DomainRegistration") .AddGeneratedCodeAttribute(domainProjectOptions.ToolName, domainProjectOptions.ToolVersion.ToString()); // Add class to namespace @namespace = @namespace.AddMembers(classDeclaration); // Add using statement to compilationUnit compilationUnit = compilationUnit.AddUsingStatements(new[] { "System.CodeDom.Compiler" }); // Add namespace to compilationUnit compilationUnit = compilationUnit.AddMembers(@namespace); var codeAsString = compilationUnit .NormalizeWhitespace() .ToFullString(); var file = new FileInfo(Path.Combine(domainProjectOptions.PathForSrcGenerate.FullName, "DomainRegistration.cs")); TextFileHelper.Save(file, codeAsString); }
public IEnumerable <string> Read() { string line; using (StreamReader reader = TextFileHelper.SetAndLoadReader(TempPath, EncodingService.DisplayEncoding)) { while (!reader.EndOfStream) { line = reader.ReadLine(); if (line == null) { continue; } if (!String.IsNullOrEmpty(line)) { yield return(line); } else { if (PrintEmptyLines) { if (NewLine == NewLineFormat.Unix) { Builder.AppendLineUnix(); } else { Builder.AppendLine(); } } } } } }
IEnumerator DrawGraph() { dataText = new TextFileHelper(); isPlotting = false; LoadData(); if (positions == null || positions.Length < 1) { yield break; } if (myLine == null) { myLine = new GameObject(); myLine.transform.position = gameObject.transform.position; myLine.AddComponent <LineRenderer>(); } LineRenderer lr = myLine.GetComponent <LineRenderer>(); lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply")); lr.SetColors(Color.blue, Color.red); lr.SetWidth(0.1f, 0.1f); for (int i = 1; i <= positions.Length; i++) { lr.positionCount = i; lr.SetPositions(positions); yield return(null); } }
private static void ScaffoldReadMe(this EntityFrameworkCoreProject project) { var lines = new List <string> { "CatFactory: Scaffolding Made Easy", string.Empty, "How to use this code on your ASP.NET Core Application:", string.Empty, "1. Install packages for EntityFrameworkCore and EntityFrameworkCore.SqlServer", string.Empty, "2. Register your DbContext and repositories in ConfigureServices method (Startup class):", string.Format(" services.AddDbContext<{0}>(options => options.UseSqlServer(Configuration[\"ConnectionString\"]));", project.Database.GetDbContextName()), " services.AddScoped<IDboRepository, DboRepository>();", string.Empty, "Happy scaffolding!", string.Empty, "You can check the guide for this package in:", "https://www.codeproject.com/Articles/1160615/Scaffolding-Entity-Framework-Core-with-CatFactory", string.Empty, "Also you can check source code on GitHub:", "https://github.com/hherzl/CatFactory.EntityFrameworkCore", string.Empty, "*** Soon CatFactory will scaffold code for Entity Framework Core 2.0 (December - 2017) ***", string.Empty, "CatFactory Development Team ==^^==" }; TextFileHelper.CreateFile(Path.Combine(project.OutputDirectory, "ReadMe.txt"), lines.ToStringBuilder().ToString()); }
public void SerializeExistingDatabaseTest() { // Arrange var databaseFactory = new SqlServerDatabaseFactory { ConnectionString = "server=(local);database=AdventureWorks2012;integrated security=yes;MultipleActiveResultSets=true;", ImportSettings = new DatabaseImportSettings { ImportMSDescription = true, Exclusions = new List <string> { "dbo.EventLog" } } }; // Act var database = databaseFactory.Import(); var serializer = new Serializer(); var output = serializer.Serialize(database); TextFileHelper.CreateFile("C:\\Temp\\CatFactory.SqlServer\\AdventureWorks2012.xml", output); // Assert }
public static void DbCommaNoCast <T>(DbDebugItem <T> debug, AttributeList list, int indexStart, int length) { var table = debug.AbsractDb.Table; foreach (string[] elements in TextFileHelper.GetElementsByCommas(File.ReadAllBytes(debug.FilePath))) { try { T itemId = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(elements[0]); int max = length; for (int index = 1; index < elements.Length && max > 0; index++) { DbAttribute property = list.Attributes[index + indexStart - 1]; int previousVal = 0; if (table.ContainsKey(itemId)) { previousVal = table.GetTuple(itemId).GetValue <int>(ServerSkillAttributes.Flag); } table.SetRaw(itemId, property, Int32.Parse(elements[index]) | previousVal); max--; } } catch (Exception err) { if (!debug.ReportException(err)) { return; } } } }
public static void DbCommaRange <T>(DbDebugItem <T> debug, AttributeList list, int indexStart, int length, bool addAutomatically = true) { var table = debug.AbsractDb.Table; foreach (string[] elements in TextFileHelper.GetElementsByCommas(File.ReadAllBytes(debug.FilePath))) { try { T itemId = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(elements[0]); if (!addAutomatically && !table.ContainsKey(itemId)) { Z.F(); continue; } int max = length; for (int index = 1; index < elements.Length && max > 0; index++) { DbAttribute property = list.Attributes[index + indexStart - 1]; table.SetRaw(itemId, property, elements[index]); max--; } } catch (Exception err) { if (!debug.ReportException(err)) { return; } } } }
private void ScaffoldBasicFileApiGenerated() { // Create compilationUnit var compilationUnit = SyntaxFactory.CompilationUnit(); // Create a namespace var @namespace = SyntaxProjectFactory.CreateNamespace(projectOptions); // Create class var classDeclaration = SyntaxClassDeclarationFactory.Create("ApiRegistration") .AddGeneratedCodeAttribute(projectOptions.ToolName, projectOptions.ToolVersion.ToString()); // Add class to namespace @namespace = @namespace.AddMembers(classDeclaration); // Add using statement to compilationUnit compilationUnit = compilationUnit.AddUsingStatements(new[] { "System.CodeDom.Compiler" }); // Add namespace to compilationUnit compilationUnit = compilationUnit.AddMembers(@namespace); var codeAsString = compilationUnit .NormalizeWhitespace() .ToFullString() .EnsureEnvironmentNewLines(); var file = new FileInfo(Path.Combine(projectOptions.PathForSrcGenerate.FullName, "ApiRegistration.cs")); var fileDisplayLocation = file.FullName.Replace(projectOptions.PathForSrcGenerate.FullName, "src: ", StringComparison.Ordinal); TextFileHelper.Save(logger, file, fileDisplayLocation, codeAsString); }
private static void ScaffoldReadMe(this DapperProject project) { var lines = new List <string> { "CatFactory: Scaffolding Made Easy", string.Empty, "How to use this code on your ASP.NET Core Application", string.Empty, "Register objects in Startup class, register your repositories in ConfigureServices method:", " services.AddScoped<IDboRepository, DboRepository>();", string.Empty, "Happy coding!", string.Empty, "You can check the guide for this package in:", "https://www.codeproject.com/Articles/1213355/Scaffolding-Dapper-with-CatFactory", string.Empty, "You can check source code on GitHub:", "https://github.com/hherzl/CatFactory.Dapper", string.Empty, "*** Special Thanks for Edson Ferreira to let me help for Dapper community ***", string.Empty, "CatFactory Development Team ==^^==" }; TextFileHelper.CreateFile(Path.Combine(project.OutputDirectory, "CatFactory.Dapper.ReadMe.txt"), lines.ToStringBuilder().ToString()); }
private void MoveToHistoryFile() { var fi = new FileInfo(_logFile); try { int maxSize = Settings.Instance.LogMaxSize; if (maxSize > 100) { maxSize = 100; } if (!fi.Exists || fi.Length < maxSize * 1024 * 1024) { return; } var fileName = Path.GetFileNameWithoutExtension(_logFile); var newFileName = string.Format("{0}-{1:yyyyMMddHHmmss}{2}", fileName, DateTime.Now, fi.Extension); var newLocation = Path.Combine(fi.DirectoryName, newFileName); File.Move(_logFile, newLocation); } catch { var logLine = string.Format("{0}: {1}: Cannot truncate log file.{2}", DateTime.Now.ToString(CultureInfo), ErrorLevel.Error, Environment.NewLine); TextFileHelper.WriteTextFile(logLine, _logFile, true, System.Text.Encoding.UTF8); } }
public void Log(ErrorLevel errorLevel, string logLine) { if (!string.IsNullOrEmpty(_logFile)) { bool isAllowedAddToLog = IsAllowedAddToLog(errorLevel); lock (SyncLock) { if (isAllowedAddToLog) { MoveToHistoryFile(); logLine = string.Format("{0}: {1}: {2}{3}", DateTime.Now.ToString(CultureInfo), errorLevel, logLine, Environment.NewLine); try { TextFileHelper.WriteTextFile(logLine, _logFile, true, System.Text.Encoding.UTF8); } catch (IOException) { Thread.Sleep(500); TextFileHelper.WriteTextFile(logLine, _logFile, true, System.Text.Encoding.UTF8); } catch { var fileName = HttpContext.Current.Server.MapPath(string.Format("/Files/System/Log/LiveIntegration/{0}.log", Guid.NewGuid())); TextFileHelper.WriteTextFile(logLine, fileName, false, System.Text.Encoding.UTF8); } } } if (errorLevel != ErrorLevel.DebugInfo && errorLevel != ErrorLevel.EmailSend) { SendLog(logLine, isAllowedAddToLog); } } }
public virtual void CreateFile(string subdirectory = "", string fileName = "") { Logger?.LogDebug("'{0}' has been invoked", nameof(CreateFile)); CreateOutputDirectory(); var filePath = string.IsNullOrEmpty(fileName) ? Path.Combine(OutputDirectory, subdirectory, FilePath) : Path.Combine(OutputDirectory, subdirectory, fileName); if (!ForceOverwrite && File.Exists(filePath)) { throw new CodeFactoryException(string.Format("The '{0}' file alread exists, if you want to overwrite set ForceOverwrite property as true", filePath)); } if (!string.IsNullOrEmpty(subdirectory)) { var subdirectoryPath = Path.Combine(OutputDirectory, subdirectory); if (!Directory.Exists(subdirectoryPath)) { Logger?.LogInformation("Creating '{0}' directory...", subdirectoryPath); Directory.CreateDirectory(subdirectoryPath); } } Logger?.LogInformation("Creating '{0}' file...", filePath); Translating(); OnTranslatedDefinition(new TranslatedDefinitionEventArgs(Logger)); TextFileHelper.CreateFile(filePath, Lines.ToStringBuilder().ToString()); }
/// <summary> /// Savaes all the Json Items in a dictionary to the File System /// </summary> /// <param name="jsonRootFolder"></param> /// <param name="itemType"></param> /// <param name="jsonItems"></param> /// <param name="eventLog"></param> /// <returns></returns> /// <remarks>Note: The JSON files end in the file extension .json</remarks> public bool SaveAllJsonFileItems(string jsonRootFolder, string itemTypeName, List <JsonItemFile> jsonItems, IEventLog eventLog) { if (jsonItems == null) { if (eventLog != null) { eventLog.LogEvent(0, "SaveAllJsonFileItems - " + itemTypeName + " - jsonItems is null"); } return(false); } bool returnValue = true; foreach (var item in jsonItems) { try { // Note: JSON Files need to end in .json string fullPath = FileHelper.EnsureTrailingDirectorySeparator(jsonRootFolder) + FileHelper.EnsureTrailingDirectorySeparator(itemTypeName) + (item.RelativePathBeneathTable.StartsWith("\\") ? item.RelativePathBeneathTable.Substring(1) : item.RelativePathBeneathTable) + (item.RelativePathBeneathTable.EndsWith(".json") ? "" : ".json"); TextFileHelper.WriteContents(fullPath, item.JsonContent, true); } catch (Exception exception) { if (eventLog != null) { eventLog.LogEvent(0, "Error SaveAllJsonFileItems: (" + item.JsonFileName + ") " + exception.ToString()); } returnValue = false; } } return(returnValue); }
/// <summary> /// Loads all the Json Items into a dictionary containing item name and JSON Content /// </summary> /// <param name="jsonRootFolder"></param> /// <param name="itemType"></param> /// <param name="eventLog"></param> /// <returns></returns> public List <JsonItemFile> LoadAllJsonFileItems(string jsonRootFolder, string itemTypeName, IEventLog eventLog) { List <JsonItemFile> jsonItems = new List <JsonItemFile>(); // Make sure the folder exists. If it does not then create it. string folderToLoadFrom = FileHelper.EnsureTrailingDirectorySeparator(jsonRootFolder) + itemTypeName; if (Directory.Exists(folderToLoadFrom) == false) { Directory.CreateDirectory(folderToLoadFrom); } // Use directory to get all files beneath a folder and subfolders FileInfo[] filePaths = FileHelper.GetFilteredFileListForDirectory(FileHelper.EnsureTrailingDirectorySeparator(jsonRootFolder) + itemTypeName, "*.json", true); foreach (var filePath in filePaths) { JsonItemFile jsonItemFile = new JsonItemFile() { UniqueFileName = FileHelper.GetFileNameFromFilePath(jsonRootFolder) + Guid.NewGuid().ToString().Replace("{", "").Replace("}", "").Replace("-", ""), JsonFileName = FileHelper.GetFileNameFromFilePath(filePath.FullName), RelativePathBeneathTable = FileHelper.GetFileNameFromFilePath(filePath.FullName), JsonContent = TextFileHelper.ReadContents(filePath.FullName.ToString()) }; jsonItems.Add(jsonItemFile); } return(jsonItems); }
private static void Main(string[] args) { const double maxAmplitude = 1000; double coefLong = 36; // I want my sine function to have period of 36 units double coefShort = 13; // I want my sine function to have period of 7 units double degreeCoefLong = 360 / coefLong; double degreeCoefShort = 360 / coefShort; double halfAmplitude = maxAmplitude / 2; double quarterAmplitude = maxAmplitude / 4; // The code provided will print ‘Hello World’ to the console. // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app. Console.WriteLine("MathTest Console"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); // Open csv file IoHelper.CreateDirectory(path); var fullFilePath = path + baseFileName + XDateTime.NowToFileSuffix() + fileExt; TextFileHelper.OpenTextFileForWrite(fullFilePath, false); // Write header TextFileHelper.AppendLine("Degrees," + "Sin," + "Sin+1," + "Amplified Sin + 1," + "Amplified SinShort + 1," + "Amplified SinLong + 1," + "Mixed," ); for (int degree = 0; degree < 720; degree++) { var sin = Math.Sin(degree * Math.PI / 180); var sinShort = Math.Sin(degreeCoefShort * degree * Math.PI / 180); var sinLong = Math.Sin(degreeCoefLong * degree * Math.PI / 180); //Console.WriteLine($"{degree}°: Sin={sin:f4}"); // write data to CSV file TextFileHelper.AppendLine($"{degree}," + $"{sin}," + $"{sin+1}," + $"{halfAmplitude * (sin + 1)}," + $"{halfAmplitude * (sinShort + 1)}," + $"{halfAmplitude * (sinLong + 1)}," + $"{quarterAmplitude * (sinShort + sinLong + 2)}," ); } TextFileHelper.CloseWriteTextFile(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Press any key ..."); //Console.ReadKey(); GlobalHelper.ProcessStart(fullFilePath); }
public LogKeyValueItem ToFile() { var area = FocusOnSegmentName.EnsureFirstCharacterToUpper(); var endpointName = ApiOperation.GetOperationName() + NameConstants.Endpoint; var file = Util.GetCsFileNameForContract(ApiProjectOptions.PathForEndpoints, area, endpointName); return(TextFileHelper.Save(file, ToCodeAsString())); }
public GameDataSet ReadData() { GameDataSet dataSet = new GameDataSet(); AddList(dataSet, GameDataType.USER_ITEM, TextFileHelper.Read(Const.Path.GameData.userItem)); AddList(dataSet, GameDataType.USER_PARAMETER, TextFileHelper.Read(Const.Path.GameData.userParameter)); return(dataSet); }
public void ToFile(FileInfo file) { if (file == null) { throw new ArgumentNullException(nameof(file)); } TextFileHelper.Save(file, ToCodeAsString()); }
public void StopRecording() { TextFileHelper help = new TextFileHelper(); help.WriteToFile(currentFileName, Data); print("Done"); mInputField.text = ""; isCalibrated = false; }
public void ToFile( FileInfo file) { ArgumentNullException.ThrowIfNull(file); var fileDisplayLocation = file.FullName.Replace(ApiProjectOptions.PathForSrcGenerate.FullName, "src: ", StringComparison.Ordinal); TextFileHelper.Save(logger, file.FullName, fileDisplayLocation, ToCodeAsString()); }
public LogKeyValueItem ToFile() { var area = FocusOnSegmentName.EnsureFirstCharacterToUpper(); var parameterName = ApiOperation.GetOperationName() + NameConstants.ContractParameters; var file = UseOwnFolder ? Util.GetCsFileNameForContract(ApiProjectOptions.PathForContracts, area, NameConstants.ContractParameters, parameterName) : Util.GetCsFileNameForContract(ApiProjectOptions.PathForContracts, area, parameterName); return(TextFileHelper.Save(file, ToCodeAsString())); }
public static LogKeyValueItem GenerateGeneratedTests( DomainProjectOptions domainProjectOptions, SyntaxGeneratorHandler sgHandler) { if (domainProjectOptions == null) { throw new ArgumentNullException(nameof(domainProjectOptions)); } if (sgHandler == null) { throw new ArgumentNullException(nameof(sgHandler)); } var area = sgHandler.FocusOnSegmentName.EnsureFirstCharacterToUpper(); var nsSrc = $"{domainProjectOptions.ProjectName}.{NameConstants.Handlers}.{area}"; var nsTest = $"{domainProjectOptions.ProjectName}.Tests.{NameConstants.Handlers}.{area}.Generated"; var srcSyntaxNodeRoot = ReadCsFile(domainProjectOptions, sgHandler.FocusOnSegmentName, sgHandler); var usedInterfacesInConstructor = GetUsedInterfacesInConstructor(srcSyntaxNodeRoot); var usingStatements = GetUsedUsingStatements( srcSyntaxNodeRoot, nsSrc, usedInterfacesInConstructor.Count > 0); var sb = new StringBuilder(); foreach (var item in usingStatements) { sb.AppendLine($"using {item};"); } sb.AppendLine(); GenerateCodeHelper.AppendNamespaceComment(sb, domainProjectOptions.ToolNameAndVersion); sb.AppendLine($"namespace {nsTest}"); sb.AppendLine("{"); GenerateCodeHelper.AppendGeneratedCodeAttribute(sb, domainProjectOptions.ToolName, domainProjectOptions.ToolVersion); sb.AppendLine(4, $"public class {sgHandler.HandlerTypeName}GeneratedTests"); sb.AppendLine(4, "{"); AppendInstantiateConstructor(sb, sgHandler, usedInterfacesInConstructor); if (sgHandler.HasParametersOrRequestBody) { sb.AppendLine(); AppendParameterArgumentNullCheck(sb, sgHandler, usedInterfacesInConstructor); } sb.AppendLine(4, "}"); sb.AppendLine("}"); var pathGenerated = Path.Combine(Path.Combine(domainProjectOptions.PathForTestHandlers !.FullName, area), "Generated"); var fileGenerated = new FileInfo(Path.Combine(pathGenerated, $"{sgHandler.HandlerTypeName}GeneratedTests.cs")); return(TextFileHelper.Save(fileGenerated, sb.ToString())); }
public IndexServiceTests() { var indexStoreMock = new Mock <IIndexStore>(); _examplePatientJson = TextFileHelper.ReadTextFileFromDisk( $".{Path.DirectorySeparatorChar}Examples{Path.DirectorySeparatorChar}patient-example.json"); _exampleAppointmentJson = TextFileHelper.ReadTextFileFromDisk( $".{Path.DirectorySeparatorChar}Examples{Path.DirectorySeparatorChar}appointment-example2doctors.json"); _carePlanWithContainedGoal = TextFileHelper.ReadTextFileFromDisk( $".{Path.DirectorySeparatorChar}Examples{Path.DirectorySeparatorChar}careplan-example-f201-renal.json"); _exampleObservationJson = TextFileHelper.ReadTextFileFromDisk( $".{Path.DirectorySeparatorChar}Examples{Path.DirectorySeparatorChar}observation-example-bloodpressure.json"); var spPatientName = new SearchParamDefinition { Resource = "Patient", Name = "name", Description = new Markdown(@"A portion of either family or given name of the patient"), Type = SearchParamType.String, Path = new[] { "Patient.name" }, Expression = "Patient.name" }; var spMiddleName = new SearchParamDefinition { Resource = "Patient", Name = "middlename", Type = SearchParamType.String, Path = new[] { "Patient.name.extension.where(url='http://hl7.no/fhir/StructureDefinition/no-basis-middlename')" }, Expression = "Patient.name.extension.where(url='http://hl7.no/fhir/StructureDefinition/no-basis-middlename')" }; var searchParameters = new List <SearchParamDefinition> { spPatientName, spMiddleName }; var resources = new Dictionary <Type, string> { { typeof(Patient), "Patient" }, { typeof(HumanName), "HumanName" } }; // For this test setup we want a limited available types and search parameters. IFhirModel limitedFhirModel = new FhirModel(resources, searchParameters); var limitedElementIndexer = new ElementIndexer(limitedFhirModel, new Mock <ILogger <ElementIndexer> >().Object); _limitedIndexService = new IndexService(limitedFhirModel, indexStoreMock.Object, limitedElementIndexer); // For this test setup we want all available types and search parameters. IFhirModel fullFhirModel = new FhirModel(); var fullElementIndexer = new ElementIndexer(fullFhirModel, new Mock <ILogger <ElementIndexer> >().Object); _fullIndexService = new IndexService(fullFhirModel, indexStoreMock.Object, fullElementIndexer); }
public void SerializeMockDatabaseTest() { // Arrange var database = Databases.Store; // Act var output = XmlSerializerHelper.Serialize(database); TextFileHelper.CreateFile("C:\\Temp\\CatFactory.SqlServer\\Store.xml", output); // Assert }
public LogKeyValueItem ToFile() { var area = FocusOnSegmentName.EnsureFirstCharacterToUpper(); var modelName = ApiSchemaKey.EnsureFirstCharacterToUpper(); var file = IsEnum ? Util.GetCsFileNameForContractEnumTypes(ApiProjectOptions.PathForContracts, modelName) : IsSharedContract ? Util.GetCsFileNameForContractShared(ApiProjectOptions.PathForContractsShared, modelName) : Util.GetCsFileNameForContract(ApiProjectOptions.PathForContracts, area, NameConstants.ContractModels, modelName); return(TextFileHelper.Save(file, ToCodeAsString())); }
public static void GenerateGeneratedTests( ILogger logger, DomainProjectOptions domainProjectOptions, SyntaxGeneratorHandler sgHandler) { ArgumentNullException.ThrowIfNull(logger); ArgumentNullException.ThrowIfNull(domainProjectOptions); ArgumentNullException.ThrowIfNull(sgHandler); var area = sgHandler.FocusOnSegmentName.EnsureFirstCharacterToUpper(); var nsSrc = $"{domainProjectOptions.ProjectName}.{NameConstants.Handlers}.{area}"; var nsTest = $"{domainProjectOptions.ProjectName}.Tests.{NameConstants.Handlers}.{area}.Generated"; var srcSyntaxNodeRoot = ReadCsFile(domainProjectOptions, sgHandler.FocusOnSegmentName, sgHandler); var usedInterfacesInConstructor = GetUsedInterfacesInConstructor(srcSyntaxNodeRoot); var usingStatements = GetUsedUsingStatements( srcSyntaxNodeRoot, nsSrc, usedInterfacesInConstructor.Count > 0); var sb = new StringBuilder(); foreach (var item in usingStatements) { sb.AppendLine($"using {item};"); } sb.AppendLine(); GenerateCodeHelper.AppendGeneratedCodeWarningComment(sb, domainProjectOptions.ToolNameAndVersion); sb.AppendLine($"namespace {nsTest}"); sb.AppendLine("{"); GenerateCodeHelper.AppendGeneratedCodeAttribute(sb, domainProjectOptions.ToolName, domainProjectOptions.ToolVersion); sb.AppendLine(4, $"public class {sgHandler.HandlerTypeName}GeneratedTests"); sb.AppendLine(4, "{"); AppendInstantiateConstructor(sb, sgHandler, usedInterfacesInConstructor); if (sgHandler.HasParametersOrRequestBody) { sb.AppendLine(); AppendParameterArgumentNullCheck(sb, sgHandler, usedInterfacesInConstructor); } sb.AppendLine(4, "}"); sb.AppendLine("}"); var pathGenerated = Path.Combine(Path.Combine(domainProjectOptions.PathForTestHandlers !.FullName, area), "Generated"); var fileGenerated = new FileInfo(Path.Combine(pathGenerated, $"{sgHandler.HandlerTypeName}GeneratedTests.cs")); var fileDisplayLocation = fileGenerated.FullName.Replace(domainProjectOptions.PathForTestGenerate !.FullName, "test: ", StringComparison.Ordinal); TextFileHelper.Save(logger, fileGenerated, fileDisplayLocation, sb.ToString()); }