Пример #1
0
        private void SaveSourceFile(SortableBindingList <DataItem> data)
        {
            if (!data.Any())
            {
                MessageBox.Show("Отсутствуют данные для сохранения.", "XDataConv", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return;
            }

            if (!String.IsNullOrEmpty(_openSourceFileDialog.FileName))
            {
                _saveSourceFileDialog.InitialDirectory = Path.GetDirectoryName(_openSourceFileDialog.FileName);
            }

            if (_saveSourceFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            try
            {
                var fileManager = new CsvFileManager(_logger);

                fileManager.WriteToFile(_saveSourceFileDialog.FileName, data);

                MessageBox.Show($"Данные сохранены в файл {_saveSourceFileDialog.FileName}.", "XDataConv",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                _logger.Error($"Error writing file {_saveSourceFileDialog.FileName}", ex);
                MessageBox.Show($"Ошибка сохранения файла {_saveSourceFileDialog.FileName}.{Environment.NewLine}{ex.Message}",
                                "XDataConv", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #2
0
        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);
        }
Пример #3
0
        public bool AddAssetTypes(string fullFileName, List <AssetTypeInfo> listToFill, bool tolerateFailure = false)
        {
            bool succeeded = true;

            List <AssetTypeInfo> newTypes = new List <AssetTypeInfo>();

            try
            {
                CsvFileManager.CsvDeserializeList(typeof(AssetTypeInfo), fullFileName, newTypes);
            }
            catch (Exception e)
            {
                succeeded = false;

                if (tolerateFailure)
                {
#if GLUE
                    // let's report it:
                    PluginManager.ReceiveError("Error loading CSV: " + fullFileName + "\n" + e.ToString());
#endif
                }
                else
                {
                    throw e;
                }
            }
            if (succeeded)
            {
#if GLUE
                PluginManager.ReceiveOutput("Loading content types from " + fullFileName + " and found " + newTypes.Count + " types");
#endif
                listToFill.AddRange(newTypes);
            }
            return(succeeded);
        }
 private void SetLocalizationDb(string filePath)
 {
     GlueCommands.Self.TryMultipleTimes(() =>
     {
         LocalizationDb = CsvFileManager.CsvDeserializeToRuntime(filePath);
     }, 5);
 }
Пример #5
0
        public static void LoadAvaliableProjectFromCsv()
        {
            var fileName = "Content/EmptyTemplates.csv";

            var absoluteFile = FileManager.RelativeDirectory + fileName;

            if (!File.Exists(absoluteFile))
            {
                MessageBox.Show($"{Resources.LoadProjectTip1}{absoluteFile}{Resources.LoadProjectTip2}");
            }
            else
            {
                EmptyProjects.Clear();
                CsvFileManager.CsvDeserializeList(typeof(PlatformProjectInfo), fileName, EmptyProjects);
            }


            fileName = "Content/StarterProjects.csv";

            absoluteFile = FileManager.RelativeDirectory + fileName;

            if (!File.Exists(absoluteFile))
            {
                MessageBox.Show($"{Resources.LoadProjectTip3}{absoluteFile}{Resources.LoadProjectTip4}");
            }
            else
            {
                StarterProjects.Clear();
                CsvFileManager.CsvDeserializeList(typeof(PlatformProjectInfo), fileName, StarterProjects);
            }
        }
Пример #6
0
        public static void LoadAvailableProjectsFromCsv()
        {
            string fileName = "Content/EmptyTemplates.csv";

            string absoluteFile = FileManager.RelativeDirectory + fileName;

            if (!File.Exists(absoluteFile))
            {
                MessageBox.Show("The New Project Creator is missing a critical file called EmptyTemplates.csv.  Full path is\n\n" +
                                absoluteFile + "\n\nThis file is needed to get the list of available projects that the New Project Creator can create");
            }
            else
            {
                CsvFileManager.CsvDeserializeList(typeof(PlatformProjectInfo), fileName, emptyProjects);
            }

            fileName = "Content/StarterProjects.csv";

            absoluteFile = FileManager.RelativeDirectory + fileName;

            if (!File.Exists(absoluteFile))
            {
                MessageBox.Show("The New Project Creator is missing a critical file called StarterProjects.csv.  Full path is\n\n" +
                                absoluteFile + "\n\nThis file is needed to get the list of available projects that the New Project Creator can create");
            }
            else
            {
                CsvFileManager.CsvDeserializeList(typeof(PlatformProjectInfo), fileName, starterProjects);
            }
        }
Пример #7
0
        public void LoadExternalBuildToolsFromCsv(string csvFileName)
        {
            List <BuildToolAssociation> externals = new List <BuildToolAssociation>();

            CsvFileManager.CsvDeserializeList(typeof(BuildToolAssociation), csvFileName, externals);

            BuildToolAssociations.AddExternalRange(externals);
        }
Пример #8
0
        public static BuildToolAssociationList FromFileCsv(string fileName)
        {
            BuildToolAssociationList toReturn = new BuildToolAssociationList();

            CsvFileManager.CsvDeserializeList(typeof(BuildToolAssociation), fileName, toReturn.BuildToolList);

            return(toReturn);
        }
Пример #9
0
        void CustomPreGlobalContentInitialize()
        {
            GlobalContent.SpreadsheetToReplace = new Dictionary <string, DataTypes.SpreadsheetToReplace>();

            CsvFileManager.CsvDeserializeDictionary <string, DataTypes.SpreadsheetToReplace>(
                "content/globalcontent/replacewiththis.csv",
                GlobalContent.SpreadsheetToReplace
                );
        }
Пример #10
0
 public static void LoadStaticContent(string contentManagerName)
 {
     if (string.IsNullOrEmpty(contentManagerName))
     {
         throw new ArgumentException("contentManagerName cannot be empty or null");
     }
     ContentManagerName = contentManagerName;
                 #if DEBUG
     if (contentManagerName == FlatRedBallServices.GlobalContentManager)
     {
         HasBeenLoadedWithGlobalContentManager = true;
     }
     else if (HasBeenLoadedWithGlobalContentManager)
     {
         throw new Exception("This type has been loaded with a Global content manager, then loaded with a non-global.  This can lead to a lot of bugs");
     }
                 #endif
     bool registerUnload = false;
     if (LoadedContentManagers.Contains(contentManagerName) == false)
     {
         LoadedContentManagers.Add(contentManagerName);
         lock (mLockObject)
         {
             if (!mRegisteredUnloads.Contains(ContentManagerName) && ContentManagerName != FlatRedBallServices.GlobalContentManager)
             {
                 FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("PlatformerCharacterBaseStaticUnload", UnloadStaticContent);
                 mRegisteredUnloads.Add(ContentManagerName);
             }
         }
         if (MovementValues == null)
         {
             {
                 // We put the { and } to limit the scope of oldDelimiter
                 char oldDelimiter = CsvFileManager.Delimiter;
                 CsvFileManager.Delimiter = ',';
                 Dictionary <string, MovementValues> temporaryCsvObject = new Dictionary <string, MovementValues>();
                 CsvFileManager.CsvDeserializeDictionary <string, MovementValues>("content/entities/platformercharacterbase/movementvalues.csv", temporaryCsvObject);
                 CsvFileManager.Delimiter = oldDelimiter;
                 MovementValues           = temporaryCsvObject;
             }
         }
     }
     if (registerUnload && ContentManagerName != FlatRedBallServices.GlobalContentManager)
     {
         lock (mLockObject)
         {
             if (!mRegisteredUnloads.Contains(ContentManagerName) && ContentManagerName != FlatRedBallServices.GlobalContentManager)
             {
                 FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("PlatformerCharacterBaseStaticUnload", UnloadStaticContent);
                 mRegisteredUnloads.Add(ContentManagerName);
             }
         }
     }
     CustomLoadStaticContent(contentManagerName);
 }
        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...
                }
            }
        }
Пример #12
0
        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");
                    }
                }
            }
        }
Пример #14
0
        public void Initialize(string contentTypesFileLocation, string startupPath)
        {
            mStartupPath           = startupPath;
            mCoreTypesFileLocation = contentTypesFileLocation;

            if (!File.Exists(contentTypesFileLocation))
            {
                throw new Exception("Could not find the file " + contentTypesFileLocation + " when trying to initialize the AvailableAssetTypes");
            }
            try
            {
                // We create a temporary
                // list to deserialize to
                // so that we can take the contents
                // and insert them at the front of the
                // list.  This makes the default implementations
                // show up first in the list so they can be found
                // first if searching by runtime type name.
                //List<AssetTypeInfo> tempList = new List<AssetTypeInfo>();
                // Update:  We now have a core asset types list
                CsvFileManager.CsvDeserializeList(typeof(AssetTypeInfo), contentTypesFileLocation, mCoreAssetTypes);
            }
            catch (Exception e)
            {
                string message = "Could not load the AssetTypes from\n" +
                                 contentTypesFileLocation + "\nThis probably means your ContentTypes.csv is corrupt (the file was found).  You should re-install Glue.";


                throw new Exception(message, e);
            }



            if (Directory.Exists(GlobalCustomContentTypesFolder))
            {
                List <string> extraCsvs = FileManager.GetAllFilesInDirectory(GlobalCustomContentTypesFolder, "csv", 0);

                foreach (string file in extraCsvs)
                {
                    try
                    {
                        AddAssetTypes(file);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Failed to add additional asset types from file " + file + "\n\nError info:\n" + e);
                    }
                }
            }
        }
Пример #15
0
        public static void Initialize()
        {
            string fileToLoad = FlatRedBall.IO.FileManager.MakeAbsolute(
                @"Content/BuiltInEvents.csv");

            try
            {
                CsvFileManager.CsvDeserializeDictionary <string, EventSave>(fileToLoad, mAllEvents);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show("Could not initialize event manager.  Check to make sure " +
                                                     "the following file exists and is not corrupt: " + fileToLoad);
            }
        }
Пример #16
0
        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);
        }
Пример #17
0
        public IActionResult Upload(IFormFile file)
        {
            if (file != null && file.Length > 0)
            {
                try
                {
                    var fileManager = new CsvFileManager();
                    return(View("Index", fileManager.ParseFileData(file)));
                }
                catch
                {
                    return(RedirectToAction("Error"));
                }
            }

            return(RedirectToAction("Index"));
        }
Пример #18
0
        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());
                }
            }
        }
Пример #19
0
        /// <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);
                }
            }
        }
Пример #20
0
        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;
            }
        }
Пример #21
0
        private static Dictionary <string, TopDownValues> GetCsvValues(EntitySave currentEntitySave)
        {
            var csvValues = new Dictionary <string, TopDownValues>();
            var filePath  = CsvGenerator.Self.CsvFileFor(currentEntitySave);

            bool doesFileExist = filePath.Exists();

            if (doesFileExist)
            {
                try
                {
                    CsvFileManager.CsvDeserializeDictionary <string, TopDownValues>(filePath.FullPath, csvValues);
                }
                catch (Exception e)
                {
                    PluginManager.ReceiveError("Error trying to load top down csv:\n" + e.ToString());
                }
            }

            return(csvValues);
        }
Пример #22
0
        private static Dictionary <string, PlatformerValues> GetCsvValues(EntitySave currentEntitySave)
        {
            Dictionary <string, PlatformerValues> csvValues = new Dictionary <string, PlatformerValues>();
            string absoluteFileName = CsvGenerator.Self.CsvFileFor(currentEntitySave);

            bool doesFileExist = System.IO.File.Exists(absoluteFileName);

            if (doesFileExist)
            {
                try
                {
                    CsvFileManager.CsvDeserializeDictionary <string, PlatformerValues>(absoluteFileName, csvValues);
                }
                catch (Exception e)
                {
                    PluginManager.ReceiveError("Error trying to load platformer csv:\n" + e.ToString());
                }
            }

            return(csvValues);
        }
Пример #23
0
        public static void AddDatabase(string fileName, char delimiter)
        {
            RuntimeCsvRepresentation rcr;

            char oldDelimiter = CsvFileManager.Delimiter;

            CsvFileManager.Delimiter = delimiter;
            Dictionary <string, string[]> entryDictionary = new Dictionary <string, string[]>();

            CsvFileManager.CsvDeserializeDictionary <string, string[]>(fileName, entryDictionary, out rcr);
            CsvFileManager.Delimiter = oldDelimiter;


            List <string> headerList = new List <string>();

            foreach (CsvHeader header in rcr.Headers)
            {
                headerList.Add(header.Name);
            }

            AddDatabase(entryDictionary, headerList);
        }
Пример #24
0
        private void OpenSourceFile()
        {
            if (_openSourceFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            try
            {
                var fileManager = new CsvFileManager(_logger);

                var items = fileManager.LoadDataItems(_openSourceFileDialog.FileName);

                gridSource.SuspendLayout();
                _matchingManager.SourceData.Clear();
                _matchingManager.SourceMatchedData.Clear();

                foreach (var item in items)
                {
                    _matchingManager.SourceData.Add(item);
                }

                fileNameStatusLabel.Text = Path.GetFileName(_openSourceFileDialog.FileName);

                MessageBox.Show($"Загрузка файла {_openSourceFileDialog.FileName} завершена.", "XDataConv",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                _logger.Error($"Error opening file {_openSourceFileDialog.FileName}", ex);
                MessageBox.Show($"Ошибка открытия файла {_openSourceFileDialog.FileName}.{Environment.NewLine}{ex.Message}",
                                "XDataConv", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                gridSource.ResumeLayout();
                UpdateSourceTabsCounters();
            }
        }
        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);
        }
Пример #26
0
        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);
            }
        }
Пример #27
0
        public override TImport Import(string filename, ContentImporterContext context)
        {
            BuildtimeCsvRepresentation buildtimeCsvRepresentation = CsvFileManager.CsvDeserializeToRuntime <BuildtimeCsvRepresentation>(filename);

            return(buildtimeCsvRepresentation);
        }
Пример #28
0
        void CustomInitialize()
        {
            if (StaticVariableEntity.FromGlobalCsv == null)
            {
                throw new Exception("Referencing a static entity's CSV variables is not working becaus the static variable is not properly set.  This variable is of a type defined in GlobalContent.");
            }

            // check if constants are made properly
            string in1 = SpreadsheetClass.FirstGuy;

            // to ignore warnings
            if (in1 != null)
            {
            }

            string in2 = SpreadsheetClass.GuyInFile2;

            if (in2 != null)
            {
            }

            if (GlobalCsvVariable.Name != "Name2")
            {
                throw new Exception("Variables using global CSVs in Screens are not getting their values set");
            }

            if (GlobalCsvVariableWithEvent.Name != "Name3")
            {
                throw new Exception("Variables with events using global CSVs in Screens are not getting their values set");
            }

            if (mHasCsvVariableEventBeenRaised == false)
            {
                throw new Exception("Events for CSV variables that are set in Glue are not raised");
            }

            if (new DataTypes.Spreadsheet().ListOfString == null)
            {
                throw new Exception("new instances of CSV objects should 'new' any lists");
            }

            // Check that the class with no associated CSV actually exists - we'll get a compile error if not:
            ClassWithNoAssociatedCsvs instance = new ClassWithNoAssociatedCsvs();

            var list = CsvFileManager.CsvDeserializeList(typeof(ManualCsvClass),
                                                         "Content/Screens/CsvScreen/CsvManuallyLoadedForPropertyTest.csv");

            ManualCsvClass entry = list[0] as ManualCsvClass;

            if (entry.StringList.Count == 0)
            {
                throw new NotImplementedException("CSVs that contain lists which are deserialized into properties are not set");
            }

            if (CsvUsingCustomDataFile["First"].StringListField.Count == 0)
            {
                throw new Exception("Primitive (string) lists as fields in custom data are not being deserialized properly");
            }

            if (CsvUsingCustomDataFile["First"].StringListProperty.Count == 0)
            {
                throw new Exception("Primitive (string) lists as properties in custom data are not being deserialized properly");
            }

            if (CsvUsingCustomDataFile["First"].ComplexCustomTypeListField.Count == 0)
            {
                throw new Exception("Complex type lists as fields in custom data are not being deserialized properly");
            }

            if (CsvUsingCustomDataFile["First"].ComplexCustomTypeListProperty.Count == 0)
            {
                throw new Exception("Complex type lists as properties in custom data are not being deserialized properly");
            }

            if (CsvUsingCustomDataFile["First"].ComplexCustomTypeListProperty[1].CustomEnumType != CustomDataTypes.CustomEnumType.Enum2)
            {
                throw new Exception("Enums in complex type property lists are not getting set.");
            }

            if (CsvUsingCustomDataFile["First"].StringProperty != "Test1")
            {
                throw new Exception("String properties are not being set correctly");
            }
        }
Пример #29
0
 public void SetUp()
 {
     _csvFileManager = new CsvFileManager();
 }
Пример #30
0
        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);
        }