Inheritance: MonoBehaviour
Example #1
0
        IEnumerable<CompilerError> CreateAndValidateBase(JsonFile json, string baseFolder, string baseType)
        {
            List<CompilerError> errors = new List<CompilerError>();

            internalName = Building.Info.internalName + ":" + Path.GetFileNameWithoutExtension(json.Path);

            AddIfNotNull(SetJsonValue(json, "displayName", ref displayName, internalName), errors);

            hasCode = json.Json.Has("code");
            AddIfNotNull(SetJsonValue(json, "code", ref code, baseType + "." + Defs.ParseName(internalName)), errors);
            if (code != null)
            {
                if (code.Contains(':'))
                    code = code.Replace(':', '.');
                else
                    code = Building.Info.internalName + "." + code;
            }

            string r = Path.ChangeExtension(json.Path.Substring(Building.OriginPath.Length + 1).Replace('\\', '/'), null);
            AddIfNotNull(SetJsonValue(json, "texture", ref texture, r), errors);
            if (!Building.files.ContainsKey(texture + ".png"))
                errors.Add(new CompilerError(Building)
                {
                    Cause = new FileNotFoundException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "Could not find item texture '" + texture + ".png'."
                });

            return errors;
        }
Example #2
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            internalName = Building.Info.internalName + ":" + Path.GetFileNameWithoutExtension(json.Path);

            AddIfNotNull(SetJsonValue(json, "displayName", ref displayName, internalName), errors);

            string r = Path.ChangeExtension(json.Path.Substring(Building.OriginPath.Length + 1).Replace('\\', '/'), null);
            AddIfNotNull(SetJsonValue(json, "texture", ref texture, r), errors);
            if (!Building.files.ContainsKey(texture + ".png"))
                errors.Add(new CompilerError(Building)
                {
                    Cause = new FileNotFoundException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "Could not find item texture '" + texture + ".png'."
                });

            AddIfNotNull(SetJsonValue(json, "house", ref house, true), errors);
            AddIfNotNull(SetJsonValue(json, "dungeon", ref dungeon, false), errors);
            AddIfNotNull(SetJsonValue(json, "light", ref light, false), errors);

            AddIfNotNull(SetJsonValue(json, "blend", ref blend, 0), errors);
            AddIfNotNull(SetJsonValue(json, "sound", ref sound, 0), errors);
            AddIfNotNull(SetJsonValue(json, "soundGroup", ref soundGroup, 0), errors);
            AddIfNotNull(SetJsonValue(json, "dust", ref dust, 0), errors);

            AddIfNotNull(SetJsonValue(json, "drop", ref drop, drop), errors);

            return errors;
        }
Example #3
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            JsonData optionsArr = null;

            if (json.Json.IsArray)
                optionsArr = json.Json;
            else if (!json.Json.Has("options"))
                errors.Add(new CompilerError(Building)
                {
                    Cause = new KeyNotFoundException(),
                    IsWarning = false,
                    FilePath = json.Path,
                    Message = "Key 'options' not found."
                });
            else
                optionsArr = json.Json["options"];

            if (optionsArr == null)
                return errors;

            for (int i = 0; i < optionsArr.Count; i++)
            {
                var result = Option.NewOption(Compiler, new JsonFile(json.Path, optionsArr[i])); // actual stuff happens here

                options.Add(result.Item1);
                errors.AddRange(result.Item2);
            }

            return errors;
        }
Example #4
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            errors.AddRange(CreateAndValidateBase(json, "Projectile", "Projectiles"));

            AddIfNotNull(SetJsonValue(json, "friendly"       , ref friendly       , true ), errors);
            AddIfNotNull(SetJsonValue(json, "hurtsTiles"     , ref hurtsTiles     , false), errors);
            AddIfNotNull(SetJsonValue(json, "ignoreWater"    , ref ignoreWater    , false), errors);
            AddIfNotNull(SetJsonValue(json, "magic"          , ref magic          , false), errors);
            AddIfNotNull(SetJsonValue(json, "manualDirection", ref manualDirection, false), errors);
            AddIfNotNull(SetJsonValue(json, "melee"          , ref melee          , false), errors);
            AddIfNotNull(SetJsonValue(json, "minion"         , ref minion         , false), errors);
            AddIfNotNull(SetJsonValue(json, "ownerHitCheck"  , ref ownerHitCheck  , false), errors);
            AddIfNotNull(SetJsonValue(json, "pet"            , ref pet            , false), errors);
            AddIfNotNull(SetJsonValue(json, "ranged"         , ref ownerHitCheck  , false), errors);
            AddIfNotNull(SetJsonValue(json, "tileCollide"    , ref tileCollide    , true ), errors);

            AddIfNotNull(SetJsonValue(json, "aiStyle"      , ref aiStyle      , 0   ), errors);
            AddIfNotNull(SetJsonValue(json, "alpha"        , ref alpha        , 0   ), errors);
            AddIfNotNull(SetJsonValue(json, "damage"       , ref damage       , 0   ), errors);
            AddIfNotNull(SetJsonValue(json, "frameCount"   , ref frameCount   , 1   ), errors);
            AddIfNotNull(SetJsonValue(json, "maxUpdates"   , ref maxUpdates   , 1   ), errors);
            AddIfNotNull(SetJsonValue(json, "npcCritChance", ref npcCritChance, 4   ), errors);
            AddIfNotNull(SetJsonValue(json, "penetrate"    , ref penetrate    , 1   ), errors);
            AddIfNotNull(SetJsonValue(json, "timeLeft"     , ref timeLeft     , 3600), errors);

            AddIfNotNull(SetJsonValue(json, "knockback"  , ref knockback  , 1f), errors);
            AddIfNotNull(SetJsonValue(json, "npcCritMult", ref npcCritMult, 2f), errors);

            AddIfNotNull(SetJsonValue(json, "killedSound", ref killedSound, String.Empty), errors);

			AddIfNotNull(SetJsonValue(json, "bobber", ref bobber, false), errors);

			if (bobber)
			{
				AddIfNotNull(SetJsonValue(json, "bobberLineColor", ref bobberLineColor, true, new[] { 255, 255, 255 }), errors);
				if (bobberLineColor.Length < 3 || bobberLineColor.Length > 4)
					errors.Add(new CompilerError(Building)
					{
						Cause = new IndexOutOfRangeException(),
						FilePath = json.Path,
						IsWarning = false,
						Message = "'bobberLineColor' should be an array of ints with length 3 or 4."
					});

				AddIfNotNull(SetJsonValue(json, "bobberLineEnd", ref bobberLineEnd, true, new[] { 0f, 0f }), errors);
				if (bobberLineEnd.Length != 2)
					errors.Add(new CompilerError(Building)
					{
						Cause = new IndexOutOfRangeException(),
						FilePath = json.Path,
						IsWarning = false,
						Message = "'bobberLineEnd' should be an array of floats with length 2."
					});
			}

            return errors;
        }
Example #5
0
        /// <summary>
        /// Create &amp; validate subclass-only fields.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        protected override IEnumerable<CompilerError> CreateAndValidateOverride(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            AddIfNotNull(SetJsonValue(json, "length",  ref length                    ), errors);
            AddIfNotNull(SetJsonValue(json, "default", ref defaultValue, String.Empty), errors);

            return errors;
        }
Example #6
0
        /// <summary>
        /// Create &amp; validate subclass-only fields.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        protected override IEnumerable<CompilerError> CreateAndValidateOverride(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            AddIfNotNull(SetJsonValue(json, "minimum",      ref minimum        ), errors);
            AddIfNotNull(SetJsonValue(json, "maximum",      ref maximum        ), errors);
            AddIfNotNull(SetJsonValue(json, "defaultValue", ref defaultValue, 0), errors);

            return errors;
        }
    void InitializeDatabase()
    {
        NameGenerator nameGen = GetComponent <NameGenerator> ();

        if (!JsonFile.FilesExistIn("NameGenerator"))
        {
            LoggerTool.Post("Initializing Database");
            nameGen.BuildDatabase();
        }
    }
Example #8
0
        protected void WriteEnvelope <T>(ApprovalEnvelope <T> envelope)
        {
            var fPath = GetFilePath(envelope.RequestKey);

            if (File.Exists(fPath))
            {
                File.Delete(fPath);
            }
            JsonFile.Write(envelope, fPath, true);
        }
Example #9
0
        private void LoadJsonFile()
        {
            string path = string.Format(@"{0}\\{1}", System.Environment.CurrentDirectory, _jsonFilePath);

            if (File.Exists(path))
            {
                string jsonText = File.ReadAllText(path);
                _novoCyteConfig.Config = JsonFile.GetNovoCyteConfigFromJsonText(jsonText).Config;
            }
        }
Example #10
0
        SetUpNetworkServiceMock(string absoluteUrl, JsonFile jsonFile)
        {
            var json = JsonHelper.GetJson(jsonFile);
            var httpResponseMessage = new HttpResponseMessage
            {
                Content = new StringContent(json)
            };

            return(SetUpNetworkServiceMock(absoluteUrl, httpResponseMessage));
        }
Example #11
0
        public void Clone()
        {
            var dummy = new DummySerializable {
                Value = 1
            };
            var clone = JsonFile.Clone(dummy);

            Assert.AreNotSame(dummy, clone);
            Assert.AreEqual(dummy.Value, clone.Value);
        }
Example #12
0
        public void Create(Tweet tweet)
        {
            Dictionary <int, Tweet> dicT = new JsonFile <Tweet>().ReadJsonFile(_filePath);

            tweet.Id          = dicT.Count + 1;
            tweet.DateOfTweet = DateTime.Now;
            tweet.Likes       = new List <int>();
            dicT.Add(dicT.Count + 1, tweet);
            new JsonFile <Tweet>().WriteJsonFile(dicT, _filePath);
        }
Example #13
0
        private static JsonFile GetDatabaseFile()
        {
            string binDir   = GetBinDir();
            string fileName = "database.json";
            string filePath = Path.Combine(binDir, fileName);

            JsonFile config = new JsonFile(filePath);

            return(config);
        }
Example #14
0
        private async Task LoadAsync()
        {
            Folder = ApplicationData.Current.LocalCacheFolder;

            try
            {
                JsonFile = await Folder.GetFileAsync(JsonFileName);
            }
            catch (FileNotFoundException)
            {
                try
                {
                    var oldPinnedItemsFile = await Folder.GetFileAsync("PinnedItems.txt");

                    var oldPinnedItems = await FileIO.ReadLinesAsync(oldPinnedItemsFile);

                    await oldPinnedItemsFile.DeleteAsync();

                    foreach (var line in oldPinnedItems)
                    {
                        if (!Model.Items.Contains(line))
                        {
                            Model.Items.Add(line);
                        }
                    }
                }
                catch (FileNotFoundException)
                {
                    Model.AddDefaultItems();
                }

                JsonFile = await Folder.CreateFileAsync(JsonFileName, CreationCollisionOption.ReplaceExisting);

                await FileIO.WriteTextAsync(JsonFile, JsonConvert.SerializeObject(Model, Formatting.Indented));
            }

            try
            {
                Model = JsonConvert.DeserializeObject <SidebarPinnedModel>(await FileIO.ReadTextAsync(JsonFile));
                if (Model == null)
                {
                    Model = new SidebarPinnedModel();
                    throw new Exception($"{JsonFileName} is empty, regenerating...");
                }
            }
            catch (Exception)
            {
                await JsonFile.DeleteAsync();

                Model.AddDefaultItems();
                Model.Save();
            }

            Model.AddAllItemsToSidebar();
        }
        // GET: JsonFile
        public ActionResult Index()
        {
            var filePath = Directory.GetCurrentDirectory() + @"\UploadedFiles\test.json";
            var jFile    = new JsonFile
            {
                Path = filePath,
                Body = _reader.ReadFile(filePath)
            };

            return(View(jFile));
        }
Example #16
0
        private void tsbSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.DefaultExt = "stamp";
            dlg.Filter     = fileDialogFilter;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                JsonFile.Save(dlg.FileName, _stamp);
            }
        }
Example #17
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();
            
            AddIfNotNull(SetJsonValue(json, "name",        ref name                 ), errors);
            AddIfNotNull(SetJsonValue(json, "items",       ref items                ), errors);
            AddIfNotNull(SetJsonValue(json, "displayName", ref displayName, name    ), errors);
            AddIfNotNull(SetJsonValue(json, "displayItem", ref displayItem, items[0]), errors);

            return errors;
        }
Example #18
0
        /// <summary>
        /// Parse the bucket info to <see cref="ConfigBucket"/>.
        /// </summary>
        /// <param name="json">The json content.</param>
        /// <returns>Returns the <see cref="ConfigBucket"/> instance.</returns>
        protected virtual ConfigBucket ParseBucketInformation(string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                return(null);
            }

            var configBucket = JsonFile.Parse <ConfigBucket>(json);

            return(configBucket);
        }
Example #19
0
 void ShowLanguageEditor()
 {
     if (languageDic.dic.Count == 0)
     {
         languageDic.dic.Add(new LanguageInfo(string.Empty, string.Empty));
     }
     EditorGUILayout.BeginHorizontal();
     if (GUILayout.Button("<<<", GUILayout.Width(50)))
     {
         showMainMenu = true;
         JsonFile.SaveToFile(languageDic, dataPath, languageType.ToString());
     }
     if (GUILayout.Button("Save", GUILayout.Width(200)))
     {
         JsonFile.SaveToFile(languageDic, dataPath, languageType.ToString());
     }
     EditorGUILayout.LabelField(languageType.ToString(), EditorStyles.boldLabel);
     EditorGUILayout.EndHorizontal();
     EditorGUILayout.BeginHorizontal();
     EditorGUILayout.LabelField("key                                                value", EditorStyles.boldLabel);
     EditorGUILayout.EndHorizontal();
     for (int i = 0; i < languageDic.dic.Count; i++)
     {
         EditorGUILayout.BeginHorizontal();
         if (languageType == SystemLanguage.English)
         {
             languageDic.dic[i].Key = EditorGUILayout.TextField(languageDic.dic[i].Key, GUILayout.Width(200));
         }
         else
         {
             languageDic.dic[i].Key = EditorGUILayout.TextField(engnishDic.dic[i].Key, GUILayout.Width(200));
         }
         languageDic.dic[i].Value = EditorGUILayout.TextField(languageDic.dic[i].Value, GUILayout.Width(500));
         if (i == languageDic.dic.Count - 1)
         {
             if (GUILayout.Button("+", GUILayout.Width(20)))
             {
                 if (languageType == SystemLanguage.English)
                 {
                     languageDic.dic.Add(new LanguageInfo(string.Empty, string.Empty));
                 }
                 else if (languageDic.dic.Count + 1 <= engnishDic.dic.Count)
                 {
                     languageDic.dic.Add(new LanguageInfo(string.Empty, string.Empty));
                 }
             }
         }
         if (GUILayout.Button("-", GUILayout.Width(20)))
         {
             languageDic.dic.RemoveAt(i);
         }
         EditorGUILayout.EndHorizontal();
     }
 }
Example #20
0
        private void tsbOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = fileDialogFilter;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                _stamp = JsonFile.Load <Stamp>(dlg.FileName);
                InitDataBinding(_stamp);
            }
        }
Example #21
0
        public bool TryGetEnvelope <T>(out ApprovalEnvelope <T> requestEnvelope, string filePath)
        {
            requestEnvelope = null;
            if (!File.Exists(filePath))
            {
                return(false);
            }

            requestEnvelope = JsonFile.Read <ApprovalEnvelope <T> >(filePath);
            return(true);
        }
Example #22
0
        static void Main(string[] arguments)
        {
            var configuration = JsonFile.Read <Configuration>();

            using (var server = new Server(configuration.Port, configuration.ConnectionString))
            {
                server.Run();
                var resetEvent = new ManualResetEvent(false);
                resetEvent.WaitOne();
            }
        }
 public static ChangeSenderSettings LoadOrDefault()
 {
     try
     {
         return(JsonFile.Read <ChangeSenderSettings>(SETTINGS_CFG));
     }
     catch (FileNotFoundException)
     {
         return(WriteDefaultSettingsFile());
     }
 }
Example #24
0
        public void TestParseObject()
        {
            var filePath = Helper.Fixtrue("Json/read-1.json");
            var content  = File.ReadAllText(filePath);

            var foo = JsonFile.Parse <Read1>(content);

            Assert.AreEqual("menghanyu", foo.Name);
            Assert.AreEqual("miaomiao", foo.Aliases[0]);
            Assert.AreEqual("candycat", foo.Aliases[1]);
        }
Example #25
0
        public void TestNyokaRemote()
        {
            const string nyokaremoteFileName = ".nyokaremotetest.json";
            var          dir = Directory.GetCurrentDirectory();
            var          nrFileNameWithPath = $"{dir}{Os.DIRSEPERATOR}{nyokaremoteFileName}";
            var          info = new NyokaRemoteInfo
            {
                RepositoryServer = null,
                ZementisServer   = null,
                ZementisModeler  = "http://localhost:7007"
            };

            #region write nyokaremote file in current directory
            var nrFile = new JsonFile <NyokaRemoteInfo>(nyokaremoteFileName, readOnly: false);
            nrFile["default"] = info;
            nrFile.Save(force: true);
            #endregion
            Assert.True(File.Exists(nrFileNameWithPath));
            #region read nyokaremote file in current directory
            var nrFile0 = new JsonFile <NyokaRemoteInfo>(nyokaremoteFileName, readOnly: false);
            var info0   = nrFile0["default"];
            #endregion
            Assert.Equal(info.ZementisModeler, info0.ZementisModeler);
            #region set new values and save it back to the file
            info0.ZementisServer = "https://zserver.zmod.org";
            nrFile0["default"]   = info0;
            nrFile0.Save(force: true);   // should not be neccessary to force
            #endregion
            Assert.True(File.Exists(nrFileNameWithPath));
            #region readonly test for nyokaremote file
            var nrFileReadOnly = new JsonFile <NyokaRemoteInfo>(nyokaremoteFileName);    // readonly is default
            var info2          = nrFileReadOnly["default"];
            Assert.Equal(info.ZementisModeler, info2.ZementisModeler);
            info2.RepositoryServer    = "https://dlexp.zmod.org";
            nrFileReadOnly["default"] = info2;
            try {
                nrFileReadOnly.Save();
                Assert.True(false, "IOException was supposed to get thrown");
            }
            catch (IOException)
            {
                Assert.True(true);
            }
            catch (Exception ex)
            {
                Assert.True(false, $"wrong exception type {ex.GetType()} was thrown: {ex.Message}");
            }
            #endregion
            #region clean up test
            //nrFile.rm()   // not implemented
            File.Delete(nrFileNameWithPath);
            #endregion
            Assert.False(File.Exists(nrFileNameWithPath));
        }
        private string GetConnectionReference(string connectionString)
        {
            var    parts    = Parse(connectionString);
            string fileName = $"{parts.CoalesceValues("Data Source", "Server")}-{parts["User Id"]}-{parts.CoalesceValues("Database", "Catalog")}.json";
            string path     = GetSecureConnectionPath(fileName);

            JsonFile.Save(path, new ConnectionString()
            {
                Value = connectionString
            });
            return($"@{fileName}");
        }
Example #27
0
        private void SaveCurrentSolution()
        {
            if (!string.IsNullOrEmpty(SolutionFile) && _solution != null)
            {
                JsonFile.Save(SolutionFile, _solution, (settings) =>
                {
                    settings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
                });

                JsonFile.Save(_sharedExcludeFilename, _sharedExclusions);
            }
        }
Example #28
0
        protected BooliService SetUpTest(string absoluteUrl, JsonFile jsonFile)
        {
            _absoluteUrl = absoluteUrl;

            var(networkServiceMock, httpMessageHandlerMock) = NetworkHelper.SetUpNetworkServiceMock(absoluteUrl, jsonFile);
            _httpMessageHandlerMock = httpMessageHandlerMock;

            var sut = new BooliService(TestConstants.CallerId, TestConstants.Key);

            sut.BaseService.NetworkService = networkServiceMock.Object;
            return(sut);
        }
        private ColorScheme ReadColorSchemeFile()
        {
            if (!File.Exists(_pathToColorFile))
            {
                return(null);
            }

            var json   = new JsonFile <ColorScheme>();
            var scheme = json.Read(_pathToColorFile);

            return(scheme);
        }
Example #30
0
 private void SaveOptions()
 {
     _options.Weaver                 = new SimpleWeaver();
     _options.Weaver.WarpColor       = cbWarpColor.GetItem <ColorOption>().Color;
     _options.Weaver.WeftColor       = cbWeftColor.GetItem <ColorOption>().Color;
     _options.Weaver.SquareSize      = Convert.ToInt32(nudSquareSize.Value);
     _options.Weaver.Harnesses       = (dgvHarnesses.DataSource as BindingSource).OfType <SimpleWeaver.Harness>().ToList();
     _options.Weaver.DrawCoordinates = chkDrawCoordinates.Checked;
     _options.Weaver.HarnessOrder    = tbHarnessOrder.Text;
     _options.FormPosition           = FormPosition.FromForm(this);
     JsonFile.Save(OptionsFilename, _options);
 }
Example #31
0
    public void Init()
    {
#if UNITY_IOS
        GameSetting setting = JsonFile.ReadFromFile <GameSetting>("Text/", "gameSetting");
        shareText      = setting.shareText;
        shareTitle     = setting.shareTitle;
        shareImageName = setting.shareImageName;
        SetShareContent();
        shareSdk.shareHandler += ShareResultHandler;
        Mediator.AddListener(this, "share");
#endif
    }
Example #32
0
        private MessageInfo GetMessage(string code)
        {
            MessagesList rootObject = JsonFile.FromJson <MessagesList>("\\Mensajes\\MensajesJSon\\MensajeNegocio.json");
            MessageInfo  message    = rootObject.MessageInfo.FirstOrDefault(s => s.Code == code);

            if (message == null)
            {
                message = new MessageInfo();
            }

            return(message);
        }
Example #33
0
        /// <summary>
        /// Create &amp; validate subclass-only fields.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        protected override IEnumerable<CompilerError> CreateAndValidateOverride(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            values.Add(false);
            values.Add(true );

            defaultValue = false;
            AddIfNotNull(SetDefault(json), errors);

            return errors;
        }
 public static void KeyReset()
 {
     JsonFile.save.Controls.Left      = "a";
     JsonFile.save.Controls.Right     = "d";
     JsonFile.save.Controls.Up        = "w";
     JsonFile.save.Controls.Down      = "s";
     JsonFile.save.Controls.Inventory = "tab";
     JsonFile.save.Controls.Interact  = "e";
     JsonFile.save.Controls.Skip      = "space";
     JsonFile.save.Controls.Minimap   = "left shift";
     JsonFile.WriteData();
 }
Example #35
0
 private static DeployScript GetDeployScript(string[] args)
 {
     try
     {
         string fileName = args[0];
         return(JsonFile.Load <DeployScript>(fileName));
     }
     catch (Exception exc)
     {
         throw new Exception($"Couldn't open deploy script: {exc.Message}");
     }
 }
Example #36
0
        private void FormList_Load(object sender, EventArgs e)
        {
            var JsonFile = new JsonFile <CommandJsonStorage.CommandJsonObject>(Settings.Default.JsonFilePath);

            JsonFile.Read();
            if (JsonFile.Object != null)
            {
                CommandObj = JsonFile.Object;
            }

            DisplayUpdate();
        }
Example #37
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var JsonFile = new JsonFile <CommandJsonStorage.CommandJsonObject>(Settings.Default.JsonFilePath);

            if (JsonFile.Open())
            {
                Settings.Default.JsonFilePath = JsonFile.FileName;
                CommandObj = JsonFile.Object;
                Clear();
                DisplayUpdate();
            }
        }
Example #38
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            AddIfNotNull(SetJsonValue(json, "item", ref item), errors);
            AddIfNotNull(SetJsonValue(json, "weight", ref weight, 1f), errors);

            AddIfNotNull(d.ValidateStack(Building, json, ref stack), errors);
            //AddIfNotNull(SetJsonValue(json, "stack", ref stack, 1), errors);

            return errors;
        }
Example #39
0
        private void SaveFile()
        {
            try {
                AssemblyCacheFile f = new AssemblyCacheFile();
                f.Path       = Path;
                f.PathHash   = GetPathHash(Path);
                f.Assemblies = Assemblies;

                JsonFile.Write(_cacheFile, f);
            } catch {
            }
        }
        public void ShouldRemoveFromDataFile()
        {
            var file = new JsonFile<TestModel>(_testDataFileDir);
            file.Add(new TestModel { MyTest = "Bar" });

            Assert.AreEqual(2, file.Count);

            var someData = file.First(x => x.MyTest == "Bar");
            file.Remove(someData);

            Assert.AreEqual(1, file.Count);
            Assert.IsInstanceOfType(file, typeof(IList<TestModel>));
        }
Example #41
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            errors.AddRange(CreateAndValidateBase(json, "Buffs", "Buffs"));

            AddIfNotNull(SetJsonValue(json, "tip",         ref tip        ), errors);

            AddIfNotNull(SetJsonValue(json, "debuff",      ref debuff,      false), errors);
            AddIfNotNull(SetJsonValue(json, "vanityPet",   ref vanityPet,   false), errors);
            AddIfNotNull(SetJsonValue(json, "lightPet",    ref lightPet,    false), errors);
            AddIfNotNull(SetJsonValue(json, "enchantment", ref enchantment, false), errors);
            AddIfNotNull(SetJsonValue(json, "noTimer",     ref noTimer,     false), errors);

            return errors;
        }
Example #42
0
        /// <summary>
        /// Creates a new option object.
        /// </summary>
        /// <param name="mc">The <see cref="ModCompiler" /> that is compiling the <see cref="Option" />.</param>
        /// <param name="json">The JSON useto create the objects. (ModOptions.json)</param>
        /// <returns>A tuple containing the option, and a collection of errors.</returns>
        public static Tuple<Option, IEnumerable<CompilerError>> NewOption(ModCompiler mc, JsonFile json)
        {
            Dictionary<string, Func<Option>> Options = new Dictionary<string, Func<Option>>();

            // only lower-case
            Options.Add("string",     () => new StringOption    (mc));
            Options.Add("integer",    () => new IntegerOption   (mc));
            Options.Add("float",      () => new FloatOption     (mc));
            Options.Add("keybinding", () => new KeybindingOption(mc));
            Options.Add("list",       () => new ListOption      (mc));
            Options.Add("boolean",    () => new BoolOption      (mc));
            Options.Add("dynamic",    () => new DynamicOption   (mc));

            Option ret = null;
            List<CompilerError> errors = new List<CompilerError>();

            if (!json.Json.Has("type"))
                errors.Add(new CompilerError(mc.building)
                {
                    Cause = new KeyNotFoundException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "Key 'type' not found."
                });
            else
            {
                string type = ((string)json.Json["type"]).ToLowerInvariant();

                if (!Options.ContainsKey(type))
                    errors.Add(new CompilerError(mc.building)
                    {
                        Cause = new KeyNotFoundException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "Did nout found the '" + type + "' option."
                    });
                else
                {
                    Option o = Options[type]();
                    o.type = type;

                    errors.AddRange(o.CreateAndValidate(json));
                }
            }

            return new Tuple<Option, IEnumerable<CompilerError>>(ret, errors);
        }
Example #43
0
        private static void InitApiKeys()
        {
            // Check Accounts.json
            var isExists = File.Exists(Consts.FileNameAccounts);
            if( !isExists )
            {
                _apiKeys = new List<EveApiKey>();
                // Add test key
                var apiKey = new EveApiKey {KeyId = 12312, VCode ="xxxx", Name = "Test Account"};
                _apiKeys.Add(apiKey);

                return;
            }

            // If exists - load data
            var fl = new JsonFile<List<EveApiKey>> {FileName = Consts.FileNameAccounts};
            fl.OpenAndRead();
            _apiKeys = fl.GetObject();
        }
Example #44
0
        /// <summary>
        /// Sets the default value of the JSON Option object.
        /// </summary>
        /// <param name="json">The JSON object to check.</param>
        /// <returns>The (possible) compiler error.</returns>
        protected CompilerError SetDefault(JsonFile json)
        {
            if (json.Json.Has("default"))
            {
                var def = json.Json["default"];

                if (def.IsString)
                {
                    if (!values.Contains(defaultValue = (string)def))
                        return new CompilerError(Building)
                        {
                            Cause = new KeyNotFoundException(),
                            FilePath = json.Path,
                            IsWarning = false,
                            Message = "The list does not contain the value '" + defaultValue + "'."
                        };
                }
                else if (def.IsInt)
                {
                    int id = (int)(defaultValue = (int)def);

                    if (id < 0 || id >= values.Count)
                        return new CompilerError(Building)
                        {
                            Cause = new IndexOutOfRangeException(),
                            FilePath = json.Path,
                            IsWarning = false,
                            Message = "The index " + id + " is either below 0 or out of the bounds of the list."
                        };
                }
                else
                    return new CompilerError(Building)
                    {
                        Cause = new InvalidCastException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "Key 'default' is a " + def.GetJsonType() + ", not an int or a string."
                    };
            }

            return null;
        }
        /// <summary>
        /// Create &amp; validate subclass-only fields.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        protected override IEnumerable<CompilerError> CreateAndValidateOverride(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            string def = String.Empty;

            AddIfNotNull(SetJsonValue(json, "default", ref def), errors);

            Keys key;
            if (Enum.TryParse(def, true, out key))
                defaultValue = key;
            else
                errors.Add(new CompilerError(Building)
                {
                    Cause = new InvalidCastException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "Key 'default': not a valid Keys enumeration value." 
                });

            return errors;
        }
Example #46
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            AddIfNotNull(SetJsonValue(json, "catchChance", ref catchChance, 0.1f), errors);

            AddIfNotNull(SetJsonValue(json, "worldLayer", ref worldLayer), errors);
            AddIfNotNull(SetJsonValue(json, "liquidType", ref liquidType, LiquidType.Water), errors);

            AddIfNotNull(SetJsonValue(json, "biomes", ref biomes, EmptyStringArr), errors); // values are checked by the... checker

            AddIfNotNull(SetJsonValue(json, "poolCount", ref poolCount, 0), errors);

            if (poolCount < 0)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new ArgumentOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "Invalid value for property 'poolCount' " + poolCount + ", value must be equal to or greater than 0."
                });

            return errors;
        }
Example #47
0
        /// <summary>
        /// Create &amp; validate subclass-only fields.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        protected override IEnumerable<CompilerError> CreateAndValidateOverride(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            if (!json.Json.Has("list"))
                errors.Add(new CompilerError(Building)
                {
                    Cause = new KeyNotFoundException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "Key 'list' not found."
                });
            else
            {
                var list = json.Json["list"];

                for (int i = 0; i < list.Count; i++)
                    values.Add((string)list[i]);
            }

            SetDefault(json);

            return errors;
        }
Example #48
0
 private void SaveApiKeysToFile()
 {
     JsonFile<List<EveApiKey>> fl = new JsonFile<List<EveApiKey>>();
     fl.FileName = Consts.FileNameAccounts;
     fl.SetObject(apiKeysCollection.Rows.ToList());
     fl.OpenAndWrite();
 }
Example #49
0
        internal IEnumerable<CompilerError> ValidateStack(ModData Building, JsonFile json, ref int[] stack)
        {
            List<CompilerError> errors = new List<CompilerError>();

            if (!json.Json.Has("stack"))
            {
                stack = new[] { 1 };

                return errors;
            }

            JsonData jStack = json.Json["stack"];

            if (jStack.IsArray)
            {
                AddIfNotNull(SetJsonValue(json, "stack", ref stack, true, TwoOnes), errors);

                if (stack.Length != 2)
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new IndexOutOfRangeException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "Invalid length " + stack.Length + " for field 'stack'."
                    });
                if (stack[0] > stack[1])
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new ArgumentOutOfRangeException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "The minimum value of the stack cannot be greater than the maximum value."
                    });
                if (stack[0] < 0 || stack[1] < 0)
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new ArgumentOutOfRangeException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "The stack values must be greater than or equal to 0."
                    });
            }
            else
            {
                int st = 1;
                AddIfNotNull(SetJsonValue(json, "stack", ref st, 1), errors);
                stack = new[] { st };

                if (st <= 0)
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new ArgumentOutOfRangeException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "'stack' is equal to or below 0. Please remove the Drop object from the array, or change the stack."
                    });
            }


            return errors;
        }
Example #50
0
        /// <summary>
        /// Base class field validation.
        /// </summary>
        /// <param name="json">The JSON file to validate.</param>
        /// <param name="baseFolder">Used for the 'texture' key ({baseFolder}/{fileName}.png)</param>
        /// <param name="baseType">Used for the 'code' key ({internalName}.{basetype}.{fileName})</param>
        /// <returns>A collection containing all (possible) errors.</returns>
        protected IEnumerable<CompilerError> CreateAndValidateBase(JsonFile json, string baseFolder, string baseType)
        {
            List<CompilerError> errors = new List<CompilerError>();

            internalName = Building.Info.internalName + ":" + Path.GetFileNameWithoutExtension(json.Path);

            AddIfNotNull(SetJsonValue(json, "displayName", ref displayName, internalName), errors);

            AddIfNotNull(SetJsonValue(json, "code", ref code, null), errors);

            if (code == null)
            {
                code = Defs.ParseName(Building.Info.internalName) + "." + baseType + "." + Defs.ParseName(internalName);

                codeDefaultValue = true;
            }
            else if (code.Contains(':'))
                code = code.Replace(':', '.');
            else
                code = Defs.ParseName(Building.Info.internalName) + "." + code;

            string r = Path.ChangeExtension(json.Path.Substring(Building.OriginPath.Length + 1).Replace('\\', '/'), null);
            AddIfNotNull(SetJsonValue(json, "texture", ref texture, r), errors);
            if (!Building.files.ContainsKey(texture + ".png"))
                errors.Add(new CompilerError(Building)
                {
                    Cause = new FileNotFoundException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "Could not find item texture '" + texture + ".png'."
                });

            AddIfNotNull(SetJsonValue(json, "size", ref size, true, new int[2]), errors);
            if (size != null && size.Length != 2)
            {
                errors.Add(new CompilerError(Building)
                {
                    Cause = new IndexOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "'size' should be an array of ints with length 2."
                });

                size = new int[2] { 16, 16 };
            }
            AddIfNotNull(SetJsonValue(json, "width" , ref size[0], size[0]), errors);
            AddIfNotNull(SetJsonValue(json, "height", ref size[1], size[1]), errors);
            if (size[0] <= 0 || size[1] <= 0)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new ArgumentOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "Invalid item size value."
                });

            AddIfNotNull(SetJsonValue(json, "scale", ref scale, 1f), errors);

            AddIfNotNull(SetJsonValue(json, "color", ref colour, true, new int[3] { 255, 255, 255 }), errors);
            if (colour.Length < 3 || colour.Length > 4)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new IndexOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "'color' should be an array of ints with length 3 or 4."
                });
            for (int i = 0; i < colour.Length; i++)
                if (colour[i] < 0 || colour[i] > 255)
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new ArgumentOutOfRangeException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "'color[" + i + "] cannot be converted to a color channel. The value must be an element of [0;255]."
                    });

            return errors;
        }
Example #51
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            if (json.Json.Has("choose"))
            {
                JsonData jChoose = json.Json["choose"];

                usesChoose = true;

                if (!jChoose.IsArray)
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new InvalidCastException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "'choose' has to be an array of objects."
                    });

                choose = new Choice[jChoose.Count];
                for (int i = 0; i < jChoose.Count; i++)
                {
                    if (!jChoose[i].IsObject)
                        errors.Add(new CompilerError(Building)
                        {
                            Cause = new ArrayTypeMismatchException(),
                            FilePath = json.Path,
                            IsWarning = false,
                            Message = "'choose' has to be an array of objects."
                        });

                    Choice c = new Choice(Compiler);
                    c.d = this;
                    AddIfNotNull(c.CreateAndValidate(new JsonFile(json.Path, jChoose[i])), errors);
                    c.d = null;
                    choose[i] = c;
                }
            }
            else
            {
                ValidateStack(Building, json, ref stack);

                #region stack
                /*if (json.Json.Has("stack"))
                {
                    JsonData jStack = json.Json["stack"];

                    if (jStack.IsArray)
                    {
                        AddIfNotNull(SetJsonValue(json, "stack", ref stack, true, TwoOnes), errors);

                        if (stack.Length != 2)
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new IndexOutOfRangeException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "Invalid length " + stack.Length + " for field 'stack'."
                            });
                        if (stack[0] > stack[1])
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new ArgumentOutOfRangeException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "The minimum value of the stack cannot be greater than the maximum value."
                            });
                        if (stack[0] < 0 || stack[1] < 0)
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new ArgumentOutOfRangeException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "The stack values must be greater than or equal to 0."
                            });
                    }
                    else
                    {
                        int st = 1;
                        AddIfNotNull(SetJsonValue(json, "stack", ref st, 1), errors);
                        stack = new[] { st };

                        if (st <= 0)
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new ArgumentOutOfRangeException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "'stack' is equal to or below 0. Please remove the Drop object from the array, or change the stack."
                            });
                    }
                }*/
                #endregion

                AddIfNotNull(SetJsonValue(json, "item", ref item), errors);
            }

            AddIfNotNull(SetJsonValue(json, "chance", ref chance, 1f), errors);
            if (chance > 1f)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new ArgumentOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = true,
                    Message = "'chance' is above 1. Set it to 1."
                });
            if (chance <= 0f)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new ArgumentOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = true,
                    Message = "'chance' is equal to or below 0. Please remove the Drop object from the array, or change it."
                });

            return errors;
        }
Example #52
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            errors.AddRange(CreateAndValidateBase(json, "Items", "Items"));

            #region informative
            AddIfNotNull(SetJsonValue(json, "rare", ref rare, 0), errors);
            #region tooltip
            if (json.Json.Has("tooltip"))
            {
                JsonData tt = json.Json["tooltip"];

                if (tt.IsString)
                    tooltip.Add((string)tt);
                else if (tt.IsArray)
                {
                    List<string> tips = new List<string>();

                    for (int i = 0; i < tt.Count; i++)
                    {
                        JsonData tip = tt[i];

                        if (!tip.IsString)
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new ArrayTypeMismatchException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "'tooltip[" + i + "]' should be a string, but is a " + tip.GetJsonType() + "."
                            });
                        else
                            tips.Add((string)tip);
                    }

                    for (int i = 0; i < tips.Count; i++)
                        tooltip.Add(tips[i]);
                }
                else
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new InvalidCastException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "'tooltip' should be a string or an array of strings, but is a " + tt.GetJsonType() + "."
                    });
            }
            #endregion
            #region value
            if (json.Json.Has("value"))
            {
                JsonData v = json.Json["value"];

                if (v.IsInt)
                    value = (int)v;
                else if (v.IsArray)
                {
                    if (v.Count > 4)
                        errors.Add(new CompilerError(Building)
                        {
                            Cause = new IndexOutOfRangeException(),
                            FilePath = json.Path,
                            IsWarning = false,
                            Message = "'value' array's length should be ranging from 0 to 4."
                        });

                    int[] values  = new int[4]; // structs, no init needed

                    for (int i = 0; i < v.Count; i++)
                    {
                        JsonData val = v[i];

                        if (!val.IsInt)
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new ArrayTypeMismatchException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "'value[" + i + "]' should be an int, but is a " + val.GetJsonType() + "."
                            });
                        else
                            values[i] = (int)val;
                    }

                    value += values[0] * 1000000; // p
                    value += values[1] * 10000;   // g
                    value += values[2] * 100;     // s
                    value += values[3] * 1;       // c
                }
                else
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new InvalidCastException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "'value' should be an int or an array of ints, but is a " + v.GetJsonType() + "."
                    });
            }
            #endregion
            AddIfNotNull(SetJsonValue(json, "maxStack", ref maxStack, 1), errors);
            AddIfNotNull(SetJsonValue(json, "notMaterial", ref notMaterial, false), errors);
            #region recipes
            if (json.Json.Has("recipes"))
            {
                JsonData recs = json.Json["recipes"];

                if (recs.IsArray)
                    for (int i = 0; i < recs.Count; i++)
                    {
                        if (!recs[i].IsObject)
                        {
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new ArrayTypeMismatchException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "'recipes[" + i + "]' is a " + recs[i].GetJsonType() + ", not a Recipe."
                            });

                            continue;
                        }

                        Recipe r = new Recipe(Compiler);

                        errors.AddRange(r.CreateAndValidate(new JsonFile(json.Path, recs[i])));
                        recipes.Add(r);
                    }
                else
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new InvalidCastException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "Key 'recipes' is a " + recs.GetJsonType() + ", not an array of Recipes."
                    });
            }
            #endregion
            #endregion

            // appearance
            AddIfNotNull(SetJsonValue(json, "noUseGraphic", ref noUseGraphic, false), errors);

            #region armour
            AddIfNotNull(SetJsonValue(json, "accessory", ref accessory, false), errors);
            AddIfNotNull(SetJsonValue(json, "defense", ref defense, 0), errors);
            AddIfNotNull(SetJsonValue(json, "lifeRegen", ref lifeRegen, 0), errors);
            AddIfNotNull(SetJsonValue(json, "manaIncrease", ref manaIncrease, 0), errors);
            AddIfNotNull(SetJsonValue(json, "tileBoost", ref tileBoost, 0), errors);
            AddIfNotNull(SetJsonValue(json, "setName", ref setName, String.Empty), errors);
            AddIfNotNull(SetJsonValue(json, "vanity", ref vanity, false), errors);
            AddIfNotNull(SetJsonValue(json, "armorHead", ref armorHead, false), errors);
            AddIfNotNull(SetJsonValue(json, "armorBody", ref armorBody, false), errors);
            AddIfNotNull(SetJsonValue(json, "armorLegs", ref armorLegs, false), errors);
            AddIfNotNull(SetJsonValue(json, "textureHead", ref textureHead, texture + "._Head"), errors);
            AddIfNotNull(SetJsonValue(json, "textureBody", ref textureBody, texture + "._Body"), errors);
            AddIfNotNull(SetJsonValue(json, "textureLegs", ref textureLegs, texture + "._Legs"), errors);
            AddIfNotNull(SetJsonValue(json, "textureFemale", ref textureFemale, textureBody + "_Female"), errors);
            AddIfNotNull(SetJsonValue(json, "textureArm", ref textureArm, texture + "._Arm"), errors);
            AddIfNotNull(SetJsonValue(json, "hairType", ref hairType, 0), errors);
            if (hairType < 0 || hairType > 3)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new ArgumentOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "'hairType': invalid value. The value must be an element of [0;3]."
                });
            AddIfNotNull(SetJsonValue(json, "hasHands", ref hasHands, false), errors);
            #endregion

            #region use
            AddIfNotNull(SetJsonValue(json, "useStyle", ref useStyle, 0), errors);
            if (useStyle < 0 || useStyle > 5)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new ArgumentOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "'useStyle': invalid value. The value must be an element of [0;5]."
                });
            AddIfNotNull(SetJsonValue(json, "holdStyle", ref holdStyle, 0), errors);
            if (holdStyle < 0 || holdStyle > 2)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new ArgumentOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "'holdStyle': invalid value. The value must be an element of [0;2]."
                });
            AddIfNotNull(SetJsonValue(json, "useTime", ref useTime, 100), errors);
            if (useTime <= 0)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new ArgumentOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "'useTime': invalid value. The value must be grater than 0."
                });
            AddIfNotNull(SetJsonValue(json, "useAnimation", ref useAnimation, 100), errors);
            if (useTime <= 0)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new ArgumentOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "'useAnimation': invalid value. The value must be grater than 0."
                });
            AddIfNotNull(SetJsonValue(json, "holdoutOffset", ref holdoutOffset, new float[2]), errors);
            if (holdoutOffset.Length != 2)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new IndexOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "'holdoutOffset': array length must be 2."
                });
            AddIfNotNull(SetJsonValue(json, "holdoutOrigin", ref holdoutOrigin, new float[2]), errors);
            if (holdoutOrigin.Length != 2)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new IndexOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "'holdoutOrigin': array length must be 2."
                });
            AddIfNotNull(SetJsonValue(json, "reuseDelay", ref reuseDelay, 0), errors);
            AddIfNotNull(SetJsonValue(json, "channel", ref channel, false), errors);
            AddIfNotNull(SetJsonValue(json, "pick", ref pick, 0), errors);
            AddIfNotNull(SetJsonValue(json, "axe", ref axe, 0), errors);
            AddIfNotNull(SetJsonValue(json, "hammer", ref hammer, 0), errors);
            AddIfNotNull(SetJsonValue(json, "autoReuse", ref autoReuse, false), errors);
            AddIfNotNull(SetJsonValue(json, "useTurn", ref useTurn, false), errors);
            AddIfNotNull(SetJsonValue(json, "useSound", ref useSound, useSound), errors);
            AddIfNotNull(SetJsonValue(json, "mana", ref mana, 0), errors);
            AddIfNotNull(SetJsonValue(json, "consumable", ref consumable, false), errors);
            #endregion

            #region combat
            AddIfNotNull(SetJsonValue(json, "noMelee", ref noMelee, false), errors);
            AddIfNotNull(SetJsonValue(json, "melee", ref melee, false), errors);
            AddIfNotNull(SetJsonValue(json, "ranged", ref ranged, false), errors);
            AddIfNotNull(SetJsonValue(json, "magic", ref magic, false), errors);
            AddIfNotNull(SetJsonValue(json, "summon", ref summon, false), errors);
            AddIfNotNull(SetJsonValue(json, "damage", ref damage, 0), errors);
            AddIfNotNull(SetJsonValue(json, "crit", ref crit, 4), errors);
            AddIfNotNull(SetJsonValue(json, "knockback", ref knockback, 0), errors);
            AddIfNotNull(SetJsonValue(json, "shoot", ref shoot, shoot), errors);
            AddIfNotNull(SetJsonValue(json, "shootSpeed", ref shootSpeed, 1f), errors);
            AddIfNotNull(SetJsonValue(json, "useAmmo", ref useAmmo, useAmmo), errors);
            AddIfNotNull(SetJsonValue(json, "ammo", ref ammo, ammo), errors);
            AddIfNotNull(SetJsonValue(json, "notAmmo", ref notAmmo, false), errors);
            #endregion

            #region potion
            AddIfNotNull(SetJsonValue(json, "potion", ref potion, false), errors);
            AddIfNotNull(SetJsonValue(json, "healLife", ref healLife, 0), errors);
            AddIfNotNull(SetJsonValue(json, "healMana", ref healMana, 0), errors);

            AddIfNotNull(SetJsonValue(json, "buff", ref buff, buff), errors);

            AddIfNotNull(SetJsonValue(json, "buffTime", ref buffTime, 0), errors);
            #endregion

            #region tile
            AddIfNotNull(SetJsonValue(json, "createTile", ref createTile, createTile), errors);
            AddIfNotNull(SetJsonValue(json, "tileWand", ref tileWand, tileWand), errors);
            AddIfNotNull(SetJsonValue(json, "createWall", ref createWall, createWall), errors);

            AddIfNotNull(SetJsonValue(json, "placeStyle", ref placeStyle, 0), errors);
            #endregion

            #region 1.2.4.1 stuff
            AddIfNotNull(SetJsonValue(json, "questItem", ref questItem, false), errors);

            if (questItem)
                AddIfNotNull(SetJsonValue(json, "questAnglerText", ref questAnglerText, defaultAnglerText), errors);

            AddIfNotNull(SetJsonValue(json, "fishingPole", ref fishingPole, 0), errors);

            if (fishingPole > 0)
            {
                AddIfNotNull(SetJsonValue(json, "lavaRod", ref lavaRod, false), errors);
                AddIfNotNull(SetJsonValue(json, "honeyRod", ref honeyRod, true), errors);
                AddIfNotNull(SetJsonValue(json, "waterRod", ref waterRod, true), errors);
            }

            AddIfNotNull(SetJsonValue(json, "bait", ref bait, 0), errors);

            if (json.Json.Has("fish"))
            {
                fish = new Fish(Compiler);

                fish.CreateAndValidate(new JsonFile(json.Path, json.Json["fish"])); // press F12 here
            }

            AddIfNotNull(SetJsonValue(json, "autoSelect", ref autoSelect, String.Empty), errors);

            AddIfNotNull(SetJsonValue(json, "makeNpc", ref makeNpc, 0), errors);

            AddIfNotNull(SetJsonValue(json, "wings", ref wings, false), errors);

            if (wings)
            {
                AddIfNotNull(SetJsonValue(json, "wingTime", ref wingTime, 0), errors);
                AddIfNotNull(SetJsonValue(json, "wingSpeedMax", ref wingSpeedMax, 0f), errors);
                AddIfNotNull(SetJsonValue(json, "wingRateMult", ref wingRateMult, 1f), errors);

                AddIfNotNull(SetJsonValue(json, "textureWings", ref textureWings, texture + "_Wings"), errors);
            }

            if (accessory)
            {
                AddIfNotNull(SetJsonValue(json, "textureHandsOn", ref textureHandsOn, String.Empty), errors);
                AddIfNotNull(SetJsonValue(json, "textureHandsOff", ref textureHandsOff, String.Empty), errors);
                AddIfNotNull(SetJsonValue(json, "textureNeck", ref textureNeck, String.Empty), errors);
                AddIfNotNull(SetJsonValue(json, "textureBack", ref textureBack, String.Empty), errors);
                AddIfNotNull(SetJsonValue(json, "textureShoes", ref textureShoes, String.Empty), errors);
                AddIfNotNull(SetJsonValue(json, "textureWaist", ref textureWaist, String.Empty), errors);
                AddIfNotNull(SetJsonValue(json, "textureShield", ref textureShield, String.Empty), errors);
                AddIfNotNull(SetJsonValue(json, "textureFace", ref textureFace, String.Empty), errors);
                AddIfNotNull(SetJsonValue(json, "textureBalloon", ref textureBalloon, String.Empty), errors);
            }
            #endregion

            return errors;
        }
Example #53
0
		public void TestJsonHasOneNode()
		{
			var file = new JsonFile(TestFilename);
			Assert.AreEqual(1, file.Root.NumberOfNodes);
		}
Example #54
0
 /// <summary>
 /// Create &amp; validate subclass-only fields.
 /// </summary>
 /// <param name="json">The json to validate</param>
 /// <returns>A collection of all validation errors.</returns>
 protected abstract IEnumerable<CompilerError> CreateAndValidateOverride(JsonFile json);
Example #55
0
 /// <summary>
 /// Create &amp; validate subclass-only fields.
 /// </summary>
 /// <param name="json">The json to validate</param>
 /// <returns>A collection of all validation errors.</returns>
 protected override IEnumerable<CompilerError> CreateAndValidateOverride(JsonFile json)
 {
     return errors;
 }
Example #56
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            errors.AddRange(CreateAndValidateBase(json, "NPC", "NPCs"));

            AddIfNotNull(SetJsonValue(json, "netAlways", ref netAlways, false), errors);

            // informative
            AddIfNotNull(SetJsonValue(json, "occupation",  ref occupation,  Path.GetFileNameWithoutExtension(json.Path)), errors);
            #region value
            if (json.Json.Has("value"))
            {
                JsonData v = json.Json["value"];

                if (v.IsInt)
                    value = (int)v;
                else if (v.IsArray)
                {
                    if (v.Count > 4)
                        errors.Add(new CompilerError(Building)
                        {
                            Cause = new IndexOutOfRangeException(),
                            FilePath = json.Path,
                            IsWarning = false,
                            Message = "'value' array's length should be ranging from 0 to 4."
                        });

                    int[] values  = new int[4]; // structs, no init needed

                    for (int i = 0; i < v.Count; i++)
                    {
                        JsonData val = v[i];

                        if (!val.IsInt)
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new ArrayTypeMismatchException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "'value[" + i + "]' should be an int, but is a " + val.GetJsonType() + "."
                            });
                        else
                            values[i] = (int)val;
                    }

                    value += values[0] * 1000000; // p
                    value += values[1] * 10000;   // g
                    value += values[2] * 100;     // g
                    value += values[3] * 1;       // g
                }
                else
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new InvalidCastException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "'value' should be an int or an array of ints, but is a " + v.GetJsonType() + "."
                    });
            }
            #endregion

            // stats
            AddIfNotNull(SetJsonValue(json, "lifeMax", ref lifeMax), errors);
            AddIfNotNull(SetJsonValue(json, "damage", ref damage, 0), errors);
            AddIfNotNull(SetJsonValue(json, "defense", ref defense, 0), errors);
            AddIfNotNull(SetJsonValue(json, "knockbackResist", ref knockbackResist, 1f), errors);
            AddIfNotNull(SetJsonValue(json, "critChance", ref critChance, 4), errors);
            AddIfNotNull(SetJsonValue(json, "critMult", ref critMult, 4), errors);

            // gameplay
            AddIfNotNull(SetJsonValue(json, "npcSlots", ref npcSlots, 1f), errors);
            AddIfNotNull(SetJsonValue(json, "aiStyle", ref aiStyle, 0), errors);
            AddIfNotNull(SetJsonValue(json, "friendly", ref friendly, false), errors);
            AddIfNotNull(SetJsonValue(json, "townNPC", ref townNPC, false), errors);
            AddIfNotNull(SetJsonValue(json, "male", ref male, true /* based on the vanilla male/female raito + default value of the field, don't sue me because of this */), errors);
            AddIfNotNull(SetJsonValue(json, "boss", ref boss, false), errors);
            AddIfNotNull(SetJsonValue(json, "dontTakeDamage", ref dontTakeDamage, false), errors);
            AddIfNotNull(SetJsonValue(json, "lavaImmune", ref lavaImmune, false), errors);
            AddIfNotNull(SetJsonValue(json, "noGravity", ref noGravity, false), errors);
            AddIfNotNull(SetJsonValue(json, "noTileCollide", ref noTileCollide, false), errors);
			AddIfNotNull(SetJsonValue(json, "catchItem", ref catchItem, catchItem), errors);

			// appearance
			AddIfNotNull(SetJsonValue(json, "frameCount", ref frameCount, 1), errors);
            AddIfNotNull(SetJsonValue(json, "animationStyle", ref animationStyle, 0), errors);
            AddIfNotNull(SetJsonValue(json, "behindTiles", ref behindTiles, false), errors);
            AddIfNotNull(SetJsonValue(json, "alpha", ref alpha, 0), errors);

            // interface
            AddIfNotNull(SetJsonValue(json, "textureHead", ref textureHead, texture + "._Head"), errors);
            if (townNPC && !Building.files.ContainsKey(textureHead))
                errors.Add(new CompilerError(Building)
                {
                    Cause = new FileNotFoundException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "'textureHead': file " + textureHead + " not found."
                });
            AddIfNotNull(SetJsonValue(json, "shop", ref shop, false), errors);
            AddIfNotNull(SetJsonValue(json, "showHealthBar", ref showHealthBar, true), errors);
            AddIfNotNull(SetJsonValue(json, "lifeBarScale", ref lifeBarScale, 1f), errors);
            AddIfNotNull(SetJsonValue(json, "realLifeHealthBar", ref realLifeHealthBar, false), errors);

            if (json.Json.Has("buffImmune"))
            {
                JsonData j = json.Json["buffImmune"];

                if (!j.IsArray)
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new ArrayTypeMismatchException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "'buffImmune must be an array, but is a " + j.GetType()
                    });
                else
                    for (int i = 0; i < j.Count; i++)
                        if (j[i].IsString)
                            buffImmune.Add((string)j[i]);
                        else if (j[i].IsInt)
                            buffImmune.Add((int   )j[i]);
                        else
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new ArrayTypeMismatchException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "'buffImmune['" + i + "]' must be an int or a string, but is a " + buffImmune[i].GetType()
                            });
            }

            AddIfNotNull(SetJsonValue(json, "soundHit", ref soundHit, soundHit), errors);
            AddIfNotNull(SetJsonValue(json, "soundKilled", ref soundKilled, soundKilled), errors);
            AddIfNotNull(SetJsonValue(json, "music", ref music, String.Empty), errors);

            #region drops
            if (json.Json.Has("drops"))
            {
                JsonData drps = json.Json["drops"]; // I read this as 'derps' instead of 'drops' .__.

                if (drps.IsObject)
                    drps = JsonMapper.ToObject("[" + drps.ToJson() + "]");

                if (drps.IsArray)
                    for (int i = 0; i < drps.Count; i++)
                    {
                        JsonData drop = drps[i];

                        if (drop.IsObject)
                        {
                            Drop d = new Drop(Compiler);

                            errors.AddRange(d.CreateAndValidate(new JsonFile(json.Path, drop)));
                            drops.Add(d);
                        }
                        else
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new ArrayTypeMismatchException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "'drops[" + i + "]' must be a Drop, but is a " + drop.GetJsonType() + "."
                            });
                    }
                else
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new InvalidCastException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "'drops' must be a Drop or an array of drops, but is a " + drps.GetJsonType() + "."
                    });
            }
            #endregion

            return errors;
        }
Example #57
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            AddIfNotNull(SetJsonValue(json, "notify",      ref notify,      true        ), errors);
            AddIfNotNull(SetJsonValue(json, "sync",        ref sync,        true        ), errors);
            AddIfNotNull(SetJsonValue(json, "name",        ref name                     ), errors);
            AddIfNotNull(SetJsonValue(json, "toolTip",     ref toolTip,     String.Empty), errors);
            AddIfNotNull(SetJsonValue(json, "displayName", ref displayName, name        ), errors);

            errors.AddRange(CreateAndValidateOverride(json));

            return errors;
        }
Example #58
0
        /// <summary>
        /// Create &amp; validate a JSON file.
        /// </summary>
        /// <param name="json">The json to validate</param>
        /// <returns>A collection of all validation errors.</returns>
        public override IEnumerable<CompilerError> CreateAndValidate(JsonFile json)
        {
            List<CompilerError> errors = new List<CompilerError>();

            #region items
            if (json.Json.Has("items"))
            {
                if (!json.Json["items"].IsObject)
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new InvalidCastException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "'items' is a " + json.Json["items"].GetJsonType() + ", not an object."
                    });
                else
                {
                    JsonData its = json.Json["items"];

                    foreach (KeyValuePair<string, JsonData> kvp in its)
                    {
                        if (items.ContainsKey(kvp.Key))
                        {
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new ArgumentException(),
                                FilePath = json.Path,
                                IsWarning = true,
                                Message = "The key '" + kvp.Key + " is already present in the items list, adding the two stacks..."
                            });

                            if (!kvp.Value.IsInt)
                                errors.Add(new CompilerError(Building)
                                {
                                    Cause = new InvalidCastException(),
                                    FilePath = json.Path,
                                    IsWarning = false,
                                    Message = "The key '" + kvp.Key + " 's value should be an int, not a "
                                              + (kvp.Value is JsonData ? ((JsonData)kvp.Value).GetJsonType() : (object)kvp.Value.GetType()) + "."
                                });
                            else
                                items[kvp.Key.ToString()] += (int)kvp.Value;
                        }
                        else if (!kvp.Value.IsInt)
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new InvalidCastException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "The key '" + kvp.Key + " 's value should be an int, not a "
                                          + (kvp.Value is JsonData ? ((JsonData)kvp.Value).GetJsonType() : (object)kvp.Value.GetType()) + "."
                            });
                        else
                            items.Add(kvp.Key.ToString(), (int)kvp.Value);
                    }
                }
            }
            else
                errors.Add(new CompilerError(Building)
                {
                    Cause = new KeyNotFoundException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "Required key 'items' not found."
                });

            if (items.Count == 0)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new InvalidCastException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "The Recipe does not contain any items."
                });
            #endregion
            #region tiles
            if (json.Json.Has("tiles"))
            {
                if (!json.Json["tiles"].IsArray)
                    errors.Add(new CompilerError(Building)
                    {
                        Cause = new InvalidCastException(),
                        FilePath = json.Path,
                        IsWarning = false,
                        Message = "Key 'tiles' is a " + json.Json["tiles"] + ", not an array of strings."
                    });
                else
                {
                    JsonData tis = json.Json["tiles"];

                    for (int i = 0; i < tis.Count; i++)
                    {
                        if (!tis[i].IsString)
                        {
                            errors.Add(new CompilerError(Building)
                            {
                                Cause = new InvalidCastException(),
                                FilePath = json.Path,
                                IsWarning = false,
                                Message = "'tiles[" + i + "]' is a " + tis[i].GetJsonType() + ", not a string."
                            });

                            continue;
                        }

                        if (!tiles.Contains((string)tis[i]))
                            tiles.Add((string)tis[i]);
                    }
                }
            }
            else
                errors.Add(new CompilerError(Building)
                {
                    Cause = new KeyNotFoundException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "Required key 'tiles' not found."
                });

            if (tiles.Count == 0)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new KeyNotFoundException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "The Recipe does not contain any tiles."
                });
            #endregion

            AddIfNotNull(SetJsonValue(json, "creates", ref creates, 1), errors);
            if (creates <= 0)
                errors.Add(new CompilerError(Building)
                {
                    Cause = new ArgumentOutOfRangeException(),
                    FilePath = json.Path,
                    IsWarning = false,
                    Message = "'creates' is equal to or below 0. Please remove the Recipe object from the array, or change it."
                });

            return errors;
        }
 public override void InitiateJsonFiles()
 {
     this.SomeTestData = new JsonFile<TestModel>(this.dataDirectory);
     this.MoreTestData = new JsonFile<TestModel2>(this.dataDirectory);
 }
Example #60
0
		public void LoadNodeFromTestJson()
		{
			var file = new JsonFile(TestFilename);
			Assert.AreEqual(6, file.Root.Get<int>("SomeData"));
		}