/// <summary> <p>Creates skeletal source code (without correct data structure but no business /// logic) for all segments found in the normative database. </p> /// </summary> public static void MakeAll(string baseDirectory, string version) { // make base directory if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/"))) { baseDirectory += Path.DirectorySeparatorChar; } var targetDir = SourceGenerator.MakeDirectory( Path.Combine(baseDirectory, PackageManager.GetVersionPackagePath(version), "Segment")); // get list of data types var conn = NormativeDatabase.Instance.Connection; var sql = "SELECT seg_code, [section] from HL7Segments, HL7Versions where HL7Segments.version_id = HL7Versions.version_id AND hl7_version = '" + version + "'"; DbCommand temp_OleDbCommand = conn.CreateCommand(); temp_OleDbCommand.Connection = conn; temp_OleDbCommand.CommandText = sql; var rs = temp_OleDbCommand.ExecuteReader(); var segments = new List <string>(); while (rs.Read()) { var segName = Convert.ToString(rs[1 - 1]); if (char.IsLetter(segName[0])) { segments.Add(AltSegName(segName)); } } temp_OleDbCommand.Dispose(); NormativeDatabase.Instance.ReturnConnection(conn); if (segments.Count == 0) { Log.Warn($"No version {version} segments found in database {conn.Database}"); } for (var i = 0; i < segments.Count; i++) { try { var segment = segments[i]; var source = MakeSegment(segment, version); var targetFile = Path.Combine(targetDir.ToString(), $"{GetSpecialFilename(segment)}.cs"); FileAbstraction.WriteAllBytes(targetFile, Encoding.UTF8.GetBytes($"{source}}}")); } catch (Exception e) { Console.Error.WriteLine($"Error creating source code for all segments: {e.Message}"); SupportClass.WriteStackTrace(e, Console.Error); } } }
public FileAbstraction(FileAbstraction fSource) { filePath = fSource.filePath; fileName = fSource.fileName; cubeColor = fSource.cubeColor; size = fSource.size; }
public GameObject createCube(FileAbstraction fa) { GameObject cube; switch (fa.size) { case 1: cube = Instantiate(d_Cubes.transform.Find("SmallCube").gameObject); break; case 2: cube = Instantiate(d_Cubes.transform.Find("MediumCube").gameObject); break; case 3: cube = Instantiate(d_Cubes.transform.Find("BigCube").gameObject); break; default: cube = Instantiate(d_Cubes.transform.Find("TinyCube").gameObject); break; } fa.selfCube = cube; cube.GetComponent <FileAbstraction>().clone(fa); return(cube); }
public bool enumerate(List <FileAbstraction> files, List <FolderAbstraction> folders) { try { string[] sFolders = System.IO.Directory.GetDirectories(folderPath); string[] sFiles = System.IO.Directory.GetFiles(folderPath); foreach (string sFo in sFolders) { string[] pathParts = sFo.Split('\\'); string name = pathParts[pathParts.Length - 1]; FolderAbstraction newFoA = new FolderAbstraction(sFo, name); folders.Add(newFoA); } foreach (string sFi in sFiles) { string[] pathParts = sFi.Split('\\'); string name = pathParts[pathParts.Length - 1]; FileAbstraction newFiA = new FileAbstraction(sFi, name, Color.red, 3); files.Add(newFiA); } return(true); } catch (System.Exception e) { return(false); } }
public void clone(FileAbstraction fa) { this.fileName = fa.fileName; this.filePath = fa.filePath; this.cubeColor = fa.cubeColor; this.size = fa.size; selfCube = fa.selfCube; }
private static void BuildFile(string dataType, string targetDir, string version) { var fileName = Path.Combine(targetDir, $"{dataType}.cs"); FileAbstraction.WriteAllBytes( fileName, Encoding.UTF8.GetBytes(GetClassSource(dataType, version))); }
public GameObject removeFromPocket(GameObject player) { GameObject newCube = player.GetComponent <EnvironmentHandler>().createCube(fileAbs); newCube.GetComponent <FileAbstraction>().clone(fileAbs); fileAbs = null; fileCube = null; return(newCube); }
public void setFileText(FileAbstraction fa) { System.IO.FileInfo fI = new System.IO.FileInfo(fa.filePath); long fileLength = fI.Length; float fileMB = fileLength / (1024f * 1024f); string fileinfo = "File Details\r\n--------------\r\n\r\nFile Name:" + fI.Name + "\r\nFile Size:" + fileMB.ToString("#0.00 MB") + "\r\n\r\n" + "Preview:"; fileInfoText.text = fileinfo; fileInfoPanel.SetActive(true); }
public PocketAbstraction addToPocket(GameObject obj, GameObject player) { Debug.LogError(obj.name); Debug.LogError(obj.GetComponent <FileAbstraction>().fileName); fileAbs = new FileAbstraction(obj.GetComponent <FileAbstraction>()); Debug.LogError(fileAbs.fileName); fileCube = obj; player.GetComponent <EnvironmentHandler>().Cubes.Remove(obj); Destroy(obj); return(this); }
private static IEnumerable <TagFile> GetTagFiles(BeatmapSet beatmapSet, List <string> fileNames) { if (beatmapSet.songPath == null) { yield break; } foreach (string fileName in fileNames) { TagLib.File file = null; string errorTemplate = ""; List <object> arguments = new List <object> { fileName }; if (fileName.StartsWith("..")) { errorTemplate = "Leaves Folder"; } else { string[] files; try { files = Directory.GetFiles(beatmapSet.songPath, fileName + (fileName.Contains(".") ? "" : ".*")); } catch (DirectoryNotFoundException) { files = new string[] { }; } if (files.Length > 0) { try { file = new FileAbstraction(files[0]).GetTagFile(); } catch (Exception exception) { errorTemplate = "Exception"; arguments.Add(ExceptionTag(exception)); } } else { errorTemplate = "Missing"; } } yield return(new TagFile(file, errorTemplate, arguments.ToArray())); } }
public bool moveToFolder(FileAbstraction fiA, FolderAbstraction foA) { if (!System.IO.File.Exists(foA.folderPath + "\\" + fiA.fileName)) { System.IO.File.Move(fiA.filePath, foA.folderPath + "\\" + fiA.fileName); return(true); } else { return(false); } }
public bool isCubeLoaded(FileAbstraction fa) { bool found = false; foreach (GameObject c in Cubes) { FileAbstraction cFa = c.GetComponent <FileAbstraction>(); Debug.LogWarning(cFa.filePath + " checked against " + fa.filePath); if (cFa.fileName == fa.fileName) { found = true; } Debug.LogWarning(found); } return(found); }
/// <summary> Creates source code for a specific message structure and /// writes it under the specified directory. /// throws IllegalArgumentException if there is no message structure /// for this message in the normative database. /// </summary> public static void Make(string message, string baseDirectory, string chapter, string version) { try { var segments = GetSegments(message, version); // System.out.println("Making: " + message + " with " + segments.length + " segments (not writing message code - just groups)"); var group = GroupGenerator.GetGroupDef(segments, null, baseDirectory, version, message); var contents = group.Structures; // make base directory if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/"))) { baseDirectory += Path.DirectorySeparatorChar; } var targetDir = SourceGenerator.MakeDirectory( Path.Combine(baseDirectory, PackageManager.GetVersionPackagePath(version), "Message")); var targetFile = Path.Combine(targetDir.FullName, $"{message}.cs"); var stringBuilder = new StringBuilder(); stringBuilder.Append(MakePreamble(contents, message, chapter, version)); stringBuilder.Append(MakeConstructor(contents, message, version)); for (var i = 0; i < contents.Length; i++) { var groupAccessor = GroupGenerator.MakeAccessor(@group, i); stringBuilder.Append(groupAccessor); } // add implementation of model.control interface, if any stringBuilder.Append("}\r\n"); // End class stringBuilder.Append("}\r\n"); // End namespace FileAbstraction.WriteAllBytes(targetFile, Encoding.UTF8.GetBytes(stringBuilder.ToString())); } catch (Exception e) { Log.Error("Error while creating source code", e); Log.Warn("Warning: could not write source code for message structure " + message + " - " + e.GetType().FullName + ": " + e.Message); } }
public static void MakeAll(string baseDirectory, string version) { // make base directory if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/"))) { baseDirectory += Path.DirectorySeparatorChar; } var targetDir = SourceGenerator.MakeDirectory( Path.Combine(baseDirectory, PackageManager.GetVersionPackagePath(version), "EventMapping")); // get list of data types var conn = NormativeDatabase.Instance.Connection; var sql = "SELECT * from HL7EventMessageTypes inner join HL7Versions on HL7EventMessageTypes.version_id = HL7Versions.version_id where HL7Versions.hl7_version = '" + version + "'"; DbCommand temp_OleDbCommand = conn.CreateCommand(); temp_OleDbCommand.Connection = conn; temp_OleDbCommand.CommandText = sql; var rs = temp_OleDbCommand.ExecuteReader(); var targetFile = Path.Combine(targetDir.FullName, "EventMap.properties"); var stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"#event -> structure map for {version}"); if (version == "2.1" || version == "2.2") { stringBuilder.AppendLine("#note: no mappings are defined for 2.1 and 2.2"); } else { while (rs.Read()) { var messageType = $"{rs["message_typ_snd"]}_{rs["event_code"]}"; var structure = (string)rs["message_structure_snd"]; stringBuilder.AppendLine($"{messageType} {structure}"); } } FileAbstraction.WriteAllBytes(targetFile, Encoding.UTF8.GetBytes(stringBuilder.ToString())); }
public async Task BuildBaseDataTypes_GeneratesBaseDataTypes(string version) { // Arrange var results = new ConcurrentDictionary <string, string>(); FileAbstraction.UsingImplementation((filePath, bytes) => { results.TryAdd(filePath, Encoding.UTF8.GetString(bytes)); }); // Act BaseDataTypeGenerator.BuildBaseDataTypes("basepath", version); // Assert Assert.IsNotEmpty(results); await Verifier.Verify(results) .UseTextForParameters(version.Replace(".", string.Empty)); }
/// <summary> Creates source code for a Group and returns a GroupDef object that /// describes the Group's name, optionality, repeatability. The source /// code is written under the given directory. /// The structures list may contain [] and {} pairs representing /// nested groups and their optionality and repeatability. In these cases /// this method is called recursively. /// If the given structures list begins and ends with repetition and/or /// optionality markers the repetition and optionality of the returned /// GroupDef are set accordingly. /// <param name="structures">a list of the structures that comprise this group - must /// be at least 2 long /// </param> /// <param name="groupName">The group name</param> /// <param name="version">The version of message</param> /// <param name="baseDirectory">the directory to which files should be written /// </param> /// <param name="message">the message to which this group belongs /// </param> /// <throws> HL7Exception if the repetition and optionality markers are not </throws> /// </summary> public static GroupDef WriteGroup( IStructureDef[] structures, string groupName, string baseDirectory, string version, string message) { // make base directory if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/"))) { baseDirectory += Path.DirectorySeparatorChar; } var targetDir = SourceGenerator.MakeDirectory( Path.Combine(baseDirectory, PackageManager.GetVersionPackagePath(version), "Group")); // some group names are troublesome and have "/" which will cause problems when writing files groupName = groupName.Replace("/", "_"); var group = GetGroupDef(structures, groupName, baseDirectory, version, message); var targetFile = Path.Combine(targetDir.FullName, $"{@group.Name}.cs"); var stringBuilder = new StringBuilder(); stringBuilder.Append(MakePreamble(group, version)); stringBuilder.Append(MakeConstructor(group, version)); var shallow = group.Structures; for (var i = 0; i < shallow.Length; i++) { stringBuilder.Append(MakeAccessor(group, i)); } stringBuilder.Append("}\r\n"); // Closing class stringBuilder.Append("}\r\n"); // Closing namespace FileAbstraction.WriteAllBytes(targetFile, Encoding.UTF8.GetBytes(stringBuilder.ToString())); return(group); }
public async Task MakeAll_GeneratesAllDataTypes(string version) { // Arrange var results = new ConcurrentDictionary <string, string>(); FileAbstraction.UsingImplementation((filePath, bytes) => { results.TryAdd(filePath, Encoding.UTF8.GetString(bytes)); }); ConfigurationSettings.ConnectionString = this.Configuration.GetConnectionString("Hl7Database"); // Act DataTypeGenerator.MakeAll("basepath", version); // Assert Assert.IsNotEmpty(results); await Verifier.Verify(results) .UseTextForParameters(version.Replace(".", string.Empty)); }
public async Task Test_Generate_Versions(string version) { var results = new ConcurrentDictionary <string, string>(); FileAbstraction.UsingImplementation((filePath, bytes) => { results.TryAdd(filePath, Encoding.UTF8.GetString(bytes)); }); var builder = new ModelBuilder(); builder.BasePath = Path.Combine(Directory.GetCurrentDirectory(), "out"); builder.ConnectionString = this.Configuration.GetConnectionString("Hl7Database"); builder.MessageTypeToBuild = ModelBuilder.MessageType.All; // TODO: Should make these paths and connections strings configurable builder.Version = version; builder.Execute(); Assert.IsNotEmpty(results); await Verifier.Verify(results); }
private static string RenderResources(BeatmapSet aBeatmapSet) { string RenderFloat(List <string> aFiles, Func <string, string> aFunc) { string content = String.Join("<br>", aFiles.Select(aFile => { string path = aBeatmapSet.hitSoundFiles.FirstOrDefault(anOtherFile => anOtherFile.StartsWith(aFile + ".")); if (path == null) { return(null); } return(aFunc(path)); }).Where(aValue => aValue != null) ); if (content.Length == 0) { return(""); } return(Div("overview-float", content)); } Dictionary <string, int> hsUsedCount = new Dictionary <string, int>(); return (RenderContainer("Resources", RenderBeatmapContent(aBeatmapSet, "Used Hit Sound File(s)", aBeatmap => { List <string> usedHitSoundFiles = aBeatmap.hitObjects.SelectMany(anObject => anObject.GetUsedHitSoundFileNames()).ToList(); List <string> distinctSortedFiles = usedHitSoundFiles.Distinct().OrderByDescending(aFile => aFile).ToList(); return RenderFloat(distinctSortedFiles, aPath => Encode(aPath)) + RenderFloat(distinctSortedFiles, aPath => { int count = usedHitSoundFiles.Where(anOtherFile => aPath.StartsWith(anOtherFile + ".")).Count(); // Used for total hit sound usage overview if (hsUsedCount.ContainsKey(aPath)) { hsUsedCount[aPath] += count; } else { hsUsedCount[aPath] = count; } return $"× {count}"; }); }, false), RenderField("Total Used Hit Sound File(s)", (hsUsedCount.Any() ? Div("overview-float", String.Join("<br>", hsUsedCount.Select(aPair => aPair.Key) ) ) + Div("overview-float", String.Join("<br>", hsUsedCount.Select(aPair => Try(() => { string fullPath = Path.Combine(aBeatmapSet.songPath, aPair.Key); return Encode(RenderFileSize(fullPath)); }, noteIfError: "Could not get hit sound file size" ) ) ) ) + Div("overview-float", String.Join("<br>", hsUsedCount.Select(aPair => Try(() => { string fullPath = Path.Combine(aBeatmapSet.songPath, aPair.Key); double duration = AudioBASS.GetDuration(fullPath); if (duration < 0) { return "0 ms"; } return $"{duration:0.##} ms"; }, noteIfError: "Could not get hit sound duration" ) ) ) ) + Div("overview-float", String.Join("<br>", hsUsedCount.Select(aPair => Try(() => { string fullPath = Path.Combine(aBeatmapSet.songPath, aPair.Key); return Encode(AudioBASS.EnumToString(AudioBASS.GetFormat(fullPath))); }, noteIfError: "Could not get hit sound file path" ) ) ) ) + Div("overview-float", String.Join("<br>", hsUsedCount.Select(aPair => "× " + aPair.Value) ) ) : "") ), RenderBeatmapContent(aBeatmapSet, "Background File(s)", aBeatmap => { if (aBeatmap.backgrounds.Any()) { string fullPath = Path.Combine(aBeatmap.songPath, aBeatmap.backgrounds.First().path); if (!File.Exists(fullPath)) { return ""; } string error = null; TagLib.File tagFile = null; try { tagFile = new FileAbstraction(fullPath).GetTagFile(); } catch (Exception exception) { error = exception.Message; } return Div("overview-float", Try(() => Encode(aBeatmap.backgrounds.First().path), noteIfError: "Could not get background file path" ) ) + Div("overview-float", Try(() => Encode(RenderFileSize(fullPath)), noteIfError: "Could not get background file size" ) ) + ((error != null || tagFile == null) ? Div("overview-float", Try(() => Encode(tagFile.Properties.PhotoWidth + " x " + tagFile.Properties.PhotoHeight), noteIfError: "Could not get background resolution" ) ) : Div("overview-float", Encode($"(failed getting proprties; {error})") )); } else { return ""; } }, false), RenderBeatmapContent(aBeatmapSet, "Video File(s)", aBeatmap => { if (aBeatmap.videos.Any() || (aBeatmapSet.osb?.videos.Any() ?? false)) { string fullPath = Path.Combine(aBeatmap.songPath, aBeatmap.videos.First().path); if (!File.Exists(fullPath)) { return ""; } string error = null; TagLib.File tagFile = null; try { tagFile = new FileAbstraction(fullPath).GetTagFile(); } catch (Exception exception) { error = exception.Message; } return Div("overview-float", Try(() => Encode(aBeatmap.videos.First().path), noteIfError: "Could not get video file path" ) ) + Div("overview-float", Try(() => Encode(RenderFileSize(fullPath)), noteIfError: "Could not get video file size" ) ) + ((error != null || tagFile == null) ? Div("overview-float", Try(() => FormatTimestamps(Encode(Timestamp.Get(tagFile.Properties.Duration.TotalMilliseconds))), noteIfError: "Could not get video duration" ) ) + Div("overview-float", Try(() => Encode(tagFile.Properties.VideoWidth + " x " + tagFile.Properties.VideoHeight), noteIfError: "Could not get video resolution" ) ) : Div("overview-float", Encode($"(failed getting proprties; {error})") )); } else { return ""; } }, false), RenderBeatmapContent(aBeatmapSet, "Audio File(s)", aBeatmap => { string path = aBeatmap.GetAudioFilePath(); if (path == null) { return ""; } return Div("overview-float", Try(() => Encode(PathStatic.RelativePath(path, aBeatmap.songPath)), noteIfError: "Could not get audio file path" ) ) + Div("overview-float", Try(() => Encode(RenderFileSize(path)), noteIfError: "Could not get audio file size" ) ) + Div("overview-float", Try(() => FormatTimestamps(Encode(Timestamp.Get(AudioBASS.GetDuration(path)))), noteIfError: "Could not get audio duration" ) ) + Div("overview-float", Try(() => Encode(AudioBASS.EnumToString(AudioBASS.GetFormat(path))), noteIfError: "Could not get audio format" ) ); }, false), RenderBeatmapContent(aBeatmapSet, "Audio Bitrate", aBeatmap => { string path = aBeatmap.GetAudioFilePath(); if (path == null) { return "N/A"; } return Div("overview-float", $"average {Math.Round(AudioBASS.GetBitrate(path))} kbps" ); }, false), RenderField("Has .osb", Encode((aBeatmapSet.osb?.IsUsed() ?? false).ToString()) ), RenderBeatmapContent(aBeatmapSet, "Has .osu Specific Storyboard", aBeatmap => aBeatmap.HasDifficultySpecificStoryboard().ToString()), RenderBeatmapContent(aBeatmapSet, "Song Folder Size", aBeatmap => RenderDirectorySize(aBeatmap.songPath)) )); }
public PocketAbstraction(FileAbstraction fa) { fileAbs = fa; fileCube = fa.selfCube; }
/// <summary> /// Creates source code for a single data type in the HL7 normative database. /// </summary> /// <param name="targetDirectory">the directory into which the file will be written.</param> /// <param name="dataType">the name (e.g. ST, ID, etc.) of the data type to be created.</param> /// <param name="version">the HL7 version of the intended data type.</param> public static void Make(FileInfo targetDirectory, string dataType, string version) { Console.Out.WriteLine(" Writing " + Path.Combine(targetDirectory.FullName, dataType)); // make sure that targetDirectory is a directory ... if (!Directory.Exists(targetDirectory.FullName)) { throw new IOException("Can't create file in " + targetDirectory + " - it is not a directory."); } // get any components for this data type var conn = NormativeDatabase.Instance.Connection; var stmt = TransactionManager.Manager.CreateStatement(conn); var sql = new StringBuilder(); // this query is adapted from the XML SIG informative document sql.Append( "SELECT HL7DataStructures.data_structure, HL7DataStructureComponents.seq_no, HL7DataStructures.description, HL7DataStructureComponents.table_id, "); sql.Append( "HL7Components.description, HL7Components.table_id, HL7Components.data_type_code, HL7Components.data_structure "); sql.Append( "FROM HL7Versions LEFT JOIN (HL7DataStructures LEFT JOIN (HL7DataStructureComponents LEFT JOIN HL7Components "); sql.Append("ON HL7DataStructureComponents.comp_no = HL7Components.comp_no AND "); sql.Append("HL7DataStructureComponents.version_id = HL7Components.version_id) "); sql.Append("ON HL7DataStructures.version_id = HL7DataStructureComponents.version_id "); sql.Append("AND HL7DataStructures.data_structure = HL7DataStructureComponents.data_structure) "); sql.Append("ON HL7DataStructures.version_id = HL7Versions.version_id "); sql.Append("WHERE HL7DataStructures.data_structure = '"); sql.Append(dataType); sql.Append("' AND HL7Versions.hl7_version = '"); sql.Append(version); sql.Append("' ORDER BY HL7DataStructureComponents.seq_no"); DbCommand temp_OleDbCommand; temp_OleDbCommand = stmt; temp_OleDbCommand.CommandText = sql.ToString(); var rs = temp_OleDbCommand.ExecuteReader(); var dataTypes = new ArrayList(20); var descriptions = new ArrayList(20); var tables = new ArrayList(20); string description = null; while (rs.Read()) { if (description == null) { description = Convert.ToString(rs[3 - 1]); } var de = Convert.ToString(rs[5 - 1]); var dt = Convert.ToString(rs[8 - 1]); var ta = -1; if (!rs.IsDBNull(4 - 1)) { ta = rs.GetInt32(4 - 1); } // trim all CE_x to CE if (dt != null) { if (dt.StartsWith("CE", StringComparison.Ordinal)) { dt = "CE"; } } dataTypes.Add(dt); descriptions.Add(de); tables.Add(ta); } if (dataType.ToUpper().Equals("TS")) { dataTypes[0] = "TSComponentOne"; } rs.Close(); stmt.Dispose(); NormativeDatabase.Instance.ReturnConnection(conn); // if there is only one component make a Primitive, otherwise make a Composite string source = null; if (dataTypes.Count == 1) { if (dataType.Equals("FT") || dataType.Equals("ST") || dataType.Equals("TX") || dataType.Equals("NM") || dataType.Equals("SI") || dataType.Equals("TN") || dataType.Equals("GTS")) { source = MakePrimitive(dataType, description, version); } else { source = null; // note: IS, ID, DT, DTM, and TM are coded manually } } else if (dataTypes.Count > 1) { var numComponents = dataTypes.Count; // copy data into arrays ... var type = new string[numComponents]; var desc = new string[numComponents]; var table = new int[numComponents]; for (var i = 0; i < numComponents; i++) { type[i] = (string)dataTypes[i]; desc[i] = (string)descriptions[i]; table[i] = (int)tables[i]; } source = MakeComposite(dataType, description, type, desc, table, version); } else { // no components? // throw new DataTypeException("The data type " + dataType + " could not be found"); Console.WriteLine("No components for " + dataType); } // System.out.println(source); // write to file ... if (source != null) { var targetFile = Path.Combine(targetDirectory.ToString(), $"{dataType}.cs"); FileAbstraction.WriteAllBytes(targetFile, Encoding.UTF8.GetBytes($"{source}}}")); } else { Console.WriteLine("No Source for " + dataType); } }