Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
The CsvHeader class represents a header in a CSV file in the RuntimeCsvRepresentation class. The RuntimeCsvRepresentation class contains an array of CsvHeaders called Headers.
When a RuntimeCsvRepresentation is loaded, it will (by default) contain an array of CsvHeaders. Each CsvHeader represents the first item in a column in a CSV file.
The contents of the cell can be obtained through either the Name or OriginalText properties - they will be initially identical.
By default the IsRequired property will be set to false. Both the IsRequired and Name properties can be modified through the RuntimeCsvRepresentation's RemoveHeaderWhitespaceAndDetermineIfRequired method.
Did this article leave any questions unanswered? Post any question in our forums for a rapid response.
As explained in the main CsvFileManager page, you can easily create CSV files to define data classes such as:
But what if you wanted to also include a list of modifications on the car. In other words, something like this:
The CsvFileManager understands special syntax allowing for objects represented in a row to actually take up multiple rows, and to define lists.
The class shown above for Car is all that you need to do code-side to prepare your class to take a list of strings. To create a CSV that can support rows, you would want to create a spreadsheet that looks like this:
Make (required)
Model
Horsepower (int)
Modifications (List<string>)
Ford
Taurus
200
Paint protection
After-market stereo
Toyota
Corolla
140
Tinted windows
4-way rear speakers
Remote start system
If using the CSV plugin, the CSV would appear as shown in the following image:
In this case the Ford Taurus has 2 modifications ("Paint protection" and "After-market stereo"). The Toyota Corolla has 3 modifications ("Tinted Windows", "4-way rear speakers", and "Remote start system"). The spreadsheet displayed above has two things that are needed for lists. The first, which is quite obvious, is to declare the type for the appropriate header as a List<string> (or whatever other primitive type you are using). In this case, we're using List<string>, so the header is declared as follows:
This tells the CsvFileManager that the "Modifications" row should be treated as a List of strings, and that entries in the row may belong to the same object. However, this does raise one issue - how is the CsvFileManager to know when one list starts and when one ends. While it may seem obvious to you that the "After-market stereo" modification applies to the Taurus, it is entirely possible that the "After-market stereo" could also belong to a car with an empty Make, Model, and Horsepower. This is why the Make column has "(required)" after its name. This tells the CsvFileManager that this column has a required value, and that this column will define new instances. In other words, since there are two entries in the Make column, the CsvFileManager knows to make two instances when deserializing the CSV.
If you've used CSV files in Glue, then you probably know that Glue will automatically generate classes to match the given CSV format. Glue understands the List<TYPE> syntax described above. In other words, feel free to use this CSV syntax in your own files and Glue will automatically build classes that will match your CSVs.
CsvDeserializeList can be used to load a CSV into a list of objects, where the type of the object is passed in to the method call.
The CsvFileManager can be used to load a list of specific types (such as weapon data for an RPG) or a list of strings if there is no appropriate class to deserialize to. The following code can be used to deserialize a CSV to a list of strings:
The CsvFileManager supports CSV (or .txt files) cells with multiple rows. If you are using Text objects to display the contents of a CSV cell, the Text object will obey the new lines.
To enter multiple lines in Excel:
Click on a cell
Begin entering text
Hold down the ALT key and press ENTER to insert a new line
Continue typing
If you are used to programming new lines in strings in C# code, then you may be familiar with the '\n' character. However, FlatRedBall CSVs will not obey the newline character. The reason for this is because in code the '\n' is actually a single character, while writing \n in a CSV actually generates two characters: the '\' character followed by the 'n' character. To represent the \n character as a single character, you just insert an actual newline - this is what ALT+Enter in Excel accomplishes.
The RuntimeCsvRepresentation class is a general-purpose class which represents a CSV file. It can be easily created through the CsvFileManager.
RuntimeCsvRepresentations can be loaded as follows:
For more information see the CsvFileManager page.
Did this article leave any questions unanswered? Post any question in our forums for a rapid response.
The CsvFileManager supports cells that contain color values. Color values can be specified either by standard name or can be custom defined by components (as shown below).
The following shows how to define Colors in a CSV file:
CarName
PaintColor (Microsoft.Xna.Framework.Color)
Mustang
White
Elantra
Green
Corvette
A=255,R=0,G=27,B=128
Camry
A=255, R=255,G=0,B=100
The first two cars (Mustang and Elantra) are defined using standard color names. These names match the XNA Color names. The second two colors are custom colors created by setting the Red, Green, Blue, and Alpha components. The XNA Color struct uses 0 - 255 values for these components so keep that in mind when defining colors in CSV values.
The FromList method will create a RuntimeCsvRepresentation according to the object passed to it. This method can be used to generate a RuntimeCsvRepresentation which can be saved to disk to create a CSV.
The following code will create a RuntimeCsvRepresentation from a list of Vector3's:
The FromList method will ignore any fields or properties which have the XmlIgnore attribute. This allows objects which are built for XmlSerialization to serialize the same using RuntimeCsvRepresentations.
The BinarySerialize function is a function which can save a binary file representing an instance of an object. This function is similar to FlatRedBall.IO.FileManager.XmlSerialize, but the resulting file is a binary file rather than a text XML file.
Binary files have the following benefits:
Binary files cannot be opened and edited as easily as XML files. This makes binary serialization a good choice for files which you do not want users to be able to modify.
Binary files are often smaller on disk than XML files. For smaller files this doesn't matter much, but it can have a large impact on file size when dealing with larger files.
Binary files can be faster to load.
Binary files have the following downsides:
Binary files are more difficult to debug - you can't simply look at the file and identify issues.
Binary serialization is not supported on every platform.
Binary files created on one platform may not be usable on another platform.
Binary files do not use a standard structure, therefore any area where the binary file is needed requires a custom loader. Most non-C# technology includes XML parsing libraries.
Any type that is run through the BinarySerialize function must be marked as serializable. For example:
However, the
The CsvFileManager is a class which provides functionality for working with .csv files. The CSV file format is a simple file format that can be loaded and saved by spreadsheet programs. Glue provides a lot of functionality for working with CSV files. For information on working with CSV and Glue, see the using CSVs in Glue tutorial.
FlatRedBall engines are built to work well with the XML format. The FileManager provides methods for serializing to and deserializing from XML files, and most FlatRedBall file types are actually XML files for simplified readability, debugging, and to be cross-platform. However, despite its merits, the XML file type has a few disadvantages:
XML files tend to be bloated for the data contained. In many cases most of the data in the XML file comes from the tags rather than the data.
XML files can be difficult to maintain by hand. Despite being human readable, adding new entries without copying/pasting other entries is tedious and error prone.
XML files do not have a standard editor. While there are likely options for specifically editing XML files, most by-hand XML editing is performed in text editors. These editors do not provide any support for the file format.
The CSV format is a human readable format which while still being a text format can be very compact compared to XML files and can be edited in a number of common editors such as Google Docs, Open Office, and Microsoft Excel. These editors are very easy to use, support advanced editing such as the use of formulas, and the first two are completely free!
CSV stands for Comma Separated Values. CSV files can be displayed in spreadsheet programs, or be used as data files in FlatRedBall and Glue. CSV files can also be opened in text editors. Investigating the contents of a CSV file is often not necessary but can be helpful when debugging problems related to CSVs. A typical CSV file may look like this in a text editor:
This file would appear as follows in a spreadsheet program:
Header1
Header2
Header3
FirstValue
SecondValue
ThirdValue
The comma is the most common separator of cells (although other separators such as tabs and the | character are supported). Commas are also common in regular written English as well. The CSV format supports commas inside cells. Quotes are used to distinguish between a comma within a cell and a comma separating cells. For example, the following text shows the contents of a CSV file which includes commas.
This would result in the following CSV (notice the quotes do not appear)
Morning Greeting
Regular Greeting
Good morning
Hello, how are you?
Notice that single-quotes around a cell are not included in the contents of a CSV cell. Therefore, quotes may appear around cells even if they do not include a comma (this is the default behavior of OpenOffice):
The CsvfileManager provides methods for loading CSV files and creating lists of items. The code included in this article defines a simple struct which contains properties used to initialize newly-created Sprites. But before getting to the code, we will explain how to create CSV files in Google Docs. The following lists how to create a CSV file using Google Docs.
Go to the Google Docs website: http://docs.google.com/.
Log in to Google Docs. If you have never logged in before, but have a GMail address, use your GMail address and password to log in. Otherwise, you will need to create a new account.
At this point you should have a CSV file saved on your computer. The file should be similar to: Export.csv Either save this file in the the same folder as your project's EXE file, or add it to the solution and set the file to copy.
The following code uses the CSV file from the previous section to create a group of Sprites. Create the following struct:
Add the following to Initialize after initializing FlatRedBall
The following table shows the supported types.
Type
Member Example
CSV Entry Example
bool (A)
public bool IsHungry;
true
double
public double LengthOfTime;
3.244
Enum (B)
public BorderSides Sides;
Top
float
public float X;
1
int
public int CurrentLevel;
3
Matrix
public Matrix OrientationMatrix;
1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1
string
public string FirstName;
Martin
Texture2D (C)
public Texture2D TextureToUse;
redball.bmp
Vector2
public Vector2 GoalPosition;
23,18
Vector3
public Vector3 DirectionToFace;
11,0,-14
Vector4
public Vector4 FourDimentionalVector;
24,18,0,1
List<string> (or lists of any primitive)
public List<string> Names = new List<string>;
Color
public Color PaintColor;
Custom types (such as classes and structs defined in your game)
public SpecialAbility AbilityInstance;
(A) Some applications like OpenOffice Calc convert "true" to "TRUE". FlatRedBall will parse bool values regardless of capitalization. In other words, "TRUE" will be parsed correctly. (B) CSVs support enumerations. If using enumerations in Glue, you need to fully-qualify the enumeration in the type. For example, for a color operation, the header might read:
You do not need to qualify the value. For example, you can simply use "Modulate" instead of "ColorOperation.Modulate" in the cell for a value under a ColorOperation header. (C) FlatRedBall needs a content manager to load Texture2Ds. The CsvFileManager will automatically use FlatRedBallServices.GlobalContentManager if not content manager is explicitly set. You can set the content manager as follows:
[subpages depth="1"]
The FileManager provides methods and properties commonly used when working with files on the hard disk.
Functions which access files on the file system may fail if the operating system is case sensitive (as is the case for Android and iOS).
The iOS operating system is case sensitive; however the simulator is not case sensitive by default - this can make testing more difficult. For information on how to make the simulator run in case sensitive mode, see this link:
The GenerateCsvString method can be used to generate a string in CSV format. The resulting string can be saved to a file to create a CSV which can be opened in any application that supports CSVs.
The following code shows how to use the GenerateCsvString method:
The result string will contain:
Select New->Spreadsheet:
Enter the headers for the spreadsheet. These headers will be the fields of the class that we'll be creating later in this article:
Enter values for each of the structs. Each row represents an item in the list that will be created when the CSV file is deserialized. In this case I'll create four entries:
Export the files to a .csv file.
Depending on your browser the CSV file may open right in the browser. If that's the case, save the file out from the browser through the File menu:
See
See
see
The CloneObject method performs a deep clone of an object. This uses XML serialization so the object that is to be cloned must be XML serializable. This can be used to clone any "save" object, but should not be used on runtime objects such as Sprite.
Example of "save" objects include:
Engine objects with the name "Save" at the end like SpriteSave, SceneSave, and AnimationChainSave
Instances of objects that come from CSVs
Objects which do not contain references to other objects, like Vector3. Although these may not technically be considered "save" objects, they can be properly cloned using CloneObject.
The GetUserFolder method returns a string which can be used to save and load files in the user folder. To use this, the method must be called first. The return value for GetUserFolder depends on the platform that the call is made on; however, it can be used on any platform with most methods that access the file system through the FileManager.
For an example on how to use GetUserFolder, see the article.
GetAllFilesInDirectory is a method which can be used to get all files in a given directory and its sub-directories. The overloads for this method provide constraints such as the number of levels deep to search, and limitations on the file types.
The following call:
is equivalent to calling:
An empty string as the fileType will return all contained files.
The following code creates a to display all .jpg files which exist in the c:\Projects directory. If you do not have this directory on your computer, you will need to change the directory variable. Keep in mind that if the depth variable is large, or if the argument directory has a lot of files and sub-directories, this call can take a long time to execute. Add the following using statements:
Add the following to Initialize after initializing FlatRedBall:
The InitializeUserFolder is a method which prepares a user-specific storage area for saving and loading game content. The user folder can contain information such as game settings (audio volume), progress (how far the player has made it through the game), and debug information (such as call stacks if the application crashes).
The user folder has both read and write access on every device, and using the user folder is the preferred way to save data when using FlatRedBall as it enables cross-platform IO support.
The InitializeUserFolder method must be called before any other methods which use the user folder. This method initializes the user folder, gets its location, and saves a text file.
The SaveEmbeddedResource method can be used to save a file which has been compiled as an EmeddedResource to disk. This method is useful for PC tools, especially Gum plugins.
The following will save the redball.bmp image to the given target directory assuming it exists in the current assembly:
The FileManager's RelativeDirectory is a directory that is used as the directory that file loading is performed relative to.
For example, let's say the FileManager's RelativeDirectory is
In this case any file-related FRB call will result in FlatRedBall looking in this directory for files. Therefore, we could create a Sprite as follows:
This would result in the engine looking for the following file:
Generated Glue code assumes that the RelativeDirectory is the directory of the .exe file. Therefore, if your code ever changes the RelativeDirectory and you are using Glue, you should change the RelativeDirectory back to its old value. See below on an example of how to preserve RelativeDirectory.
Virtually any FlatRedBall call which access information off of the disk will use FileManager.RelativeDirectory. For example the following calls will use the RelativeDirectory when relative paths:
Any FlatRedBall Save Class's FromFile and Save methods
The RelativeDirectory defaults to the directory of your executable if your application is running on the PC (as opposed to Silverlight or the Xbox 360). This file is determined when execution first starts. In other words, running your application in a different folder or on a different machine will result in a different RelativeDirectory at startup. This keeps file loading portable.
In some cases you may want to change the FileManager's RelativeDirectory property; however, there are some restrictions when you do this:
The RelativeDirectory must always be an absolute path.
The RelativeDirectory should preferably be relative to the location of your executable.
These two requirements might seem contradictory - how can you guarantee that RelativeDirectory stays relative to your .exe, but at the same time achieve that by setting an absolute path?
The answer is to use the old RelativeDirectory value when setting a new RelativeDirectory.
Let's say that you want to set the RelativeDirectory to your "Content" folder, as you plan on doing all loading from that folder. To do this, you'll simply want to append "Content\" to your RelativeDirectory as follows:
This means that your program will use the "Content" folder for all of its loading logic; however, your file access code will remain relative.
You should NOT do this:
If you do this then your game will break if you decide to move it to another computer, if you send it to a friend, or if you switch to a different platform like the Xbox 360 or Silverlight.
For example, let's say that MySaveClass has a list of Sprites that it will load. The code to load this might be as follows:
The FileManager supports the use of the "../" string which indicates to "move up one directory". You can change the RelativeDirectory by appending "../" at the end as follows:
You can also use the backslash:
This sill result in the RelativeDirectory moving up one directory. Keep in mind that RelativeDorectory must always be absolute, so the following is not valid:
Also, it is not recommended that you use "../" to navigate up any higher than the starting RelativeDirectory as this will keep your application from being portable.
The "./" string represents "this directory". This string should not be used when dealing with the RelativeDirectory property because it is a string that is reserved by FlatRedBall to indicate an absolute path on non-PC platforms.
The "./" can be used to indicate an absolute path if you would like to prevent the FileManager from making the file absolute. In other words, this operation would use the RelativeDirectory:
while on non-PC platforms, this is absolute:
We strongly recommend not using absolute paths like this because they keep your application from being portable to the PC versions of FlatRedBall.
The SaveText function is a function that can be used to easily save the contents of a string to a .txt file. This function will overwrite previously-created .txt files if an existing file name is passed, so be careful calling this method.
The following code creates a string, saves it to a .txt file, then opens that file.
Many file formats assume that contained references are relative to the file itself. For example, consider a file which references "redball.bmp". By default if you try to load "redball.bmp" your program will attempt to look for a redball.bmp file in the same folder as the .exe. If you are writing code which will load objects relative to another file, you may want to temporarily set the RelativeDirectory value, then change it back after you're finished.
The UserApplicationDataForThisApplication property gives you an absolute path that you can use in your application to save information for the given application. Examples of information you may want to save are:
Settings for a tool (such as window size)
Debug information
Save data (such as the user's profile)
If your game/application uses an installer to install itself to Program Files or "Program Files (x86)" (on Windows 7) then you will not be able to save files in the same location as the .exe. This is a security feature of later versions of Windows.
The UserApplicationDataForThisApplication gives you a folder which can be saved to without security issues.
The following saves a file called "myFile.txt" which contains the text "Hello World" to the application data folder.
Introduction The Standardize method is used to convert file names to a standard format. By default Standardize performs the following modifications to a file name:
It is converted to lower case
Backslashes are converted to forward slashes
Relative files are made absolute
Standardize is useful because it allows string comparison between files.
The XmlSerialize and XmlDeserialize methods are methods which can be used to easily convert a class to an XML file, or an XML file back into an instance of a given type. XmlSerialize and XmlDeserialize are often used to save and load game data, such as player progress. Internally the FileManager uses the System.Xml.Serialization.XmlSerializer for serialization and deserialization. This means that any XML file created by the FileManager can be deserialized using the XmlSerializer if FlatRedBall is not available. Similarly, FlatRedBall can deserialize files created in other applications which use the XmlSerializer to save XML files. XmlSerialize uses the FileManager's RelativeDirectory when given relative paths to serialize.
As mentioned above, game data can be saved to disk as XML files. For example, the following class could be used to save information about the user's progress:
A screen can be modified to save and load the project:
The XmlSerialize internally uses XmlSerializer and XmlWriter classes. This means that all XML attributes (such as XmlIgnore) will apply normally.
If the path of the file to save does not exist, then the XmlSerialize method will attempt to create the appropriate directory before saving the XML file.
The FileManager uses the internally. Therefore if the type cannot be serialized by the internal XmlSerializer then the FileManager.XmlSerialize will throw an exception. For information on this error, see this page.
Creating Save Classes - Discusses the "Save" class coding pattern commonly used to save game data.
The XmlDeserialize function is a function that can load a XML file and create a runtime object out of it. You must have an object that matches a given XML's format to properly deserialize an XML into an instance you can use at runtime. The XmlDeserialize method uses System.Xml.Serialization.XmlSerializer internally, but this provides a convenient way to deserialize objects with one call. XmlDeserialize uses the FileManager's RelativeDirectory when given relative paths to deserialize.
For an example on how XmlDeserialize works, see XmlSerialize: http://flatredball.com/documentation/api/flatredball/flatredball-io/flatredball-io-filemanager/flatredball-io-filemanager-xmlserialize/