internal static List <string> GetMemberNamesFrom(ReferencedFileSave rfs) { List <string> toReturn = new List <string>(); string fileName = rfs.Name; fileName = ProjectManager.MakeAbsolute(fileName); RuntimeCsvRepresentation rcr = CsvFileManager.CsvDeserializeToRuntime( fileName); for (int i = 0; i < rcr.Headers.Length; i++) { string memberName = rcr.Headers[i].Name; if (memberName.Trim().StartsWith("//")) { continue; } memberName = StringFunctions.RemoveWhitespace(memberName); if (memberName.Contains("(")) { memberName = memberName.Substring(0, memberName.IndexOfAny(new char[] { '(' })); } toReturn.Add(memberName); } return(toReturn); }
private void SetLocalizationDb(string filePath) { GlueCommands.Self.TryMultipleTimes(() => { LocalizationDb = CsvFileManager.CsvDeserializeToRuntime(filePath); }, 5); }
private static void AddAvailableValuesFromFileToList(string absoluteFile, List <string> stringsToReturn, bool shouldAppendFileName) { if (System.IO.File.Exists(absoluteFile)) { try { string toAppend = ""; if (shouldAppendFileName) { // Eventually we want to make this relative to the container, not just the folename toAppend = " in " + FileManager.RemovePath(absoluteFile); } RuntimeCsvRepresentation rcr = CsvFileManager.CsvDeserializeToRuntime(absoluteFile); rcr.RemoveHeaderWhitespaceAndDetermineIfRequired(); int requiredIndex = -1; for (int i = 0; i < rcr.Headers.Length; i++) { if (rcr.Headers[i].IsRequired) { requiredIndex = i; break; } } if (requiredIndex != -1) { foreach (string[] record in rcr.Records) { string possibleValue = record[requiredIndex]; if (!string.IsNullOrEmpty(possibleValue)) { if (shouldAppendFileName) { stringsToReturn.Add(possibleValue + toAppend); } else { stringsToReturn.Add(possibleValue); } } } } } catch (Exception e) { // do nothing for now... } } }
public static void GetDictionaryTypes(ReferencedFileSave referencedFileSave, out string keyType, out string valueType) { valueType = referencedFileSave.GetTypeForCsvFile(); // To know the value type, we gotta pop this bad boy open and find the first requied type keyType = null; char oldDelimiter = CsvFileManager.Delimiter; switch (referencedFileSave.CsvDelimiter) { case AvailableDelimiters.Comma: CsvFileManager.Delimiter = ','; break; case AvailableDelimiters.Tab: CsvFileManager.Delimiter = '\t'; break; case AvailableDelimiters.Pipe: CsvFileManager.Delimiter = '|'; break; } string absoluteFileName = ProjectManager.MakeAbsolute(referencedFileSave.Name); // If the file doesn't exist this will generate bad code. But this isn't // considered a silent failure because Glue will raise flags about missing // files earlier (like when it first starts up). We don't want to crash the // entire application in this case. if (System.IO.File.Exists(absoluteFileName)) { RuntimeCsvRepresentation rcr = CsvFileManager.CsvDeserializeToRuntime(absoluteFileName); // See if any of the headers are required foreach (CsvHeader header in rcr.Headers) { int indexOfOpeningParen = header.Name.IndexOf("("); if (indexOfOpeningParen != -1) { if (header.Name.IndexOf("required", indexOfOpeningParen) != -1) { keyType = CsvHeader.GetClassNameFromHeader(header.Name); break; } } } } CsvFileManager.Delimiter = oldDelimiter; }
public void TestSerialization() { RuntimeCsvRepresentation rcr = new RuntimeCsvRepresentation(); rcr.Headers = new CsvHeader[4]; rcr.Headers[0] = new CsvHeader("Header1"); rcr.Headers[1] = new CsvHeader("Header2"); rcr.Headers[2] = new CsvHeader("Newline Test1"); rcr.Headers[3] = new CsvHeader("Something"); rcr.Headers[3].IsRequired = true; rcr.Records = new List <string[]>(); rcr.Records.Add(new string[4]); rcr.Records[0][0] = "NoQuotes \"Quotes\" NoQuotes"; rcr.Records[0][1] = "Value = \"Something\""; rcr.Records[0][2] = string.Concat("Line 1", Environment.NewLine, "Line 2"); rcr.Records[0][3] = ""; string result = rcr.GenerateCsvString(); if (!result.Contains("NoQuotes \"\"Quotes\"\" NoQuotes")) { throw new Exception("rcr.GenerateCsvString is not properly adding double quotes for quotes"); } if (!result.Contains("\"Value = \"\"Something\"\"\"")) { throw new Exception("rcr.GenerateCsvString is not properly wrapping text in quotes when it should"); } if (!result.Contains(string.Concat("\"", rcr.Records[0][2], "\""))) { throw new Exception("rcr.GenerateCsvString is not properly wrapping newlined text in quotes"); } FileManager.SaveText(result, "SavedCsv.csv"); RuntimeCsvRepresentation loaded = CsvFileManager.CsvDeserializeToRuntime("SavedCsv.csv"); for (int i = 0; i < loaded.Records.Count; i++) { for (int j = 0; j < loaded.Records[i].Length; j++) { var loadedAtIandJ = loaded.Records[i][j]; var rcrAtIandJ = rcr.Records[i][j]; if (loadedAtIandJ != rcrAtIandJ) { throw new Exception("Loaded RCR doesn't equal what was saved"); } } } }
private static string GetClassInfo(string fileName, RuntimeCsvRepresentation rcr, CustomClassSave customClass, out List <TypedMemberBase> members, out Dictionary <string, string> untypedMembers) { bool usesCustomClass = customClass != null; List <RuntimeCsvRepresentation> rcrsForClass = new List <RuntimeCsvRepresentation>(); if (usesCustomClass) { foreach (string name in customClass.CsvFilesUsingThis) { ReferencedFileSave foundRfs = ObjectFinder.Self.GetReferencedFileSaveFromFile(name); if (foundRfs == null) { int m = 3; } else { fileName = foundRfs.Name; fileName = ProjectManager.MakeAbsolute(fileName); RuntimeCsvRepresentation runtimeToAdd = null; try { runtimeToAdd = CsvFileManager.CsvDeserializeToRuntime(fileName); } catch (Exception e) { MessageBox.Show("Error trying to parse CSV:\n" + e.ToString()); } if (runtimeToAdd != null) { rcrsForClass.Add(runtimeToAdd); } } } } else if (rcr != null) { rcrsForClass.Add(rcr); } GetClassInfoFromCsv(rcrsForClass, customClass, out members, out untypedMembers); return(fileName); }
internal void CreateAdditionalCsvFile(string name, GlobalOrProjectSpecific globalOrProjectSpecific) { // We're going to load the full // AvailableAssetTypes just to get // the headers. Then we'll // create a new RCR, copy over the headers // then save off the RCR using the argument // fileName. The new one will be empty except // for the headers. RuntimeCsvRepresentation rcr = CsvFileManager.CsvDeserializeToRuntime( mCoreTypesFileLocation); rcr.Records = new List <string[]>(); string desiredFullPath = null; if (globalOrProjectSpecific == GlobalOrProjectSpecific.Global) { desiredFullPath = GlobalCustomContentTypesFolder + name + ".csv"; } else // project-specific { desiredFullPath = ProjectSpecificContentTypesFolder + name + ".csv"; } if (File.Exists(desiredFullPath)) { MessageBox.Show("The CSV " + desiredFullPath + " already exists."); } else { try { CsvFileManager.Serialize(rcr, desiredFullPath); } catch (UnauthorizedAccessException) { MessageBox.Show("Unable to save the CSV file. You need to run Glue as an administrator"); } catch (Exception e) { MessageBox.Show("Unknown error attempting to create the CSV:\n\n" + e.ToString()); } } }
/// <summary> /// Verifies that the CSV is properly set up - this code doesn't generate anything because uniform type CSVs don't actually make /// a new class. They'll instead deserialize to something like string[] /// </summary> /// <param name="rfs">The file reference to the CSV.</param> /// <param name="fileName">The filename of the CSV</param> /// <param name="oldDelimiter">The old CSV delimiter - what to set the CSV delimiter back to after deserializing this CSV.</param> private static void CheckUniformTypeValidity(ReferencedFileSave rfs, string fileName, char oldDelimiter) { string duplicateHeader; RuntimeCsvRepresentation rcr = CsvFileManager.CsvDeserializeToRuntime( fileName); CsvFileManager.Delimiter = oldDelimiter; duplicateHeader = rcr.GetFirstDuplicateHeader; if (rfs.CreatesDictionary) { string duplicateRequiredField = rcr.FirstDuplicateRequiredField; if (!string.IsNullOrEmpty(duplicateRequiredField)) { System.Windows.Forms.MessageBox.Show("The CSV file " + fileName + "\n\nhas a duplicate required field:" + duplicateRequiredField); } } }
private static void DeserializeToRcr(AvailableDelimiters delimiter, string fileName, out RuntimeCsvRepresentation rcr, out bool succeeded) { rcr = null; succeeded = true; try { // Let's load this bad boy and get info about the class we need to make rcr = CsvFileManager.CsvDeserializeToRuntime(fileName); } catch (Exception e) { GlueGui.ShowMessageBox("Error parsing CSV\n\n" + fileName + "\nAttempted to use " + delimiter + " as the delimiter. If this is not the delimiter of the file, try changing the delimiter in Glue after the file is added"); FlatRedBall.Glue.Plugins.PluginManager.ReceiveError(e.ToString()); succeeded = false; } }
private string GetStringsGeneratedCodeFileContents(ReferencedFileSave referencedFileSave) { var glueState = Container.Get <IGlueState>(); var glueCommands = Container.Get <IGlueCommands>(); string toReturn = null; if (referencedFileSave != null) { var namespaceName = $"{glueState.ProjectNamespace}.DataTypes"; ICodeBlock document = new CodeDocument(0); ICodeBlock codeBlock = document.Namespace(namespaceName); codeBlock = codeBlock.Class("Strings"); string fileName = glueCommands.GetAbsoluteFileName(referencedFileSave); var doesFileExist = System.IO.File.Exists(fileName); if (System.IO.File.Exists(fileName)) { var runtime = CsvFileManager.CsvDeserializeToRuntime(fileName); foreach (var row in runtime.Records) { TryAddMemberForRow(codeBlock, row); } toReturn = document.ToString(); } } return(toReturn); }
public T LoadFromFile <T>(string assetName) { string extension = FileManager.GetExtension(assetName); if (FileManager.IsRelative(assetName)) { // get the absolute path using the current relative directory assetName = FileManager.RelativeDirectory + assetName; } string fullNameWithType = assetName + typeof(T).Name; // get the dictionary by the contentManagerName. If it doesn't exist, GetDisposableDictionaryByName // will create it. if (mDisposableDictionary.ContainsKey(fullNameWithType)) { #if PROFILE mHistory.Add(new ContentLoadHistory( TimeManager.CurrentTime, typeof(T).Name, fullNameWithType, ContentLoadDetail.Cached)); #endif return((T)mDisposableDictionary[fullNameWithType]); } else if (mNonDisposableDictionary.ContainsKey(fullNameWithType)) { return((T)mNonDisposableDictionary[fullNameWithType]); } else { #if PROFILE mHistory.Add(new ContentLoadHistory( TimeManager.CurrentTime, typeof(T).Name, fullNameWithType, ContentLoadDetail.HddFromFile)); #endif #if DEBUG // The ThrowExceptionIfFileDoesntExist // call used to be done before the checks // in the dictionaries. But whatever is held // in there may not really be a file so let's check // if the file exists after we check the dictionaries. FileManager.ThrowExceptionIfFileDoesntExist(assetName); #endif IDisposable loadedAsset = null; if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Microsoft.Xna.Framework.Graphics.Texture2D)) { // for now we'll create it here, eventually have it in a dictionary: loadedAsset = textureContentLoader.Load(assetName); } #region Scene else if (typeof(T) == typeof(FlatRedBall.Scene)) { FlatRedBall.Scene scene = FlatRedBall.Content.Scene.SceneSave.FromFile(assetName).ToScene(mName); object sceneAsObject = scene; lock (mNonDisposableDictionary) { if (!mNonDisposableDictionary.ContainsKey(fullNameWithType)) { mNonDisposableDictionary.Add(fullNameWithType, scene); } } return((T)sceneAsObject); } #endregion #region EmitterList else if (typeof(T) == typeof(EmitterList)) { EmitterList emitterList = EmitterSaveList.FromFile(assetName).ToEmitterList(mName); mNonDisposableDictionary.Add(fullNameWithType, emitterList); return((T)((object)emitterList)); } #endregion #region Image #if !MONOGAME else if (typeof(T) == typeof(Image)) { switch (extension.ToLowerInvariant()) { case "gif": Image image = Image.FromFile(assetName); loadedAsset = image; break; } } #endif #endregion #region BitmapList #if !XBOX360 && !SILVERLIGHT && !WINDOWS_PHONE && !MONOGAME else if (typeof(T) == typeof(BitmapList)) { loadedAsset = BitmapList.FromFile(assetName); } #endif #endregion #region NodeNetwork else if (typeof(T) == typeof(NodeNetwork)) { NodeNetwork nodeNetwork = NodeNetworkSave.FromFile(assetName).ToNodeNetwork(); mNonDisposableDictionary.Add(fullNameWithType, nodeNetwork); return((T)((object)nodeNetwork)); } #endregion #region ShapeCollection else if (typeof(T) == typeof(ShapeCollection)) { ShapeCollection shapeCollection = ShapeCollectionSave.FromFile(assetName).ToShapeCollection(); mNonDisposableDictionary.Add(fullNameWithType, shapeCollection); return((T)((object)shapeCollection)); } #endregion #region PositionedObjectList<Polygon> else if (typeof(T) == typeof(PositionedObjectList <FlatRedBall.Math.Geometry.Polygon>)) { PositionedObjectList <FlatRedBall.Math.Geometry.Polygon> polygons = PolygonSaveList.FromFile(assetName).ToPolygonList(); mNonDisposableDictionary.Add(fullNameWithType, polygons); return((T)((object)polygons)); } #endregion #region AnimationChainList else if (typeof(T) == typeof(AnimationChainList)) { if (assetName.EndsWith("gif")) { #if WINDOWS_8 || UWP || DESKTOP_GL throw new NotImplementedException(); #else AnimationChainList acl = new AnimationChainList(); acl.Add(FlatRedBall.Graphics.Animation.AnimationChain.FromGif(assetName, this.mName)); acl[0].ParentGifFileName = assetName; loadedAsset = acl; #endif } else { loadedAsset = AnimationChainListSave.FromFile(assetName).ToAnimationChainList(mName); } mNonDisposableDictionary.Add(fullNameWithType, loadedAsset); } #endregion else if (typeof(T) == typeof(Song)) { var loader = new SongLoader(); return((T)(object)loader.Load(assetName)); } #if MONOGAME else if (typeof(T) == typeof(SoundEffect)) { T soundEffect; if (assetName.StartsWith(@".\") || assetName.StartsWith(@"./")) { soundEffect = base.Load <T>(assetName.Substring(2)); } else { soundEffect = base.Load <T>(assetName); } return(soundEffect); } #endif #region RuntimeCsvRepresentation #if !SILVERLIGHT else if (typeof(T) == typeof(RuntimeCsvRepresentation)) { #if XBOX360 throw new NotImplementedException("Can't load CSV from file. Try instead to use the content pipeline."); #else return((T)((object)CsvFileManager.CsvDeserializeToRuntime(assetName))); #endif } #endif #endregion #region SplineList else if (typeof(T) == typeof(List <Spline>)) { List <Spline> splineList = SplineSaveList.FromFile(assetName).ToSplineList(); mNonDisposableDictionary.Add(fullNameWithType, splineList); object asObject = splineList; return((T)asObject); } else if (typeof(T) == typeof(SplineList)) { SplineList splineList = SplineSaveList.FromFile(assetName).ToSplineList(); mNonDisposableDictionary.Add(fullNameWithType, splineList); object asObject = splineList; return((T)asObject); } #endregion #region BitmapFont else if (typeof(T) == typeof(BitmapFont)) { // We used to assume the texture is named the same as the font file // But now FRB understands the .fnt file and gets the PNG from the font file //string pngFile = FileManager.RemoveExtension(assetName) + ".png"; string fntFile = FileManager.RemoveExtension(assetName) + ".fnt"; BitmapFont bitmapFont = new BitmapFont(fntFile, this.mName); object bitmapFontAsObject = bitmapFont; return((T)bitmapFontAsObject); } #endregion #region Text else if (typeof(T) == typeof(string)) { return((T)((object)FileManager.FromFileText(assetName))); } #endregion #region Catch mistakes #if DEBUG else if (typeof(T) == typeof(Spline)) { throw new Exception("Cannot load Splines. Try using the List<Spline> type instead."); } else if (typeof(T) == typeof(Emitter)) { throw new Exception("Cannot load Emitters. Try using the EmitterList type instead."); } #endif #endregion #region else, exception! else { throw new NotImplementedException("Cannot load content of type " + typeof(T).AssemblyQualifiedName + " from file. If you are loading " + "through the content pipeline be sure to remove the extension of the file " + "name."); } #endregion if (loadedAsset != null) { lock (mDisposableDictionary) { // Multiple threads could try to load this content simultaneously if (!mDisposableDictionary.ContainsKey(fullNameWithType)) { mDisposableDictionary.Add(fullNameWithType, loadedAsset); } } } return((T)loadedAsset); } }
public override TImport Import(string filename, ContentImporterContext context) { BuildtimeCsvRepresentation buildtimeCsvRepresentation = CsvFileManager.CsvDeserializeToRuntime <BuildtimeCsvRepresentation>(filename); return(buildtimeCsvRepresentation); }
private static bool CreateConstsForCsvEntries(ReferencedFileSave initialRfs, List <TypedMemberBase> members, Dictionary <string, string> untypedMembers, ICodeBlock codeBlock) { bool succeeded = true; bool addToOrderedLists = true; CustomClassSave customClass = GetCustomClassForCsv(initialRfs.Name); bool usesCustomClass = customClass != null; List <ReferencedFileSave> rfsesForClass = new List <ReferencedFileSave>(); if (usesCustomClass) { foreach (string name in customClass.CsvFilesUsingThis) { ReferencedFileSave foundRfs = ObjectFinder.Self.GetReferencedFileSaveFromFile(name); if (foundRfs != null) { rfsesForClass.Add(foundRfs); } } } else { rfsesForClass.Add(initialRfs); } foreach (ReferencedFileSave rfs in rfsesForClass) { if (rfs.CreatesDictionary) { string fileName = rfs.Name; fileName = ProjectManager.MakeAbsolute(fileName); var rcr = CsvFileManager.CsvDeserializeToRuntime(fileName); rcr.RemoveHeaderWhitespaceAndDetermineIfRequired(); int requiredIndex = rcr.GetRequiredIndex(); if (requiredIndex == -1) { succeeded = false; GlueGui.ShowMessageBox("The file " + rfs.Name + " is marked as a dictionary but has no column marked as required"); } else { string type = GetRequiredKeyType(rcr, members, untypedMembers, requiredIndex); FillCodeBlockWithKeys(codeBlock, type, rcr); // The first entry will be the "primary" one? if (addToOrderedLists) { FillOrderedListWithKeys(codeBlock, type, rcr); addToOrderedLists = false; } } } } return(succeeded); }
public static void GetCsvValues(EntitySave currentEntitySave, out Dictionary <string, TopDownValues> csvValues, out List <Type> additionalValueTypes, out CsvHeader[] headers) { csvValues = new Dictionary <string, TopDownValues>(); var filePath = CsvGenerator.Self.CsvFileFor(currentEntitySave); headers = null; bool doesFileExist = filePath.Exists(); additionalValueTypes = new List <Type>(); if (doesFileExist) { try { var rawValues = CsvFileManager.CsvDeserializeToRuntime(filePath.FullPath); List <TopDownValues> values = new List <TopDownValues>(); rawValues.CreateObjectList(typeof(TopDownValues), values); headers = rawValues.Headers; for (int columnIndex = 0; columnIndex < headers.Length; columnIndex++) { string headerName = headers[columnIndex].Name; bool shouldInclude = GetIfShouldIncludeInAdditionalValues(headerName); if (shouldInclude) { string typeAsString = GetTypeFromFullHeader(headers[columnIndex].OriginalText); var type = GetTypeFromTypeName(typeAsString); additionalValueTypes.Add(type); } } for (int i = 0; i < rawValues.Records.Count; i++) { for (int columnIndex = 0; columnIndex < headers.Length; columnIndex++) { string headerName = headers[columnIndex].Name; bool shouldInclude = GetIfShouldIncludeInAdditionalValues(headerName); if (shouldInclude) { var castedValue = CastValue( rawValues.Records[i][columnIndex], headers[columnIndex].OriginalText); values[i].AdditionalValues.Add(headerName, castedValue); } } csvValues.Add(values[i].Name, values[i]); } //CsvFileManager.CsvDeserializeDictionary<string, TopDownValues>(filePath.FullPath, csvValues); } catch (Exception e) { PluginManager.ReceiveError("Error trying to load top down csv:\n" + e.ToString()); } } }
private static bool CreateConstsForCsvEntries(ReferencedFileSave initialRfs, List <TypedMemberBase> members, Dictionary <string, string> untypedMembers, ICodeBlock codeBlock) { bool succeeded = true; bool addToOrderedLists = true; CustomClassSave customClass = GetCustomClassForCsv(initialRfs.Name); bool usesCustomClass = customClass != null; List <ReferencedFileSave> rfsesForClass = new List <ReferencedFileSave>(); if (usesCustomClass) { foreach (string name in customClass.CsvFilesUsingThis) { ReferencedFileSave foundRfs = ObjectFinder.Self.GetReferencedFileSaveFromFile(name); // A dupe was added one during a Glue crash, so let's protect against that: if (foundRfs != null && rfsesForClass.Contains(foundRfs) == false) { rfsesForClass.Add(foundRfs); } } } else { rfsesForClass.Add(initialRfs); } Dictionary <ReferencedFileSave, RuntimeCsvRepresentation> representations = new Dictionary <ReferencedFileSave, RuntimeCsvRepresentation>(); List <string> allKeys = new List <string>(); foreach (ReferencedFileSave rfs in rfsesForClass) { if (rfs.CreatesDictionary) { string fileName = rfs.Name; fileName = ProjectManager.MakeAbsolute(fileName); var rcr = CsvFileManager.CsvDeserializeToRuntime(fileName); representations.Add(rfs, rcr); rcr.RemoveHeaderWhitespaceAndDetermineIfRequired(); int requiredIndex = rcr.GetRequiredIndex(); if (requiredIndex == -1) { succeeded = false; GlueGui.ShowMessageBox("The file " + rfs.Name + " is marked as a dictionary but has no column marked as required"); } else { var requiredValues = RequiredColumnValues(rcr); allKeys.AddRange(requiredValues); } } } if (allKeys.Any()) { var distinct = allKeys.Distinct(); var firstRcr = representations.First().Value; int requiredIndex = firstRcr.GetRequiredIndex(); string type = GetRequiredKeyType(firstRcr, members, untypedMembers, requiredIndex); FillCodeBlockWithKeys(codeBlock, type, firstRcr, allKeys.Distinct().ToArray()); // the first rcr defines the ordered keys. Others won't add themselves to this list FillOrderedListWithKeys(codeBlock, type, firstRcr); } return(succeeded); }